1 | <?php |
||
10 | abstract class DataTransferObject |
||
11 | { |
||
12 | /** @var array */ |
||
13 | protected $allValues = []; |
||
14 | |||
15 | /** @var array */ |
||
16 | protected $exceptKeys = []; |
||
17 | |||
18 | /** @var array */ |
||
19 | protected $onlyKeys = []; |
||
20 | |||
21 | public function __construct(array $parameters) |
||
26 | |||
27 | private function isValidWith(array $parameters): bool |
||
28 | { |
||
29 | $class = new ReflectionClass(static::class); |
||
30 | |||
31 | $properties = $this->getPublicProperties($class); |
||
32 | |||
33 | foreach ($properties as $property) { |
||
34 | if ( |
||
35 | ! isset($parameters[$property->getName()]) |
||
36 | && ! $property->isNullable() |
||
37 | ) { |
||
38 | throw DataTransferObjectError::uninitialized($property); |
||
39 | } |
||
40 | |||
41 | $value = $parameters[$property->getName()] ?? null; |
||
42 | |||
43 | $property->set($value); |
||
44 | |||
45 | unset($parameters[$property->getName()]); |
||
46 | |||
47 | $this->allValues[$property->getName()] = $property->getValue($this); |
||
48 | } |
||
49 | |||
50 | if (count($parameters)) { |
||
51 | throw DataTransferObjectError::unknownProperties(array_keys($parameters), $class->getName()); |
||
52 | } |
||
53 | |||
54 | return true; |
||
55 | } |
||
56 | |||
57 | public function all(): array |
||
61 | |||
62 | /** |
||
63 | * @param string ...$keys |
||
64 | * |
||
65 | * @return static |
||
66 | */ |
||
67 | public function only(string ...$keys): DataTransferObject |
||
75 | |||
76 | /** |
||
77 | * @param string ...$keys |
||
78 | * |
||
79 | * @return static |
||
80 | */ |
||
81 | public function except(string ...$keys): DataTransferObject |
||
89 | |||
90 | public function toArray(): array |
||
98 | |||
99 | /** |
||
100 | * @param \ReflectionClass $class |
||
101 | * |
||
102 | * @return array|\Spatie\DataTransferObject\Property[] |
||
103 | */ |
||
104 | protected function getPublicProperties(ReflectionClass $class): array |
||
114 | } |
||
115 |