Passed
Branch master (7e4b7e)
by Mariano
04:51
created

Properties::validateList()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 2
Bugs 1 Features 1
Metric Value
c 2
b 1
f 1
dl 0
loc 13
ccs 0
cts 8
cp 0
rs 9.4285
cc 3
eloc 8
nc 3
nop 1
crap 12
1
<?php
2
/**
3
 * This file is part of php-simple-request.
4
 *
5
 * php-simple-request is free software: you can redistribute it and/or modify
6
 * it under the terms of the GNU Lesser General Public License as published by
7
 * the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * php-simple-request is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with php-simple-request.  If not, see <http://www.gnu.org/licenses/>.
17
 */
18
namespace Mcustiel\SimpleRequest\Validator;
19
20
use Mcustiel\SimpleRequest\Interfaces\ValidatorInterface;
21
use Mcustiel\SimpleRequest\Annotation\ValidatorAnnotation;
22
use Mcustiel\SimpleRequest\Exception\UnspecifiedValidatorException;
23
24
/**
25
 * Checks that each element of an object or array validates against its corresponding
26
 * validator in a collection, using the name of the property or key.
27
 * <a href="http://spacetelescope.github.io/understanding-json-schema/UnderstandingJSONSchema.pdf">Here</a>
28
 * you can see examples of use for this validator.
29
 *
30
 * @author mcustiel
31
 */
