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