-
-
Notifications
You must be signed in to change notification settings - Fork 657
Expand file tree
/
Copy pathAbstractDomainObject.php
More file actions
53 lines (45 loc) · 1.78 KB
/
AbstractDomainObject.php
File metadata and controls
53 lines (45 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
namespace HiEvents\DomainObjects;
use HiEvents\DomainObjects\Interfaces\DomainObjectInterface;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Database\Eloquent\Model;
use InvalidArgumentException;
abstract class AbstractDomainObject implements DomainObjectInterface, Arrayable
{
public static function hydrate($data): DomainObjectInterface
{
if ($data instanceof Model) {
return self::hydrateFromModel($data);
}
if (is_array($data)) {
return self::hydrateFromArray($data);
}
throw new InvalidArgumentException(sprintf('Cannot hydrate from type %s', gettype($data)));
}
public static function hydrateFromModel(Model $model): DomainObjectInterface
{
return self::hydrateFromArray($model->toArray());
}
public static function hydrateFromArray(array $array): DomainObjectInterface
{
$domainObject = new static();
foreach ($array as $key => $value) {
if (is_array($value)) {
$setter = 'set' . str_replace('_', '', ucwords($key, '_'));
if (method_exists($domainObject, $setter)) {
$reflection = new \ReflectionMethod($domainObject, $setter);
$params = $reflection->getParameters();
if (!empty($params)) {
$type = $params[0]->getType();
if ($type instanceof \ReflectionNamedType && is_a($type->getName(), \Illuminate\Support\Collection::class, true)) {
$domainObject->{$key} = collect($value);
continue;
}
}
}
}
$domainObject->{$key} = $value;
}
return $domainObject;
}
}