Completed
Pull Request — master (#143)
by Simone
01:53
created

MandatoryConditional::check()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 5

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 27
ccs 18
cts 18
cp 1
rs 8.439
cc 5
eloc 18
nc 4
nop 1
crap 5
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 MandatoryConditional implements Validator
18
{
19 32
    public function check(Resource $resource)
20
    {
21 32
        foreach ($resource->mandatory() as $key => $value) {
22 19
            if (isset($value['when']['has_value'])) {
23 4
                $name = $value['when']['property'];
24 4
                $value = $value['when']['has_value'];
25
26 4
                if (is_array($value)) {
27 3
                    foreach ($value as $value) {
28 3
                        $this->ensurePropertyNameHasKey(
29 3
                            $resource,
30 3
                            $value,
31 3
                            $name,
32 3
                            $key
33
                        );
34
                    }
35
                } else {
36 1
                    $this->ensurePropertyNameHasKey(
37 1
                        $resource,
38 1
                        $value,
39 1
                        $name,
40 1
                        $key
41
                    );
42
                }
43
            }
44
        }
45 30
    }
46
47 4
    public function ensurePropertyNameHasKey(Resource $resource, $value, $name, $key)
48
    {
49 4
        if ($resource->get($name) === $value && $resource->hasNotProperty($key)) {
50 2
            throw new \Sensorario\Resources\Exceptions\PropertyException(
51 2
                'When property `' . $name . '` '
52 2
                . 'has value ' . '`' . $value . '` '
53 2
                . 'also `' . $key . '` is mandatory'
54
            );
55
        }
56 3
    }
57
}
58