1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Cerbero\Dto\Traits; |
4
|
|
|
|
5
|
|
|
use const Cerbero\Dto\MUTABLE; |
|
|
|
|
6
|
|
|
use const Cerbero\Dto\NONE; |
|
|
|
|
7
|
|
|
use const Cerbero\Dto\PARTIAL; |
|
|
|
|
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Trait to manipulate a DTO data. |
11
|
|
|
* |
12
|
|
|
*/ |
13
|
|
|
trait ManipulatesData |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* Merge the given data in the DTO |
17
|
|
|
* |
18
|
|
|
* @param iterable $data |
19
|
|
|
* @param int $flags |
20
|
|
|
* @return self |
21
|
|
|
*/ |
22
|
9 |
|
public function merge(iterable $data, int $flags = NONE): self |
23
|
|
|
{ |
24
|
9 |
|
$replacements = static::getArrayConverter()->convert($data); |
25
|
9 |
|
$mergedData = array_replace_recursive($this->toArray(), $replacements); |
|
|
|
|
26
|
9 |
|
$mergedFlags = $this->mergeFlags($this->getFlags(), $flags); |
|
|
|
|
27
|
|
|
|
28
|
9 |
|
if (!($this->getFlags() & MUTABLE)) { |
29
|
6 |
|
return new static($mergedData, $mergedFlags); |
|
|
|
|
30
|
|
|
} |
31
|
|
|
|
32
|
3 |
|
$this->flags = $mergedFlags; |
|
|
|
|
33
|
3 |
|
$this->propertiesMap = $this->mapData($mergedData); |
|
|
|
|
34
|
|
|
|
35
|
3 |
|
return $this; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Retrieve the DTO including only the given properties |
40
|
|
|
* |
41
|
|
|
* @param array $properties |
42
|
|
|
* @param int $flags |
43
|
|
|
* @return self |
44
|
|
|
*/ |
45
|
12 |
|
public function only(array $properties, int $flags = NONE): self |
46
|
|
|
{ |
47
|
12 |
|
$data = []; |
48
|
12 |
|
$isMutable = $this->getFlags() & MUTABLE; |
49
|
12 |
|
$mergedFlags = $this->mergeFlags($this->getFlagsWithoutDefaults(), $flags | PARTIAL); |
|
|
|
|
50
|
|
|
|
51
|
12 |
|
foreach ($this->getPropertiesMap() as $name => $property) { |
|
|
|
|
52
|
12 |
|
if (in_array($name, $properties) && !$isMutable) { |
53
|
6 |
|
$data[$name] = $property->value(); |
54
|
12 |
|
} elseif (!in_array($name, $properties) && $isMutable) { |
55
|
10 |
|
unset($this->propertiesMap[$name]); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
59
|
12 |
|
if ($isMutable) { |
60
|
6 |
|
$this->flags = $mergedFlags; |
|
|
|
|
61
|
6 |
|
return $this; |
62
|
|
|
} |
63
|
|
|
|
64
|
6 |
|
return new static($data, $mergedFlags); |
|
|
|
|
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* Retrieve the DTO excluding the given properties |
69
|
|
|
* |
70
|
|
|
* @param array $properties |
71
|
|
|
* @param int $flags |
72
|
|
|
* @return self |
73
|
|
|
*/ |
74
|
6 |
|
public function except(array $properties, int $flags = NONE): self |
75
|
|
|
{ |
76
|
6 |
|
$propertiesToKeep = array_diff($this->getPropertyNames(), $properties); |
|
|
|
|
77
|
|
|
|
78
|
6 |
|
return $this->only($propertiesToKeep, $flags); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|