Completed
Push — master ( 5927eb...1e13db )
by
unknown
04:04
created

Items::validate()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5
Metric Value
cc 5
eloc 11
nc 7
nop 4
dl 0
loc 22
ccs 12
cts 12
cp 1
crap 5
rs 8.6737
1
<?php
2
3
namespace League\JsonGuard\Constraints;
4
5
use League\JsonGuard\SubSchemaValidatorFactory;
6
7
class Items implements ContainerInstanceConstraint
8
{
9
    /**
10
     * {@inheritdoc}
11
     */
12 12
    public static function validate($data, $parameter, SubSchemaValidatorFactory $validatorFactory, $pointer = null)
13
    {
14 12
        if (!is_array($data)) {
15 4
            return null;
16
        }
17
18 10
        $errors = [];
19 10
        foreach ($data as $key => $value) {
20 10
            $schema = self::getSchema($parameter, $key);
21
22
            // Additional items are allowed by default,
23
            // so there might not be a schema for this.
24 10
            if (is_null($schema)) {
25 2
                continue;
26
            }
27
28 10
            $validator = $validatorFactory->makeSubSchemaValidator($value, $schema, $pointer . '/' . $key);
29 10
            $errors = array_merge($errors, $validator->errors());
30 10
        }
31
32 10
        return $errors ?: null;
33
    }
34
35
    /**
36
     * @param $parameter
37
     * @param $key
38
     *
39
     * @return mixed
40
     */
41 10
    protected static function getSchema($parameter, $key)
42
    {
43 10
        if (is_object($parameter)) {
44
            // list validation
45 8
            return $parameter;
46 6
        } elseif (is_array($parameter) && array_key_exists($key, $parameter)) {
47
            // tuple validation
48 6
            return $parameter[$key];
49
        }
50
51 2
        return null;
52
    }
53
}
54