10 Commits

6 changed files with 44 additions and 7 deletions

View File

@ -122,4 +122,35 @@ abstract class Model extends BaseModel implements ModelInterface {
public function toArray(): array {
return $this->asArray();
}
protected static function parseInput($input): array {
return array_intersect_key((array) $input, array_combine(static::$fields, static::$fields));
}
public static function add(ModelFactory $factory, $input): ?ModelInterface {
$data = static::parseInput($input);
$class = get_called_class();
if (method_exists($class, 'find')) {
$obj = static::find($factory, $input);
} else {
$where = $data;
array_walk($where, function(&$item, $key) {
$item = [$key, $item];
});
$where = array_values($where);
$obj = $factory->find($class)->where($where)->one();
}
if ($obj === null) {
$obj = $factory->create($class, $data);
}
return $obj;
}
public function edit($input): bool {
$data = static::parseInput($input);
foreach (static::$fields as $field) {
if ($this->{$field} != $data[$field]) {
$this->{$field} = $data[$field];
}
}
return $this->save();
}
}

View File

@ -11,4 +11,7 @@ interface Model {
public function siblingOf(string $sibling_model_class, string $connecting_table, array $relation_definitions): ?array;
public function toArray(): array;
public static function add(ModelFactory $factory, $input): ?Model;
public function edit($input): bool;
}

View File

@ -4,7 +4,7 @@ namespace ProVM\Common\Define\Model;
use Carbon\Carbon;
trait Date {
public function date(\DateTime $date) {
public function date(\DateTime $date = null) {
if ($date === null) {
return Carbon::parse($this->date);
}

View File

@ -4,7 +4,7 @@ namespace ProVM\Common\Define\Model;
use Carbon\Carbon;
trait DateTime {
public function date(\DateTime $date_time) {
public function dateTime(\DateTime $date_time = null) {
if ($date_time === null) {
return Carbon::parse($this->date_time);
}

View File

@ -4,7 +4,7 @@ namespace ProVM\Common\Define\Model;
use Carbon\Carbon;
trait Time {
public function date(\DateTime $time) {
public function time(\DateTime $time = null) {
if ($time === null) {
return Carbon::parse($this->time);
}

View File

@ -81,7 +81,7 @@ class Model {
'to' => $j['to'] ?? $j[2],
'sym' => $j['sym'] ?? ($j[3] ?? '='),
'alias' => $j['alias'] ?? '',
'type' => strtolower($j['type']) ?? '',
'type' => strtolower($j['type'] ?? ''),
'params' => $j['params'] ?? ''
];
$this->joins []= $join;
@ -98,7 +98,7 @@ class Model {
'column' => $c['column'] ?? $c[0],
'value' => $c['value'] ?? $c[1],
'sym' => strtolower($c['sym'] ?? ($c[2] ?? '=')),
'type' => strtolower($c['type']) ?? ''
'type' => strtolower($c['type'] ?? '')
];
$this->conditions []= $cond;
}
@ -363,10 +363,13 @@ class Model {
return $results;
}
public function array(): ?array {
$results = $this->build()->findArray();
if (!$results) {
$results = $this->many();
if (!$results or $results === null) {
return null;
}
array_walk($results, function(&$item) {
$item = $item->toArray();
});
return $results;
}