32
class Properties extends AbstractIterableValidator
33
{
34
    const ITEMS_INDEX = 'properties';
35
    const ADDITIONAL_ITEMS_INDEX = 'additionalProperties';
36
37
    /**
38
     * @var bool|\Mcustiel\SimpleRequest\Interfaces\ValidatorInterface
39
     */
40
    private $additionalItems = true;
41
42
    /**
43
     * {@inheritdoc}
44
     *
45
     * @see \Mcustiel\SimpleRequest\Validator\AbstractIterableValidator::setSpecification()
46
     */
47 83
    public function setSpecification($specification = null)
48
    {
49 83
        $this->checkSpecificationIsArray($specification);
50
51 82
        if (isset($specification[self::ITEMS_INDEX])) {
52 81
            $this->setItems($specification[self::ITEMS_INDEX]);
53 79
        }
54 80
        if (isset($specification[self::ADDITIONAL_ITEMS_INDEX])) {
55 80
            $this->setAdditionalItems($specification[self::ADDITIONAL_ITEMS_INDEX]);
56 79
        }
57 79
    }
58
59
    /**
60
     * {@inheritdoc}
61
     *
62
     * @see \Mcustiel\SimpleRequest\Validator\AbstractAnnotationSpecifiedValidator::validate()
63
     */
64 80
    public function validate($value)
65
    {
66 80
        if (!(is_array($value) || $value instanceof \stdClass)) {
67
            return false;
68
        }
69
70
        // From json-schema definition: if "items" is not present, or its value is an object,
71
        // validation of the instance always succeeds, regardless of the value of "additionalItems";
72 80
        if (empty($this->items)) {
73
            return true;
74
        }
75
76 80
        return $this->executePropertiesValidation($this->convertToArray($value));
77
    }
78
79 80
    private function executePropertiesValidation($value)
80
    {
81 80
        if ($this->items instanceof ValidatorInterface) {
82
            return $this->validateWithoutAdditionalItemsConcern($value);
83
        }
84
85
        // From json-schema definition: if the value of "additionalItems" is boolean value false and
86
        // the value of "items" is an array, the instance is valid if its size is less than, or
87
        // equal to, the size of "items".
88 80
        if ($this->additionalItems === false) {
89 80
            return (count($value) <= count($this->items))
90 80
            && $this->validateTuple($value);
91
        }
92
93
        // From json-schema definition: if the value of "additionalItems" is
94
        // boolean value true or an object, validation of the instance always succeeds;
95
        return $this->validateList($value);
96
    }
97
98 80
    private function convertToArray($value)
99
    {
100 80
        if (!is_array($value)) {
101
            return json_decode(json_encode($value), true);
102
        }
103 80
        return $value;
104
    }
105
106
107
    /**
108
     * Checks all properties against a validator.
109
     *
110
     * @param array $array
111
     *
112
     * @return bool
113
     */
114
    private function validateWithoutAdditionalItemsConcern(array $array)
115
    {
116
        foreach ($array as $value) {
117
            if (!$this->items->validate($value)) {
0 ignored issues
show
Bug introduced by
The method validate cannot be called on $this->items (of type array<integer,object<Mcu...es\ValidatorInterface>>).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
118
                return false;
119
            }
120
        }
121
122
        return true;
123
    }
124
125
    /**
126
     * Validates each element against its validator and if additionalItems is a
127
     * validator, validates the rest of the elements against it.
128
     *
129
     * @param array $list
130
     *
131
     * @return bool
132
     */
133
    private function validateList(array $list)
134
    {
135
        if (!$this->validateTuple($list)) {
136
            return false;
137
        }
138
        if ($this->additionalItems === true) {
139
            return true;
140
        }
141
142
        $keys = array_keys($this->items);
143
        $count = count($this->items);
144
        return $this->validateListItems(array_slice($keys, $count, count($list) - $count));
145
    }
146
147
    private function validateListItems($array)
148
    {
149
        foreach ($array as $item) {
150
            if (!$this->additionalItems->validate($item)) {
151
                return false;
152
            }
153
        }
154
        return true;
155
    }
156
157
    /**
158
     * Validate each element of the array against its corresponding validator.
159
     *
160
     * @param array $tuple
161
     *
162
     * @return bool
163
     */
164 79
    private function validateTuple(array $tuple)
165
    {
166 79
        foreach ($this->items as $property => $validator) {
167 79
            if (!$validator->validate(isset($tuple[$property]) ? $tuple[$property] : null)) {
168 1
                return false;
169
            }
170 79
        }
171
172 78
        return true;
173
    }
174
175
    /**
176
     * Checks and sets items specification.
177
     *
178
     * @param array|\Mcustiel\SimpleRequest\Interfaces\ValidatorInterface $specification
179
     */
180 81
    private function setItems($specification)
181
    {
182 81
        if ($specification instanceof ValidatorAnnotation) {
183
            $this->items = $this->createValidatorInstanceFromAnnotation(
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->createValidatorIn...otation($specification) of type object<Mcustiel\SimpleRe...ces\ValidatorInterface> is incompatible with the declared type array<integer,object<Mcu...es\ValidatorInterface>> of property $items.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
184
                $specification
185
            );
186 81
        } elseif (is_array($specification)) {
187 80
            foreach ($specification as $key => $item) {
188 80
                $this->items[$key] = $this->checkIfAnnotationAndReturnObject($item);
189 79
            }
190 79
        } else {
191 1
            throw new UnspecifiedValidatorException(
192 1
                'The validator Properties is being initialized with an invalid ' . self::ITEMS_INDEX . ' parameter'
193 1
            );
194
        }
195 79
    }
196
197
    /**
198
     * Sets the specified additionalItems.
199
     *
200
     * @param bool|\Mcustiel\SimpleRequest\Interfaces\ValidatorInterface $specification
201
     */
202 80
    private function setAdditionalItems($specification)
203
    {
204 80
        if (is_bool($specification)) {
205 79
            $this->additionalItems = $specification;
206 80
        } elseif ($specification instanceof ValidatorAnnotation) {
207
            $this->additionalItems = $this->createValidatorInstanceFromAnnotation(
208
                $specification
209
            );
210
        } else {
211 1
            throw new UnspecifiedValidatorException(
212 1
                'The validator Properties is being initialized with an invalid ' . self::ADDITIONAL_ITEMS_INDEX . ' parameter'
213 1
            );
214
        }
215 79
    }
216
}
217