1 | <?php |
||
10 | abstract class DataTransferObject |
||
11 | { |
||
12 | /** @var array */ |
||
13 | protected $exceptKeys = []; |
||
14 | |||
15 | /** @var array */ |
||
16 | protected $onlyKeys = []; |
||
17 | |||
18 | /** @var array[] */ |
||
19 | protected static $cache = []; |
||
20 | |||
21 | /** |
||
22 | * @param array $parameters |
||
23 | * |
||
24 | * @return \Spatie\DataTransferObject\ImmutableDataTransferObject|static |
||
25 | */ |
||
26 | public static function immutable(array $parameters): ImmutableDataTransferObject |
||
30 | |||
31 | public function __construct(array $parameters) |
||
32 | { |
||
33 | $class = new ReflectionClass(static::class); |
||
34 | |||
35 | $properties = $this->getPublicProperties($class); |
||
36 | |||
37 | foreach ($properties as $property) { |
||
38 | if ( |
||
39 | ! isset($parameters[$property->getName()]) |
||
40 | && ! $property->isDefault() |
||
41 | && ! $property->isNullable() |
||
42 | ) { |
||
43 | throw DataTransferObjectError::uninitialized($property); |
||
44 | } |
||
45 | |||
46 | $value = $parameters[$property->getName()] ?? $property->getValue($this); |
||
47 | |||
48 | $property->set($value); |
||
49 | |||
50 | unset($parameters[$property->getName()]); |
||
51 | } |
||
52 | |||
53 | if (count($parameters)) { |
||
54 | throw DataTransferObjectError::unknownProperties(array_keys($parameters), $class->getName()); |
||
55 | } |
||
56 | } |
||
57 | |||
58 | public function all(): array |
||
72 | |||
73 | /** |
||
74 | * @param string ...$keys |
||
75 | * |
||
76 | * @return static |
||
77 | */ |
||
78 | public function only(string ...$keys): DataTransferObject |
||
86 | |||
87 | /** |
||
88 | * @param string ...$keys |
||
89 | * |
||
90 | * @return static |
||
91 | */ |
||
92 | public function except(string ...$keys): DataTransferObject |
||
100 | |||
101 | public function toArray(): array |
||
113 | |||
114 | protected function parseArray(array $array): array |
||
135 | |||
136 | /** |
||
137 | * @param \ReflectionClass $class |
||
138 | * |
||
139 | * @return array|\Spatie\DataTransferObject\Property[] |
||
140 | */ |
||
141 | protected function getPublicProperties(ReflectionClass $class): array |
||
151 | |||
152 | /** |
||
153 | * @param \ReflectionClass $class |
||
154 | * |
||
155 | * @return array|ReflectionProperty[] |
||
156 | */ |
||
157 | protected function getPublicReflectionProperties(ReflectionClass $class): array |
||
171 | } |
||
172 |