Compare commits
6 Commits
Author | SHA1 | Date | |
---|---|---|---|
6cd26a88ea | |||
293b5af3ff | |||
022ba575b7 | |||
643c3e714f | |||
db2864395c | |||
1cd06d5fe6 |
@ -122,4 +122,34 @@ 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;
|
||||
$where = array_values(array_walk($where, function(&$item, $key) {
|
||||
$item = [$key, $item];
|
||||
}));
|
||||
$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();
|
||||
}
|
||||
}
|
||||
|
@ -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;
|
||||
}
|
||||
|
Reference in New Issue
Block a user