Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created November 25, 2019 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kobus1998/57f0818b56939c96be9a7d36d93a0361 to your computer and use it in GitHub Desktop.
Save kobus1998/57f0818b56939c96be9a7d36d93a0361 to your computer and use it in GitHub Desktop.
entity
<?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