Completed
Pull Request — master (#108)
by Matt
19:10
created

Items   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 56
Duplicated Lines 30.36 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
dl 17
loc 56
rs 10
c 0
b 0
f 0
wmc 9
lcom 0
cbo 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
B validate() 17 29 5
A getSchema() 0 12 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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\JsonReference\pointer_push;
9
10
class Items implements Constraint
11
{
12
    const KEYWORD = 'items';
13
14
    /**
15
     * {@inheritdoc}
16
     */
17
    public function validate($value, $parameter, Validator $validator)
18
    {
19
        Assert::type($parameter, ['array', 'object'], self::KEYWORD, $validator->getSchemaPath());
20
21
        if (!is_array($value)) {
22
            return null;
23
        }
24
25
        $errors = [];
26 View Code Duplication
        foreach ($value as $key => $itemValue) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
27
            $schema = self::getSchema($parameter, $key);
28
29
            // Additional items are allowed by default,
30
            // so there might not be a schema for this.
31
            if (is_null($schema)) {
32
                continue;
33
            }
34
35
            $subValidator = $validator->makeSubSchemaValidator(
36
                $itemValue,
37
                $schema,
38
                pointer_push($validator->getDataPath(), $key),
39
                pointer_push($validator->getSchemaPath(), $key)
40
            );
41
            $errors = array_merge($errors, $subValidator->errors());
42
        }
43
44
        return $errors ?: null;
45
    }
46
47
    /**
48
     * @param $parameter
49
     * @param $key
50
     *
51
     * @return mixed
52
     */
53
    private static function getSchema($parameter, $key)
54
    {
55
        if (is_object($parameter)) {
56
            // list validation
57
            return $parameter;
58
        } elseif (is_array($parameter) && array_key_exists($key, $parameter)) {
59
            // tuple validation
60
            return $parameter[$key];
61
        }
62
63
        return null;
64
    }
65
}
66