Completed
Pull Request — master (#143)
by Simone
02:57
created

MandatoryConditional::check()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

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