Completed
Push — master ( 77b530...acb106 )
by Jonathan
02:05
created

Nested::finish()   C

Complexity

Conditions 7
Paths 7

Size

Total Lines 25
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 7.0061

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 19
cts 20
cp 0.95
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 20
nc 7
nop 1
crap 7.0061
1
<?php
2
declare(strict_types=1);
3
/**
4
 * Caridea
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
7
 * use this file except in compliance with the License. You may obtain a copy of
8
 * the License at
9
 *
10
 * http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15
 * License for the specific language governing permissions and limitations under
16
 * the License.
17
 *
18
 * @copyright 2015-2018 LibreWorks contributors
19
 * @license   Apache-2.0
20
 */
21
namespace Caridea\Validate\Rule;
22
23
/**
24
 * Rules for nested list and object validation.
25
 *
26
 * @copyright 2015-2018 LibreWorks contributors
27
 * @license   Apache-2.0
28
 */
29
class Nested implements \Caridea\Validate\Draft
30
{
31
    /**
32
     * @var string The operator type
33
     */
34
    private $operator;
35
    /**
36
     * @var \Caridea\Validate\Validator Optional. A validator for nested objects.
37
     */
38
    private $validator;
39
    /**
40
     * @var string Optional field on object that chooses rules.
41
     */
42
    private $field;
43
44
    /**
45
     * Creates a new NestedRule.
46
     *
47
     * @param string $operator The operator type
48
     * @param mixed|\Caridea\Validate\Validator The validator to use, or definitions to create one
49
     * @param string $field Optional field on object that chooses rules
50
     */
51 4
    protected function __construct(string $operator, $validator, string $field = null)
52
    {
53 4
        $this->operator = $operator;
54 4
        $this->validator = $validator;
55 4
        $this->field = $field;
56 4
    }
57
58
    /**
59
     * Finishes creating a rule using the parent builder.
60
     *
61
     * @param \Caridea\Validate\Registry $registry
62
     * @return \Caridea\Validate\Rule The fully created rule
63
     */
64 4
    public function finish(\Caridea\Validate\Registry $registry): \Caridea\Validate\Rule
65
    {
66 4
        if ($this->validator instanceof \Caridea\Validate\Validator) {
67 4
            return $this;
68
        } else {
69 4
            $rule = clone $this;
70 4
            $builder = $registry->builder();
71 4
            switch ($this->operator) {
72 4
                case "nested_object":
73 3
                case "list_objects":
74 2
                    $rule->validator = $builder->build($this->validator);
75 2
                    return $rule;
76 2
                case "list":
77 1
                    $rule->validator = $builder->build((object)['entry' => $this->validator]);
78 1
                    return $rule;
79 1
                case "list_different_objects":
80 1
                    $validators = [];
81 1
                    foreach ($this->validator as $value => $ruleset) {
82 1
                        $validators[$value] = $builder->build($ruleset);
83
                    }
84 1
                    $rule->validator = new \Caridea\Validate\SwitchValidator($this->field, $validators);
85 1
                    return $rule;
86
            }
87
        }
88
    }
89
90
    /**
91
     * {@inheritDoc}
92
     */
93 7
    public function apply($value, $data = []): ?array
94
    {
95 7
        if (!($this->validator instanceof \Caridea\Validate\Validator)) {
96 1
            throw new \BadMethodCallException("This rule is a Draft. Try calling the 'finish' method to get the full Rule.");
97
        }
98 6
        if (!is_array($value) && !($value instanceof \Traversable)) {
99 1
            return ['FORMAT_ERROR'];
100
        }
101 5
        switch ($this->operator) {
102 5
            case "nested_object":
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
103 2
                $result = $this->validator->validate($value);
104 2
                return $result->hasErrors() ? $result->getErrors() : null;
105 3
            case "list":
106 1
                $errors = [];
107 1
                foreach ($value as $entry) {
108 1
                    $result = $this->validator->validate(['entry' => $entry]);
109 1
                    $errors[] = $result->hasErrors() ?
110 1
                        $result->getErrors()['entry'] : null;
111
                }
112 1
                return array_filter($errors) ? $errors : null;
113 2
            case "list_objects":
114 1
            case "list_different_objects":
115 2
                $errors = [];
116 2
                foreach ($value as $entry) {
117
                    try {
118 2
                        $result = $this->validator->validate($entry);
119 2
                        $errors[] = $result->hasErrors() ?
120 2
                            $result->getErrors() : null;
121 1
                    } catch (\InvalidArgumentException $e) {
122 2
                        $errors[] = 'FORMAT_ERROR';
123
                    }
124
                }
125 2
                return array_filter($errors) ? $errors : null;
126
        }
127
    }
128
129
    /**
130
     * Verifies an object value against separate validator rules.
131
     *
132
     * @param object $ruleset The validation ruleset
133
     * @return \Caridea\Validate\Rule\Nested the created rule
134
     */
135 1
    public static function nestedObject(\stdClass $ruleset): Nested
136
    {
137 1
        return new Nested("nested_object", $ruleset);
138
    }
139
140
    /**
141
     * Verifies each entry in a list using one or more rules.
142
     *
143
     * @param mixed $rules The rule or rules to enforce
144
     * @return \Caridea\Validate\Rule\Nested the created rule
145
     */
146 1
    public static function listOf($rules): Nested
147
    {
148 1
        return new Nested("list", $rules);
149
    }
150
151
    /**
152
     * Verifies each entry in a list against separate validator rules.
153
     *
154
     * @param object $ruleset The validation ruleset
155
     * @return \Caridea\Validate\Rule\Nested the created rule
156
     */
157 1
    public static function listOfObjects(\stdClass $ruleset): Nested
158
    {
159 1
        return new Nested("list_objects", $ruleset);
160
    }
161
162
    /**
163
     * Verifies each entry in a list using one of several validators based on a field value.
164
     *
165
     * @param string $field The deciding field name
166
     * @param object $rulesets The rulesets
167
     * @return \Caridea\Validate\Rule\Nested the created rule
168
     */
169 1
    public static function listOfDifferentObjects(string $field, \stdClass $rulesets): Nested
170
    {
171 1
        return new Nested('list_different_objects', $rulesets, $field);
172
    }
173
}
174