|
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
|
|
|
private $resource; |
|
20
|
|
|
|
|
21
|
|
|
private $allowed; |
|
22
|
|
|
|
|
23
|
27 |
|
public function check(Resource $resource) |
|
24
|
|
|
{ |
|
25
|
27 |
|
$this->resource = $resource; |
|
26
|
27 |
|
$this->buildAllowedProperties(); |
|
27
|
27 |
|
if (!$this->checkShouldBeSkipped()) { |
|
|
|
|
|
|
28
|
25 |
|
$this->ensurePropertyIsAllowed(); |
|
29
|
|
|
} |
|
30
|
26 |
|
} |
|
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 ($this->mustSkip($kk, $vv)) { |
|
44
|
2 |
|
return true; |
|
45
|
|
|
} |
|
46
|
|
|
} |
|
47
|
25 |
|
} |
|
48
|
|
|
|
|
49
|
25 |
|
public function ensurePropertyIsAllowed() |
|
50
|
|
|
{ |
|
51
|
25 |
|
foreach ($this->resource->properties() as $key => $value) { |
|
52
|
17 |
|
if (!in_array($key, $this->allowed)) { |
|
53
|
1 |
|
throw new \Sensorario\Resources\Exceptions\NotAllowedKeyException( |
|
54
|
1 |
|
"Key `" . get_class($this->resource) . "::\$$key` with value `" . $value . "` is not allowed" |
|
55
|
|
|
); |
|
56
|
|
|
} |
|
57
|
|
|
} |
|
58
|
24 |
|
} |
|
59
|
|
|
|
|
60
|
25 |
|
public function mustSkip($key, $value) |
|
61
|
|
|
{ |
|
62
|
25 |
|
return !is_numeric($key) && |
|
63
|
10 |
|
isset($value['when']) && |
|
64
|
25 |
|
$this->resource->hasProperty($value['when']['property']); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|
If an expression can have both
false, andnullas possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.