Completed
Pull Request — master (#145)
by Simone
01:55
created

AllowedProperties::ensurePropertyIsAllowed()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

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