1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\ValueObject; |
4
|
|
|
|
5
|
|
|
abstract class ValueObject |
6
|
|
|
{ |
7
|
|
|
/** @var array */ |
8
|
|
|
protected $allValues = []; |
9
|
|
|
|
10
|
|
|
/** @var array */ |
11
|
|
|
protected $exceptKeys = []; |
12
|
|
|
|
13
|
|
|
/** @var array */ |
14
|
|
|
protected $onlyKeys = []; |
15
|
|
|
|
16
|
|
|
public function __construct(array $parameters) |
17
|
|
|
{ |
18
|
|
|
$class = new ValueObjectDefinition($this); |
19
|
|
|
|
20
|
|
|
$properties = $class->getValueObjectProperties(); |
21
|
|
|
|
22
|
|
|
foreach ($properties as $property) { |
23
|
|
|
$value = $parameters[$property->getName()] ?? null; |
24
|
|
|
|
25
|
|
|
$property->set($value); |
26
|
|
|
|
27
|
|
|
unset($parameters[$property->getName()]); |
28
|
|
|
|
29
|
|
|
$this->allValues[$property->getName()] = $property->getValue($this); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
if (count($parameters)) { |
33
|
|
|
throw ValueObjectError::unknownProperties(array_keys($parameters), $class); |
34
|
|
|
} |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function all(): array |
38
|
|
|
{ |
39
|
|
|
return $this->allValues; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param string ...$keys |
44
|
|
|
* |
45
|
|
|
* @return static |
46
|
|
|
*/ |
47
|
|
|
public function only(string ...$keys): ValueObject |
48
|
|
|
{ |
49
|
|
|
$valueObject = clone $this; |
50
|
|
|
|
51
|
|
|
$valueObject->onlyKeys = array_merge($this->onlyKeys, $keys); |
52
|
|
|
|
53
|
|
|
return $valueObject; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param string ...$keys |
58
|
|
|
* |
59
|
|
|
* @return static |
60
|
|
|
*/ |
61
|
|
|
public function except(string ...$keys): ValueObject |
62
|
|
|
{ |
63
|
|
|
$valueObject = clone $this; |
64
|
|
|
|
65
|
|
|
$valueObject->exceptKeys = array_merge($this->exceptKeys, $keys); |
66
|
|
|
|
67
|
|
|
return $valueObject; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
public function toArray(): array |
71
|
|
|
{ |
72
|
|
|
if (count($this->onlyKeys)) { |
73
|
|
|
return Arr::only($this->all(), $this->onlyKeys); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
return Arr::except($this->all(), $this->exceptKeys); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|