2022-09-08 21:35:33 -04:00
|
|
|
<?php
|
|
|
|
namespace ProVM\Alias;
|
|
|
|
|
2022-09-09 15:55:45 -04:00
|
|
|
use ProVM\Concept\Model\Repository;
|
2022-09-08 21:35:33 -04:00
|
|
|
use ProVM\Concept\Model as ModelInterface;
|
|
|
|
|
|
|
|
abstract class Model implements ModelInterface
|
|
|
|
{
|
2022-09-09 15:55:45 -04:00
|
|
|
protected Repository $repository;
|
|
|
|
public function setRepository(Repository $repository): ModelInterface
|
2022-09-08 21:35:33 -04:00
|
|
|
{
|
2022-09-09 15:55:45 -04:00
|
|
|
$this->repository = $repository;
|
2022-09-08 21:35:33 -04:00
|
|
|
return $this;
|
|
|
|
}
|
2022-09-09 15:55:45 -04:00
|
|
|
public function getRepository(): Repository
|
2022-09-08 21:35:33 -04:00
|
|
|
{
|
2022-09-09 15:55:45 -04:00
|
|
|
return $this->repository;
|
2022-09-08 21:35:33 -04:00
|
|
|
}
|
|
|
|
protected int $id;
|
|
|
|
public function setId(int $id): ModelInterface
|
|
|
|
{
|
|
|
|
$this->id = $id;
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
public function getId(): int
|
|
|
|
{
|
|
|
|
return $this->id;
|
|
|
|
}
|
|
|
|
protected bool $new;
|
|
|
|
public function setNew(): ModelInterface
|
|
|
|
{
|
|
|
|
$this->new = true;
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
public function isNew(): bool
|
|
|
|
{
|
|
|
|
return $this->new ?? false;
|
|
|
|
}
|
|
|
|
protected bool $dirty;
|
|
|
|
public function setDirty(): ModelInterface
|
|
|
|
{
|
|
|
|
$this->dirty = true;
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
public function isDirty(): bool
|
|
|
|
{
|
|
|
|
return $this->dirty ?? $this->isNew();
|
|
|
|
}
|
|
|
|
|
|
|
|
public function save(): void
|
|
|
|
{
|
|
|
|
if ($this->isDirty()) {
|
2022-09-09 15:55:45 -04:00
|
|
|
$this->getRepository()->save($this);
|
2022-09-08 21:35:33 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
public function edit(array $data): void
|
|
|
|
{
|
|
|
|
foreach ($data as $key => $val) {
|
|
|
|
$m = 'set' . ucwords($key);
|
|
|
|
$this->{$m}($val);
|
|
|
|
}
|
|
|
|
$this->isDirty();
|
|
|
|
}
|
2022-09-09 13:15:27 -04:00
|
|
|
public function delete(): void
|
|
|
|
{
|
2022-09-09 15:55:45 -04:00
|
|
|
$this->getRepository()->delete($this);
|
|
|
|
}
|
|
|
|
|
|
|
|
public function jsonSerialize(): mixed
|
|
|
|
{
|
|
|
|
$obj = new \ReflectionObject($this);
|
|
|
|
$methods = $obj->getMethods();
|
|
|
|
$output = [];
|
|
|
|
foreach ($methods as $method) {
|
|
|
|
if (!str_contains($method->getName(), 'get')) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
if ($method->getName() === 'getRepository') {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
$p = strtolower(str_replace('get', '', $method->getName()));
|
2022-09-09 17:47:46 -04:00
|
|
|
if (!isset($this->{$p})) {
|
|
|
|
continue;
|
|
|
|
}
|
2022-09-09 15:55:45 -04:00
|
|
|
$output[$p] = $this->{$method->getName()}();
|
|
|
|
}
|
|
|
|
return $output;
|
2022-09-09 13:15:27 -04:00
|
|
|
}
|
2022-09-08 21:35:33 -04:00
|
|
|
}
|