|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Loevgaard\DandomainFoundation\Entity; |
|
4
|
|
|
|
|
5
|
|
|
use Loevgaard\DandomainDateTime\DateTimeImmutable; |
|
6
|
|
|
use Zend\Hydrator\ClassMethods; |
|
7
|
|
|
use Zend\Hydrator\HydratorInterface; |
|
8
|
|
|
|
|
9
|
|
|
abstract class AbstractEntity |
|
10
|
|
|
{ |
|
11
|
|
|
/** |
|
12
|
|
|
* This will hold the conversions applied when calling hydrate |
|
13
|
|
|
* |
|
14
|
|
|
* @var array |
|
15
|
|
|
*/ |
|
16
|
|
|
protected $hydrateConversions; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* This will hold the conversions applied when calling extract |
|
20
|
|
|
* |
|
21
|
|
|
* @var array |
|
22
|
|
|
*/ |
|
23
|
|
|
protected $extractConversions; |
|
24
|
|
|
|
|
25
|
|
|
public function hydrate(array $data, bool $useConversions = false) |
|
26
|
|
|
{ |
|
27
|
|
|
$hydrator = $this->getHydrator(); |
|
28
|
|
|
|
|
29
|
|
|
if($useConversions && is_array($this->hydrateConversions)) { |
|
30
|
|
|
$data = $this->convert($data, $this->hydrateConversions); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
$hydrator->hydrate($data, $this); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
public function extract(bool $useConversions = false) : array |
|
37
|
|
|
{ |
|
38
|
|
|
$hydrator = $this->getHydrator(); |
|
39
|
|
|
|
|
40
|
|
|
$data = $hydrator->extract($this); |
|
41
|
|
|
|
|
42
|
|
|
if($useConversions && is_array($this->extractConversions)) { |
|
43
|
|
|
$data = $this->convert($data, $this->extractConversions); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
return $data; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
protected function convert(array $data, $conversions) : array |
|
50
|
|
|
{ |
|
51
|
|
|
foreach ($conversions as $from => $to) { |
|
52
|
|
|
if(isset($data[$to])) { |
|
53
|
|
|
throw new \InvalidArgumentException('The $to argument in the $data object is already set'); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
$tmp = $data[$from] ?? null; |
|
57
|
|
|
if($tmp) { |
|
58
|
|
|
unset($data[$from]); |
|
59
|
|
|
$data[$to] = $tmp; |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
return $data; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
protected function getDateTimeFromJson($val = null) : ?DateTimeImmutable |
|
67
|
|
|
{ |
|
68
|
|
|
if (!$val) { |
|
69
|
|
|
return null; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
if ($val instanceof DateTimeImmutable) { |
|
73
|
|
|
return $val; |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
|
|
return DateTimeImmutable::createFromJson($val); |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
|
|
/** |
|
80
|
|
|
* @return HydratorInterface |
|
81
|
|
|
*/ |
|
82
|
|
|
protected function getHydrator() : HydratorInterface |
|
83
|
|
|
{ |
|
84
|
|
|
return new ClassMethods(false); |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|