Completed
Push — master ( ed001e...1a182a )
by Simone
08:15 queued 05:00
created

MandatoryConditional::check()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 17
ccs 10
cts 10
cp 1
rs 8.8571
cc 5
eloc 10
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 $item) {
28 3
                        $this->ensurePropertyNameHasKey($resource, $item, $name, $key);
29
                    }
30
                } else {
31 1
                    $this->ensurePropertyNameHasKey($resource, $value, $name, $key);
32
                }
33
            }
34
        }
35 30
    }
36
37 4
    public function ensurePropertyNameHasKey(Resource $resource, $value, $name, $key)
38
    {
39 4
        if ($resource->get($name) === $value && $resource->hasNotProperty($key)) {
40 2
            throw new \Sensorario\Resources\Exceptions\PropertyException(
41 2
                'When property `' . $name . '` '
42 2
                . 'has value ' . '`' . $value . '` '
43 2
                . 'also `' . $key . '` is mandatory'
44
            );
45
        }
46 3
    }
47
}
48