Created
November 25, 2019 15:56
-
-
Save kobus1998/57f0818b56939c96be9a7d36d93a0361 to your computer and use it in GitHub Desktop.
entity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
abstract class Entity | |
{ | |
abstract public function config(): array; | |
public function validate() | |
{ | |
$config = $this->config(); | |
$errors = []; | |
foreach($this as $field => $value) | |
{ | |
$type = $config[$field] ?? null; | |
if ($type === null) { | |
continue; | |
} | |
$fun = "is_" . strtolower($type); | |
if (function_exists($fun)) { | |
if (!$fun($value)) { | |
$errors[$field] = false; | |
continue; | |
} | |
} | |
if (class_exists($type)) { | |
if (!is_a($type, $value)) { | |
$errors[$field] = false; | |
continue; | |
} | |
} | |
if (!$type === $value) { | |
$errors[$field] = false; | |
} | |
} | |
return $errors; | |
} | |
public static function fromArray($a) | |
{ | |
$s = get_called_class(); | |
$o = new $s(); | |
foreach($a as $k => $v) { | |
$o->{$k} = $v; | |
} | |
return $o; | |
} | |
} | |
class User extends Entity | |
{ | |
public function config(): array | |
{ | |
return [ | |
'id' => 'int', | |
'name' => 'string' | |
]; | |
} | |
} | |
$o = User::fromArray([ | |
'id' => 123, | |
'name' => '123' | |
]); | |
$err = $o->validate(); | |
print_r($err); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment