AllowedProperties::buildAllowedProperties()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 5
cts 5
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
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 31
    public function check(Resource $resource)
24
    {
25 31
        $this->resource = $resource;
26 31
        $this->buildAllowedProperties();
27 31
        if (null === $this->checkShouldBeSkipped()) {
28 29
            $this->ensurePropertyIsAllowed();
29
        }
30 29
    }
31
32 31
    private function buildAllowedProperties()
33
    {
34 31
        $this->allowed = array_merge(
35 31
            $this->resource->allowed(),
36 31
            $this->resource->mandatory()
37
        );
38 31
    }
39
40 31
    private function checkShouldBeSkipped()
41
    {
42 31
        foreach ($this->allowed as $kk => $vv) {
43 27
            if ($this->mustSkip($kk, $vv)) {
44 27
                return true;
45
            }
46
        }
47 29
    }
48
49 29
    public function ensurePropertyIsAllowed()
50
    {
51 29
        foreach ($this->resource->properties() as $key => $value) {
52 20
            if (!in_array($key, $this->allowed)) {
53 2
                throw new \Sensorario\Resources\Exceptions\NotAllowedKeyException(
54 20
                    "Key `" . get_class($this->resource) . "::\$$key` with value `" . $value . "` is not allowed"
55
                );
56
            }
57
        }
58 27
    }
59
60 27
    public function mustSkip($key, $value)
61
    {
62 27
        return !is_numeric($key) &&
63 27
            isset($value['when']) &&
64 27
            $this->resource->hasProperty($value['when']['property']);
65
    }
66
}
67