1 | <?php |
||
8 | trait AttributesTrait |
||
9 | { |
||
10 | public function getAttributes() |
||
33 | |||
34 | public function getMethod($attr) |
||
38 | |||
39 | public function setMethod($attr) |
||
43 | |||
44 | public function get($attr) |
||
|
|||
45 | { |
||
46 | $attributes = $this->getAttributes(); |
||
47 | |||
48 | $getMethod = $this->getMethod($attr); |
||
49 | if (method_exists($this, $getMethod)) { |
||
50 | return $this->$getMethod(); |
||
51 | } |
||
52 | |||
53 | throw new InvalidArgumentException( |
||
54 | sprintf( |
||
55 | 'The class "%s" don\'t have a method "%s"', |
||
56 | get_class($this), |
||
57 | $getMethod |
||
58 | ) |
||
59 | ); |
||
60 | } |
||
61 | |||
62 | public function set($attr, $value) |
||
63 | { |
||
64 | $setMethod = $this->setMethod($attr); |
||
65 | |||
66 | if (method_exists($this, $setMethod)) { |
||
67 | return $this->$setMethod($value); |
||
68 | } |
||
69 | |||
70 | throw new InvalidArgumentException( |
||
71 | sprintf( |
||
72 | 'The class "%s" don\'t have a method "%s"', |
||
73 | get_class($this), |
||
74 | $setMethod |
||
75 | ) |
||
76 | ); |
||
77 | } |
||
78 | |||
79 | public function toArray() |
||
80 | { |
||
81 | return array_map(function ($attr) { |
||
82 | if (method_exists($attr, 'toArray')) { |
||
83 | return $attr->toArray(); |
||
84 | } |
||
85 | |||
86 | if ($attr instanceof ArrayAccess) { |
||
87 | $newParam = []; |
||
88 | foreach ($attr as $p) { |
||
89 | if (method_exists($p, 'toArray')) { |
||
90 | $newParam[] = $p->toArray(); |
||
91 | continue; |
||
92 | } |
||
93 | |||
94 | $newParam[] = $p; |
||
95 | } |
||
96 | |||
97 | return $newParam; |
||
98 | } |
||
99 | |||
100 | return $attr; |
||
101 | }, $this->getAttributes()); |
||
102 | } |
||
103 | |||
104 | public function toJson() |
||
108 | |||
109 | public function toString() |
||
113 | |||
114 | public function __toString() |
||
118 | |||
119 | public function __get($attr) |
||
123 | |||
124 | public function __set($attr, $value) |
||
128 | |||
129 | public function __isset($attr) |
||
133 | |||
134 | public function __unset($attr) |
||
138 | } |
||
139 |
Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a
@return
annotation as described here.