Add and Edit Model
This commit is contained in:
@ -122,4 +122,34 @@ abstract class Model extends BaseModel implements ModelInterface {
|
|||||||
public function toArray(): array {
|
public function toArray(): array {
|
||||||
return $this->asArray();
|
return $this->asArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected static function parseInput($input): array {
|
||||||
|
return array_intersect_key((array) $input, array_combine(self::$fields, self::$fields));
|
||||||
|
}
|
||||||
|
public static function add(ModelFactory $factory, $input): bool {
|
||||||
|
$data = self::parseInput($input);
|
||||||
|
$class = get_called_class();
|
||||||
|
if (method_exists($class, 'find')) {
|
||||||
|
$obj = self::find($input);
|
||||||
|
} else {
|
||||||
|
$obj = $factory->find($class)->where($data)->one();
|
||||||
|
}
|
||||||
|
if ($obj === false) {
|
||||||
|
$obj = $factory->create($class, $data);
|
||||||
|
return $obj->save();
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
public function edit($input): bool {
|
||||||
|
$data = self::parseInput($input);
|
||||||
|
foreach (self::$fields as $field) {
|
||||||
|
if ($this->{$field} != $data[$field]) {
|
||||||
|
$this->{$field} = $data[$field];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($this->isDirty()) {
|
||||||
|
return $this->save();
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -11,4 +11,7 @@ interface Model {
|
|||||||
public function siblingOf(string $sibling_model_class, string $connecting_table, array $relation_definitions): ?array;
|
public function siblingOf(string $sibling_model_class, string $connecting_table, array $relation_definitions): ?array;
|
||||||
|
|
||||||
public function toArray(): array;
|
public function toArray(): array;
|
||||||
|
|
||||||
|
public static function add(ModelFactory $factory, $input): bool;
|
||||||
|
public function edit($input): bool;
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user