Completed
Pull Request — master (#108)
by Matt
11:29
created

Dependencies::validate()   C

Complexity

Conditions 7
Paths 5

Size

Total Lines 35
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 24
nc 5
nop 3
dl 0
loc 35
rs 6.7272
c 0
b 0
f 0
1
<?php
2
3
namespace League\JsonGuard\Constraints\DraftFour;
4
5
use League\JsonGuard\Assert;
6
use League\JsonGuard\Constraint;
7
use League\JsonGuard\Validator;
8
use function League\JsonGuard\error;
9
use function League\JsonReference\pointer_push;
10
11
class Dependencies implements Constraint
12
{
13
    const KEYWORD = 'dependencies';
14
15
    /**
16
     * {@inheritdoc}
17
     */
18
    public function validate($value, $parameter, Validator $validator)
19
    {
20
        Assert::type($parameter, ['object', 'array'], self::KEYWORD, $validator->getSchemaPath());
21
22
        $errors = [];
23
        foreach ($parameter as $property => $dependencies) {
24
            if (!is_object($value) || !property_exists($value, $property)) {
25
                continue;
26
            }
27
28
            if (is_array($dependencies)) {
29
                $errors = array_merge(
30
                    $errors,
31
                    array_filter(array_map(function ($dependency) use ($value, $validator) {
32
                        if (!in_array($dependency, array_keys(get_object_vars($value)), true)) {
33
                            return error('The object must contain the dependent property {cause}.', $validator)
34
                                ->withCause($dependency);
35
                        }
36
                    }, $dependencies))
37
                );
38
            } elseif (is_object($dependencies)) {
39
                $errors = array_merge(
40
                    $errors,
41
                    $validator->makeSubSchemaValidator(
42
                        $value,
43
                        $dependencies,
44
                        $validator->getDataPath(),
45
                        pointer_push($validator->getSchemaPath(), $property)
46
                    )->errors()
47
                );
48
            }
49
        }
50
51
        return $errors;
52
    }
53
}
54