1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Cerbero\Dto\Traits; |
4
|
|
|
|
5
|
|
|
use Cerbero\Dto\DtoProperty; |
6
|
|
|
use Cerbero\Dto\Exceptions\UnknownDtoPropertyException; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Trait to interact with properties. |
10
|
|
|
* |
11
|
|
|
*/ |
12
|
|
|
trait HasProperties |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* The properties map. |
16
|
|
|
* |
17
|
|
|
* @var array |
18
|
|
|
*/ |
19
|
|
|
protected $propertiesMap; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Retrieve the DTO properties map |
23
|
|
|
* |
24
|
|
|
* @return array |
25
|
|
|
*/ |
26
|
54 |
|
public function getPropertiesMap(): array |
27
|
|
|
{ |
28
|
54 |
|
return $this->propertiesMap; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Retrieve the DTO property names |
33
|
|
|
* |
34
|
|
|
* @return array |
35
|
|
|
*/ |
36
|
18 |
|
public function getPropertyNames(): array |
37
|
|
|
{ |
38
|
18 |
|
return array_keys($this->getPropertiesMap()); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Retrieve the DTO properties |
43
|
|
|
* |
44
|
|
|
* @return DtoProperty[] |
45
|
|
|
*/ |
46
|
6 |
|
public function getProperties(): array |
47
|
|
|
{ |
48
|
6 |
|
return array_values($this->getPropertiesMap()); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* Determine whether the given property is set (even if its value is NULL) |
53
|
|
|
* |
54
|
|
|
* @param string $property |
55
|
|
|
* @return bool |
56
|
|
|
*/ |
57
|
36 |
|
public function hasProperty(string $property): bool |
58
|
|
|
{ |
59
|
|
|
try { |
60
|
36 |
|
return !!$this->getProperty($property); |
61
|
27 |
|
} catch (UnknownDtoPropertyException $e) { |
62
|
27 |
|
return false; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* Retrieve the given DTO property (support dot notation) |
68
|
|
|
* |
69
|
|
|
* @param string $property |
70
|
|
|
* @return DtoProperty |
71
|
|
|
* @throws UnknownDtoPropertyException |
72
|
|
|
*/ |
73
|
114 |
|
public function getProperty(string $property): DtoProperty |
74
|
|
|
{ |
75
|
114 |
|
if (isset($this->propertiesMap[$property])) { |
76
|
75 |
|
return $this->propertiesMap[$property]; |
77
|
|
|
} |
78
|
|
|
|
79
|
63 |
|
if (strpos($property, '.') === false) { |
80
|
57 |
|
throw new UnknownDtoPropertyException(static::class, $property); |
81
|
|
|
} |
82
|
|
|
|
83
|
18 |
|
[$property, $nestedProperty] = explode('.', $property, 2); |
84
|
18 |
|
$presumedDto = $this->get($property); |
|
|
|
|
85
|
|
|
|
86
|
15 |
|
if ($presumedDto instanceof self) { |
87
|
12 |
|
return $presumedDto->getProperty($nestedProperty); |
88
|
|
|
} |
89
|
|
|
|
90
|
3 |
|
throw new UnknownDtoPropertyException(static::class, $nestedProperty); |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|