1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of sensorario/resources repository |
5
|
|
|
* |
6
|
|
|
* (c) Simone Gentili <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Sensorario\Resources\Validators\Validators; |
13
|
|
|
|
14
|
|
|
use Sensorario\Resources\Resource; |
15
|
|
|
use Sensorario\Resources\Validators\Interfaces\Validator; |
16
|
|
|
|
17
|
|
|
final class AllowedProperties implements Validator |
18
|
|
|
{ |
19
|
27 |
|
public function check(Resource $resource) |
20
|
|
|
{ |
21
|
27 |
|
$this->resource = $resource; |
|
|
|
|
22
|
|
|
|
23
|
27 |
|
$this->buildAllowedProperties(); |
24
|
|
|
|
25
|
27 |
|
if ($this->checkShouldBeSkipped()) { |
26
|
2 |
|
return; |
27
|
|
|
} |
28
|
|
|
|
29
|
25 |
|
$this->ensurePropertyIsAllowed(); |
30
|
24 |
|
} |
31
|
|
|
|
32
|
27 |
|
private function buildAllowedProperties() |
33
|
|
|
{ |
34
|
27 |
|
$this->allowed = array_merge( |
|
|
|
|
35
|
27 |
|
$this->resource->allowed(), |
36
|
27 |
|
$this->resource->mandatory() |
37
|
|
|
); |
38
|
27 |
|
} |
39
|
|
|
|
40
|
27 |
|
private function checkShouldBeSkipped() |
41
|
|
|
{ |
42
|
27 |
|
foreach ($this->allowed as $kk => $vv) { |
43
|
25 |
|
if (!is_numeric($kk) && isset($vv['when']) && $this->resource->hasProperty($vv['when']['property'])) { |
44
|
2 |
|
return true; |
45
|
|
|
} |
46
|
|
|
} |
47
|
|
|
|
48
|
25 |
|
return false; |
49
|
|
|
} |
50
|
|
|
|
51
|
25 |
|
public function ensurePropertyIsAllowed() |
52
|
|
|
{ |
53
|
25 |
|
foreach ($this->resource->properties() as $key => $value) { |
54
|
17 |
|
if (!in_array($key, $this->allowed)) { |
55
|
1 |
|
throw new \Sensorario\Resources\Exceptions\NotAllowedKeyException( |
56
|
1 |
|
"Key `" . get_class($this->resource) |
57
|
1 |
|
. "::\$$key` with value `" . $value |
58
|
1 |
|
. "` is not allowed" |
59
|
|
|
); |
60
|
|
|
} |
61
|
|
|
} |
62
|
24 |
|
} |
63
|
|
|
} |
64
|
|
|
|
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: