1 | <?php |
||
21 | abstract class MagicResource |
||
22 | { |
||
23 | protected $properties = []; |
||
24 | |||
25 | protected $validator; |
||
26 | |||
27 | private static $methodWhiteList = [ |
||
28 | 'box', |
||
29 | 'allowedValues' |
||
30 | ]; |
||
31 | |||
32 | 3 | public function __call($functionName, $arguments) |
|
33 | { |
||
34 | 3 | $propertyName = strtolower($functionName); |
|
35 | |||
36 | 3 | if ($this->hasProperty($propertyName)) { |
|
37 | 1 | return $this->get($propertyName); |
|
38 | } |
||
39 | |||
40 | 2 | if (isset($this->defaults()[$propertyName])) { |
|
41 | 1 | return $this->defaults()[$propertyName]; |
|
42 | } |
||
43 | |||
44 | 1 | throw new \Sensorario\Resources\Exceptions\UndefinedMethodException( |
|
45 | 1 | 'Method `' . get_class($this) |
|
46 | 1 | . '::' . $functionName |
|
47 | 1 | . '()` is not yet implemented' |
|
48 | ); |
||
49 | } |
||
50 | |||
51 | abstract public function applyConfiguration(Configurator $configurator); |
||
52 | |||
53 | 39 | public function __construct( |
|
54 | array $properties, |
||
55 | ResourcesValidator $validator, |
||
56 | Configurator $configuration = null |
||
57 | ) { |
||
58 | 39 | $this->properties = $properties; |
|
59 | 39 | $this->validator = $validator; |
|
60 | 39 | $this->configuration = $configuration; |
|
|
|||
61 | |||
62 | 39 | if ($configuration) { |
|
63 | 21 | $this->applyConfiguration( |
|
64 | 21 | $configuration |
|
65 | ); |
||
66 | } |
||
67 | |||
68 | 39 | $this->init(); |
|
69 | 24 | } |
|
70 | |||
71 | 39 | private function init() |
|
72 | { |
||
73 | 39 | $this->ensurePropertiesConsistency(); |
|
74 | 38 | $this->validate(); |
|
75 | 24 | } |
|
76 | |||
77 | 39 | public static function __callStatic($methodName, array $args) |
|
109 | |||
110 | 31 | final public function hasProperty($propertyName) |
|
116 | |||
117 | 1 | final public function set($propertyName, $propertValue) |
|
121 | |||
122 | 24 | final public function get($propertyName) |
|
123 | { |
||
124 | 24 | $this->ensurePropertyNameIsNotEmpty($propertyName); |
|
125 | |||
140 | |||
141 | 29 | final public function hasNotProperty($propertyName) |
|
145 | |||
146 | 2 | final public function hasProperties(array $properties) |
|
156 | |||
157 | 38 | final public function properties() |
|
181 | |||
182 | 38 | public function validate() |
|
186 | |||
187 | 39 | public function ensurePropertiesConsistency() |
|
199 | |||
200 | 24 | public function ensurePropertyNameIsNotEmpty($propertyName) |
|
208 | } |
||
209 |
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: