Files
models/src/Alias/Model.php

90 lines
2.1 KiB
PHP
Raw Normal View History

2022-09-08 21:35:33 -04:00
<?php
namespace ProVM\Alias;
use ProVM\Concept\Model\Repository;
2022-09-08 21:35:33 -04:00
use ProVM\Concept\Model as ModelInterface;
abstract class Model implements ModelInterface
{
protected Repository $repository;
public function setRepository(Repository $repository): ModelInterface
2022-09-08 21:35:33 -04:00
{
$this->repository = $repository;
2022-09-08 21:35:33 -04:00
return $this;
}
public function getRepository(): Repository
2022-09-08 21:35:33 -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()) {
$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
{
$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()));
if (!isset($this->{$p})) {
continue;
}
$output[$p] = $this->{$method->getName()}();
}
return $output;
2022-09-09 13:15:27 -04:00
}
2022-09-08 21:35:33 -04:00
}