Passed
Pull Request — master (#58)
by Todd
02:37
created

Schema   F

Complexity

Total Complexity 385

Size/Duplication

Total Lines 1899
Duplicated Lines 0 %

Test Coverage

Coverage 94.4%

Importance

Changes 0
Metric Value
eloc 826
dl 0
loc 1899
ccs 775
cts 821
cp 0.944
rs 1.774
c 0
b 0
f 0
wmc 385

64 Methods

Rating   Name   Duplication   Size   Complexity  
A validateTimestamp() 0 10 5
A validateNull() 0 6 2
A setDescription() 0 3 1
A parseProperties() 0 25 5
A getFlags() 0 2 1
A addValidator() 0 4 1
A setFlags() 0 7 2
A getDescription() 0 2 1
A setID() 0 8 2
A addFilter() 0 4 1
B requireOneOf() 0 53 10
A add() 0 3 1
B getField() 0 21 8
A getID() 0 2 2
A isValid() 0 6 2
A setFlag() 0 7 2
B validateField() 0 31 11
A setTitle() 0 2 1
D parseNode() 0 59 21
A merge() 0 3 1
A getTitle() 0 2 1
A hasFlag() 0 2 1
A validate() 0 23 5
A parseInternal() 0 31 5
B setField() 0 27 8
F mergeInternal() 0 59 28
F parseShortParam() 0 86 28
A getSchemaArray() 0 2 1
A __construct() 0 7 1
A parse() 0 4 1
A createValidation() 0 2 1
A getValidationFactory() 0 2 1
A validateBoolean() 0 8 3
A setValidationClass() 0 17 3
A validateNumber() 0 10 2
A validateEnum() 0 17 3
A callFilters() 0 9 3
A isArray() 0 2 3
B withSparseInternal() 0 27 7
D validateMultipleTypes() 0 64 25
C filterField() 0 28 12
B jsonSerialize() 0 40 10
B validateSingleType() 0 39 11
B parseFieldSelector() 0 28 8
A getRefLookup() 0 2 1
C validateNumberProperties() 0 38 14
B validateObject() 0 32 10
A setRefLookup() 0 3 1
B validateDatetime() 0 28 11
A validateInteger() 0 15 3
A offsetGet() 0 2 2
A setValidationFactory() 0 4 1
A withSparse() 0 3 1
A lookupSchema() 0 25 6
F validateProperties() 0 104 26
A offsetExists() 0 2 1
A offsetUnset() 0 2 1
C validateArray() 0 61 17
A toObjectArray() 0 12 4
A offsetSet() 0 2 1
A getType() 0 10 4
F validateString() 0 88 22
B callValidators() 0 18 7
A getValidationClass() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like Schema often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Schema, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * @author Todd Burry <[email protected]>
4
 * @copyright 2009-2018 Vanilla Forums Inc.
5
 * @license MIT
6
 */
7
8
namespace Garden\Schema;
9
10
/**
11
 * A class for defining and validating data schemas.
12
 */
13
class Schema implements \JsonSerializable, \ArrayAccess {
14
    /**
15
     * Trigger a notice when extraneous properties are encountered during validation.
16
     */
17
    const VALIDATE_EXTRA_PROPERTY_NOTICE = 0x1;
18
19
    /**
20
     * Throw a ValidationException when extraneous properties are encountered during validation.
21
     */
22
    const VALIDATE_EXTRA_PROPERTY_EXCEPTION = 0x2;
23
24
    /**
25
     * @var array All the known types.
26
     *
27
     * If this is ever given some sort of public access then remove the static.
28
     */
29
    private static $types = [
30
        'array' => ['a'],
31
        'object' => ['o'],
32
        'integer' => ['i', 'int'],
33
        'string' => ['s', 'str'],
34
        'number' => ['f', 'float'],
35
        'boolean' => ['b', 'bool'],
36
37
        // Psuedo-types
38
        'timestamp' => ['ts'], // type: integer, format: timestamp
39
        'datetime' => ['dt'], // type: string, format: date-time
40
        'null' => ['n'], // Adds nullable: true
41
    ];
42
43
    /**
44
     * @var string The regular expression to strictly determine if a string is a date.
45
     */
46
    private static $DATE_REGEX = '`^\d{4}-\d{2}-\d{2}([ T]\d{2}:\d{2}(:\d{2})?)?`i';
47
48
    private $schema = [];
49
50
    /**
51
     * @var int A bitwise combination of the various **Schema::FLAG_*** constants.
52
     */
53
    private $flags = 0;
54
55
    /**
56
     * @var array An array of callbacks that will filter data in the schema.
57
     */
58
    private $filters = [];
59
60
    /**
61
     * @var array An array of callbacks that will custom validate the schema.
62
     */
63
    private $validators = [];
64
65
    /**
66
     * @var string|Validation The name of the class or an instance that will be cloned.
67
     * @deprecated
68
     */
69
    private $validationClass = Validation::class;
70
71
    /**
72
     * @var callable A callback is used to create validation objects.
73
     */
74
    private $validationFactory;
75
76
    /**
77
     * @var callable
78
     */
79
    private $refLookup;
80
81
    /// Methods ///
82
83
    /**
84
     * Initialize an instance of a new {@link Schema} class.
85
     *
86
     * @param array $schema The array schema to validate against.
87
     */
88 264
    public function __construct(array $schema = []) {
89 264
        $this->schema = $schema;
90
        $this->refLookup = function (string $name) {
0 ignored issues
show
Unused Code introduced by
The parameter $name is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

90
        $this->refLookup = function (/** @scrutinizer ignore-unused */ string $name) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
91
            return null;
92
        };
93
        $this->validationFactory = function () {
94 206
            return new Validation();
95
        };
96 264
    }
97
98
    /**
99
     * Grab the schema's current description.
100
     *
101
     * @return string
102
     */
103 1
    public function getDescription(): string {
104 1
        return $this->schema['description'] ?? '';
105
    }
106
107
    /**
108
     * Set the description for the schema.
109
     *
110
     * @param string $description The new description.
111
     * @return $this
112
     */
113 1
    public function setDescription(string $description) {
114 1
        $this->schema['description'] = $description;
115 1
        return $this;
116
    }
117
118
    /**
119
     * Get the schema's title.
120
     *
121
     * @return string Returns the title.
122
     */
123
    public function getTitle(): string {
124
        return $this->schema['title'] ?? '';
125
    }
126
127
    /**
128
     * Set the schema's title.
129
     *
130
     * @param string $title The new title.
131
     */
132
    public function setTitle(string $title) {
133
        $this->schema['title'] = $title;
134
    }
135
136
    /**
137
     * Get a schema field.
138
     *
139
     * @param string|array $path The JSON schema path of the field with parts separated by dots.
140
     * @param mixed $default The value to return if the field isn't found.
141
     * @return mixed Returns the field value or `$default`.
142
     */
143 10
    public function getField($path, $default = null) {
144 10
        if (is_string($path)) {
145 10
            if (strpos($path, '.') !== false && strpos($path, '/') === false) {
146 1
                trigger_error('Field selectors must be separated by "/" instead of "."', E_USER_DEPRECATED);
147 1
                $path = explode('.', $path);
148
            } else {
149 9
                $path = explode('/', $path);
150
            }
151
        }
152
153 10
        $value = $this->schema;
154 10
        foreach ($path as $i => $subKey) {
155 10
            if (is_array($value) && isset($value[$subKey])) {
156 10
                $value = $value[$subKey];
157 1
            } elseif ($value instanceof Schema) {
158 1
                return $value->getField(array_slice($path, $i), $default);
159
            } else {
160 10
                return $default;
161
            }
162
        }
163 10
        return $value;
164
    }
165
166
    /**
167
     * Set a schema field.
168
     *
169
     * @param string|array $path The JSON schema path of the field with parts separated by slashes.
170
     * @param mixed $value The new value.
171
     * @return $this
172
     */
173 4
    public function setField($path, $value) {
174 4
        if (is_string($path)) {
175 4
            if (strpos($path, '.') !== false && strpos($path, '/') === false) {
176 1
                trigger_error('Field selectors must be separated by "/" instead of "."', E_USER_DEPRECATED);
177 1
                $path = explode('.', $path);
178
            } else {
179 3
                $path = explode('/', $path);
180
            }
181
        }
182
183 4
        $selection = &$this->schema;
184 4
        foreach ($path as $i => $subSelector) {
185 4
            if (is_array($selection)) {
186 4
                if (!isset($selection[$subSelector])) {
187 4
                    $selection[$subSelector] = [];
188
                }
189 1
            } elseif ($selection instanceof Schema) {
190 1
                $selection->setField(array_slice($path, $i), $value);
191 1
                return $this;
192
            } else {
193
                $selection = [$subSelector => []];
194
            }
195 4
            $selection = &$selection[$subSelector];
196
        }
197
198 4
        $selection = $value;
199 4
        return $this;
200
    }
201
202
    /**
203
     * Get the ID for the schema.
204
     *
205
     * @return string
206
     */
207 3
    public function getID(): string {
208 3
        return isset($this->schema['id']) ? $this->schema['id'] : '';
209
    }
210
211
    /**
212
     * Set the ID for the schema.
213
     *
214
     * @param string $id The new ID.
215
     * @throws \InvalidArgumentException Throws an exception when the provided ID is not a string.
216
     * @return Schema
217
     */
218 1
    public function setID(string $id) {
219 1
        if (is_string($id)) {
0 ignored issues
show
introduced by
The condition is_string($id) is always true.
Loading history...
220 1
            $this->schema['id'] = $id;
221
        } else {
222
            throw new \InvalidArgumentException("The ID is not a valid string.", 500);
223
        }
224
225 1
        return $this;
226
    }
227
228
    /**
229
     * Return the validation flags.
230
     *
231
     * @return int Returns a bitwise combination of flags.
232
     */
233 1
    public function getFlags(): int {
234 1
        return $this->flags;
235
    }
236
237
    /**
238
     * Set the validation flags.
239
     *
240
     * @param int $flags One or more of the **Schema::FLAG_*** constants.
241
     * @return Schema Returns the current instance for fluent calls.
242
     */
243 7
    public function setFlags(int $flags) {
244 7
        if (!is_int($flags)) {
0 ignored issues
show
introduced by
The condition is_int($flags) is always true.
Loading history...
245
            throw new \InvalidArgumentException('Invalid flags.', 500);
246
        }
247 7
        $this->flags = $flags;
248
249 7
        return $this;
250
    }
251
252
    /**
253
     * Whether or not the schema has a flag (or combination of flags).
254
     *
255
     * @param int $flag One or more of the **Schema::VALIDATE_*** constants.
256
     * @return bool Returns **true** if all of the flags are set or **false** otherwise.
257
     */
258 12
    public function hasFlag(int $flag): bool {
259 12
        return ($this->flags & $flag) === $flag;
260
    }
261
262
    /**
263
     * Set a flag.
264
     *
265
     * @param int $flag One or more of the **Schema::VALIDATE_*** constants.
266
     * @param bool $value Either true or false.
267
     * @return $this
268
     */
269 1
    public function setFlag(int $flag, bool $value) {
270 1
        if ($value) {
271 1
            $this->flags = $this->flags | $flag;
272
        } else {
273 1
            $this->flags = $this->flags & ~$flag;
274
        }
275 1
        return $this;
276
    }
277
278
    /**
279
     * Merge a schema with this one.
280
     *
281
     * @param Schema $schema A scheme instance. Its parameters will be merged into the current instance.
282
     * @return $this
283
     */
284 4
    public function merge(Schema $schema) {
285 4
        $this->mergeInternal($this->schema, $schema->getSchemaArray(), true, true);
286 4
        return $this;
287
    }
288
289
    /**
290
     * Add another schema to this one.
291
     *
292
     * Adding schemas together is analogous to array addition. When you add a schema it will only add missing information.
293
     *
294
     * @param Schema $schema The schema to add.
295
     * @param bool $addProperties Whether to add properties that don't exist in this schema.
296
     * @return $this
297
     */
298 4
    public function add(Schema $schema, $addProperties = false) {
299 4
        $this->mergeInternal($this->schema, $schema->getSchemaArray(), false, $addProperties);
300 4
        return $this;
301
    }
302
303
    /**
304
     * The internal implementation of schema merging.
305
     *
306
     * @param array &$target The target of the merge.
307
     * @param array $source The source of the merge.
308
     * @param bool $overwrite Whether or not to replace values.
309
     * @param bool $addProperties Whether or not to add object properties to the target.
310
     * @return array
311
     */
312 7
    private function mergeInternal(array &$target, array $source, $overwrite = true, $addProperties = true) {
313
        // We need to do a fix for required properties here.
314 7
        if (isset($target['properties']) && !empty($source['required'])) {
315 5
            $required = isset($target['required']) ? $target['required'] : [];
316
317 5
            if (isset($source['required']) && $addProperties) {
318 4
                $newProperties = array_diff(array_keys($source['properties']), array_keys($target['properties']));
319 4
                $newRequired = array_intersect($source['required'], $newProperties);
320
321 4
                $required = array_merge($required, $newRequired);
322
            }
323
        }
324
325
326 7
        foreach ($source as $key => $val) {
327 7
            if (is_array($val) && array_key_exists($key, $target) && is_array($target[$key])) {
328 7
                if ($key === 'properties' && !$addProperties) {
329
                    // We just want to merge the properties that exist in the destination.
330 2
                    foreach ($val as $name => $prop) {
331 2
                        if (isset($target[$key][$name])) {
332 2
                            $targetProp = &$target[$key][$name];
333
334 2
                            if (is_array($targetProp) && is_array($prop)) {
335 2
                                $this->mergeInternal($targetProp, $prop, $overwrite, $addProperties);
336 1
                            } elseif (is_array($targetProp) && $prop instanceof Schema) {
337
                                $this->mergeInternal($targetProp, $prop->getSchemaArray(), $overwrite, $addProperties);
338 1
                            } elseif ($overwrite) {
339 2
                                $targetProp = $prop;
340
                            }
341
                        }
342
                    }
343 7
                } elseif (isset($val[0]) || isset($target[$key][0])) {
344 5
                    if ($overwrite) {
345
                        // This is a numeric array, so just do a merge.
346 3
                        $merged = array_merge($target[$key], $val);
347 3
                        if (is_string($merged[0])) {
348 3
                            $merged = array_keys(array_flip($merged));
349
                        }
350 5
                        $target[$key] = $merged;
351
                    }
352
                } else {
353 7
                    $target[$key] = $this->mergeInternal($target[$key], $val, $overwrite, $addProperties);
354
                }
355 7
            } elseif (!$overwrite && array_key_exists($key, $target) && !is_array($val)) {
356
                // Do nothing, we aren't replacing.
357
            } else {
358 7
                $target[$key] = $val;
359
            }
360
        }
361
362 7
        if (isset($required)) {
363 5
            if (empty($required)) {
364 1
                unset($target['required']);
365
            } else {
366 5
                $target['required'] = $required;
367
            }
368
        }
369
370 7
        return $target;
371
    }
372
373
//    public function overlay(Schema $schema )
374
375
    /**
376
     * Returns the internal schema array.
377
     *
378
     * @return array
379
     * @see Schema::jsonSerialize()
380
     */
381 17
    public function getSchemaArray(): array {
382 17
        return $this->schema;
383
    }
384
385
    /**
386
     * Parse a short schema and return the associated schema.
387
     *
388
     * @param array $arr The schema array.
389
     * @param mixed[] $args Constructor arguments for the schema instance.
390
     * @return static Returns a new schema.
391
     */
392 178
    public static function parse(array $arr, ...$args) {
393 178
        $schema = new static([], ...$args);
0 ignored issues
show
Unused Code introduced by
The call to Garden\Schema\Schema::__construct() has too many arguments starting with $args. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

393
        $schema = /** @scrutinizer ignore-call */ new static([], ...$args);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
394 178
        $schema->schema = $schema->parseInternal($arr);
395 177
        return $schema;
396
    }
397
398
    /**
399
     * Parse a schema in short form into a full schema array.
400
     *
401
     * @param array $arr The array to parse into a schema.
402
     * @return array The full schema array.
403
     * @throws \InvalidArgumentException Throws an exception when an item in the schema is invalid.
404
     */
405 178
    protected function parseInternal(array $arr): array {
406 178
        if (empty($arr)) {
407
            // An empty schema validates to anything.
408 6
            return [];
409 173
        } elseif (isset($arr['type'])) {
410
            // This is a long form schema and can be parsed as the root.
411 2
            return $this->parseNode($arr);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->parseNode($arr) could return the type ArrayAccess which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
412
        } else {
413
            // Check for a root schema.
414 172
            $value = reset($arr);
415 172
            $key = key($arr);
416 172
            if (is_int($key)) {
417 107
                $key = $value;
418 107
                $value = null;
419
            }
420 172
            list ($name, $param) = $this->parseShortParam($key, $value);
421 171
            if (empty($name)) {
422 63
                return $this->parseNode($param, $value);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->parseNode($param, $value) could return the type ArrayAccess which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
423
            }
424
        }
425
426
        // If we are here then this is n object schema.
427 111
        list($properties, $required) = $this->parseProperties($arr);
428
429
        $result = [
430 111
            'type' => 'object',
431 111
            'properties' => $properties,
432 111
            'required' => $required
433
        ];
434
435 111
        return array_filter($result);
436
    }
437
438
    /**
439
     * Parse a schema node.
440
     *
441
     * @param array $node The node to parse.
442
     * @param mixed $value Additional information from the node.
443
     * @return array|\ArrayAccess Returns a JSON schema compatible node.
444
     */
445 172
    private function parseNode($node, $value = null) {
446 172
        if (is_array($value)) {
447 66
            if (is_array($node['type'])) {
448
                trigger_error('Schemas with multiple types is deprecated.', E_USER_DEPRECATED);
449
            }
450
451
            // The value describes a bit more about the schema.
452 66
            switch ($node['type']) {
453 66
                case 'array':
454 11
                    if (isset($value['items'])) {
455
                        // The value includes array schema information.
456 4
                        $node = array_replace($node, $value);
457
                    } else {
458 7
                        $node['items'] = $this->parseInternal($value);
459
                    }
460 11
                    break;
461 56
                case 'object':
462
                    // The value is a schema of the object.
463 12
                    if (isset($value['properties'])) {
464
                        list($node['properties']) = $this->parseProperties($value['properties']);
465
                    } else {
466 12
                        list($node['properties'], $required) = $this->parseProperties($value);
467 12
                        if (!empty($required)) {
468 12
                            $node['required'] = $required;
469
                        }
470
                    }
471 12
                    break;
472
                default:
473 44
                    $node = array_replace($node, $value);
474 66
                    break;
475
            }
476 132
        } elseif (is_string($value)) {
477 102
            if ($node['type'] === 'array' && $arrType = $this->getType($value)) {
478 6
                $node['items'] = ['type' => $arrType];
479 98
            } elseif (!empty($value)) {
480 102
                $node['description'] = $value;
481
            }
482 35
        } elseif ($value === null) {
483
            // Parse child elements.
484 31
            if ($node['type'] === 'array' && isset($node['items'])) {
485
                // The value includes array schema information.
486
                $node['items'] = $this->parseInternal($node['items']);
487 31
            } elseif ($node['type'] === 'object' && isset($node['properties'])) {
488 1
                list($node['properties']) = $this->parseProperties($node['properties']);
489
            }
490
        }
491
492 172
        if (is_array($node)) {
493 171
            if (!empty($node['allowNull'])) {
494 1
                $node['nullable'] = true;
495
            }
496 171
            unset($node['allowNull']);
497
498 171
            if ($node['type'] === null || $node['type'] === []) {
499 4
                unset($node['type']);
500
            }
501
        }
502
503 172
        return $node;
504
    }
505
506
    /**
507
     * Parse the schema for an object's properties.
508
     *
509
     * @param array $arr An object property schema.
510
     * @return array Returns a schema array suitable to be placed in the **properties** key of a schema.
511
     */
512 112
    private function parseProperties(array $arr): array {
513 112
        $properties = [];
514 112
        $requiredProperties = [];
515 112
        foreach ($arr as $key => $value) {
516
            // Fix a schema specified as just a value.
517 112
            if (is_int($key)) {
518 82
                if (is_string($value)) {
519 82
                    $key = $value;
520 82
                    $value = '';
521
                } else {
522
                    throw new \InvalidArgumentException("Schema at position $key is not a valid parameter.", 500);
523
                }
524
            }
525
526
            // The parameter is defined in the key.
527 112
            list($name, $param, $required) = $this->parseShortParam($key, $value);
0 ignored issues
show
Bug introduced by
$value of type string is incompatible with the type array expected by parameter $value of Garden\Schema\Schema::parseShortParam(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

527
            list($name, $param, $required) = $this->parseShortParam($key, /** @scrutinizer ignore-type */ $value);
Loading history...
528
529 112
            $node = $this->parseNode($param, $value);
530
531 112
            $properties[$name] = $node;
532 112
            if ($required) {
533 112
                $requiredProperties[] = $name;
534
            }
535
        }
536 112
        return [$properties, $requiredProperties];
537
    }
538
539
    /**
540
     * Parse a short parameter string into a full array parameter.
541
     *
542
     * @param string $key The short parameter string to parse.
543
     * @param array $value An array of other information that might help resolve ambiguity.
544
     * @return array Returns an array in the form `[string name, array param, bool required]`.
545
     * @throws \InvalidArgumentException Throws an exception if the short param is not in the correct format.
546
     */
547 173
    public function parseShortParam(string $key, $value = []): array {
548
        // Is the parameter optional?
549 173
        if (substr($key, -1) === '?') {
550 70
            $required = false;
551 70
            $key = substr($key, 0, -1);
552
        } else {
553 125
            $required = true;
554
        }
555
556
        // Check for a type.
557 173
        if (false !== ($pos = strrpos($key, ':'))) {
558 167
            $name = substr($key, 0, $pos);
559 167
            $typeStr = substr($key, $pos + 1);
560
561
            // Kludge for names with colons that are not specifying an array of a type.
562 167
            if (isset($value['type']) && 'array' !== $this->getType($typeStr)) {
563 2
                $name = $key;
564 167
                $typeStr = '';
565
            }
566
        } else {
567 16
            $name = $key;
568 16
            $typeStr = '';
569
        }
570 173
        $types = [];
571 173
        $param = [];
572
573 173
        if (!empty($typeStr)) {
574 165
            $shortTypes = explode('|', $typeStr);
575 165
            foreach ($shortTypes as $alias) {
576 165
                $found = $this->getType($alias);
577 165
                if ($found === null) {
578
                    throw new \InvalidArgumentException("Unknown type '$alias'", 500);
579 165
                } elseif ($found === 'datetime') {
580 9
                    $param['format'] = 'date-time';
581 9
                    $types[] = 'string';
582 157
                } elseif ($found === 'timestamp') {
583 12
                    $param['format'] = 'timestamp';
584 12
                    $types[] = 'integer';
585 151
                } elseif ($found === 'null') {
586 11
                    $nullable = true;
587
                } else {
588 165
                    $types[] = $found;
589
                }
590
            }
591
        }
592
593 173
        if ($value instanceof Schema) {
594 6
            if (count($types) === 1 && $types[0] === 'array') {
595 1
                $param += ['type' => $types[0], 'items' => $value];
596
            } else {
597 6
                $param = $value;
598
            }
599 171
        } elseif (isset($value['type'])) {
600 10
            $param = $value + $param;
601
602 10
            if (!empty($types) && $types !== (array)$param['type']) {
603
                $typesStr = implode('|', $types);
604
                $paramTypesStr = implode('|', (array)$param['type']);
605
606 10
                throw new \InvalidArgumentException("Type mismatch between $typesStr and {$paramTypesStr} for field $name.", 500);
607
            }
608
        } else {
609 166
            if (empty($types) && !empty($parts[1])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $parts seems to never exist and therefore empty should always be true.
Loading history...
610
                throw new \InvalidArgumentException("Invalid type {$parts[1]} for field $name.", 500);
611
            }
612 166
            if (empty($types)) {
613 4
                $param += ['type' => null];
614
            } else {
615 165
                $param += ['type' => count($types) === 1 ? $types[0] : $types];
616
            }
617
618
            // Parsed required strings have a minimum length of 1.
619 166
            if (in_array('string', $types) && !empty($name) && $required && (!isset($value['default']) || $value['default'] !== '')) {
620 41
                $param['minLength'] = 1;
621
            }
622
        }
623
624 173
        if (!empty($nullable)) {
625 11
            $param['nullable'] = true;
626
        }
627
628 173
        if (is_array($param['type'])) {
629 1
            trigger_error('Schemas with multiple types is deprecated.', E_USER_DEPRECATED);
630
        }
631
632 172
        return [$name, $param, $required];
633
    }
634
635
    /**
636
     * Add a custom filter to change data before validation.
637
     *
638
     * @param string $fieldname The name of the field to filter, if any.
639
     *
640
     * If you are adding a filter to a deeply nested field then separate the path with dots.
641
     * @param callable $callback The callback to filter the field.
642
     * @return $this
643
     */
644 2
    public function addFilter(string $fieldname, callable $callback) {
645 2
        $fieldname = $this->parseFieldSelector($fieldname);
646 2
        $this->filters[$fieldname][] = $callback;
647 2
        return $this;
648
    }
649
650
    /**
651
     * Add a custom validator to to validate the schema.
652
     *
653
     * @param string $fieldname The name of the field to validate, if any.
654
     *
655
     * If you are adding a validator to a deeply nested field then separate the path with dots.
656
     * @param callable $callback The callback to validate with.
657
     * @return Schema Returns `$this` for fluent calls.
658
     */
659 5
    public function addValidator(string $fieldname, callable $callback) {
660 5
        $fieldname = $this->parseFieldSelector($fieldname);
661 5
        $this->validators[$fieldname][] = $callback;
662 5
        return $this;
663
    }
664
665
    /**
666
     * Require one of a given set of fields in the schema.
667
     *
668
     * @param array $required The field names to require.
669
     * @param string $fieldname The name of the field to attach to.
670
     * @param int $count The count of required items.
671
     * @return Schema Returns `$this` for fluent calls.
672
     */
673 3
    public function requireOneOf(array $required, string $fieldname = '', int $count = 1) {
674 3
        $result = $this->addValidator(
675 3
            $fieldname,
676
            function ($data, ValidationField $field) use ($required, $count) {
677
                // This validator does not apply to sparse validation.
678 3
                if ($field->isSparse()) {
679 1
                    return true;
680
                }
681
682 2
                $hasCount = 0;
683 2
                $flattened = [];
684
685 2
                foreach ($required as $name) {
686 2
                    $flattened = array_merge($flattened, (array)$name);
687
688 2
                    if (is_array($name)) {
689
                        // This is an array of required names. They all must match.
690 1
                        $hasCountInner = 0;
691 1
                        foreach ($name as $nameInner) {
692 1
                            if (array_key_exists($nameInner, $data)) {
693 1
                                $hasCountInner++;
694
                            } else {
695 1
                                break;
696
                            }
697
                        }
698 1
                        if ($hasCountInner >= count($name)) {
699 1
                            $hasCount++;
700
                        }
701 2
                    } elseif (array_key_exists($name, $data)) {
702 1
                        $hasCount++;
703
                    }
704
705 2
                    if ($hasCount >= $count) {
706 2
                        return true;
707
                    }
708
                }
709
710 2
                if ($count === 1) {
711 1
                    $message = 'One of {required} are required.';
712
                } else {
713 1
                    $message = '{count} of {required} are required.';
714
                }
715
716 2
                $field->addError('missingField', [
717 2
                    'messageCode' => $message,
718 2
                    'required' => $required,
719 2
                    'count' => $count
720
                ]);
721 2
                return false;
722 3
            }
723
        );
724
725 3
        return $result;
726
    }
727
728
    /**
729
     * Validate data against the schema.
730
     *
731
     * @param mixed $data The data to validate.
732
     * @param array $options Validation options.
733
     *
734
     * - **sparse**: Whether or not this is a sparse validation.
735
     * @return mixed Returns a cleaned version of the data.
736
     * @throws ValidationException Throws an exception when the data does not validate against the schema.
737
     * @throws RefNotFoundException Throws an exception when a schema `$ref` is not found.
738
     */
739 211
    public function validate($data, $options = []) {
740 211
        if (is_bool($options)) {
0 ignored issues
show
introduced by
The condition is_bool($options) is always false.
Loading history...
741 1
            trigger_error('The $sparse parameter is deprecated. Use [\'sparse\' => true] instead.', E_USER_DEPRECATED);
742 1
            $options = ['sparse' => true];
743
        }
744 211
        $options += ['sparse' => false];
745
746
747 211
        list($schema, $schemaPath) = $this->lookupSchema($this->schema, '');
748 208
        $field = new ValidationField($this->createValidation(), $schema, '', $schemaPath, $options);
749
750 208
        $clean = $this->validateField($data, $field);
751
752 206
        if (Invalid::isInvalid($clean) && $field->isValid()) {
753
            // This really shouldn't happen, but we want to protect against seeing the invalid object.
754
            $field->addError('invalid', ['messageCode' => '{field} is invalid.']);
755
        }
756
757 206
        if (!$field->getValidation()->isValid()) {
758 71
            throw new ValidationException($field->getValidation());
759
        }
760
761 150
        return $clean;
762
    }
763
764
    /**
765
     * Validate data against the schema and return the result.
766
     *
767
     * @param mixed $data The data to validate.
768
     * @param array $options Validation options. See `Schema::validate()`.
769
     * @return bool Returns true if the data is valid. False otherwise.
770
     */
771 44
    public function isValid($data, $options = []) {
772
        try {
773 44
            $this->validate($data, $options);
774 31
            return true;
775 23
        } catch (ValidationException $ex) {
776 23
            return false;
777
        }
778
    }
779
780
    /**
781
     * Validate a field.
782
     *
783
     * @param mixed $value The value to validate.
784
     * @param ValidationField $field A validation object to add errors to.
785
     * @return mixed|Invalid Returns a clean version of the value with all extra fields stripped out or invalid if the value
786
     * is completely invalid.
787
     */
788 208
    protected function validateField($value, ValidationField $field) {
789 208
        $result = $value = $this->filterField($value, $field);
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
790
791 208
        if ($field->getField() instanceof Schema) {
792
            try {
793 5
                $result = $field->getField()->validate($value, $field->getOptions());
794 2
            } catch (ValidationException $ex) {
795
                // The validation failed, so merge the validations together.
796 5
                $field->getValidation()->merge($ex->getValidation(), $field->getName());
797
            }
798 208
        } elseif (($value === null || ($value === '' && !$field->hasType('string'))) && ($field->val('nullable') || $field->hasType('null'))) {
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: ($value === null || $val...$field->hasType('null'), Probably Intended Meaning: $value === null || ($val...field->hasType('null'))
Loading history...
799 13
            $result = null;
800
        } else {
801
            // Validate the field's type.
802 208
            $type = $field->getType();
803 208
            if (is_array($type)) {
804 29
                $result = $this->validateMultipleTypes($value, $type, $field);
805
            } else {
806 187
                $result = $this->validateSingleType($value, $type, $field);
807
            }
808 208
            if (Invalid::isValid($result)) {
809 199
                $result = $this->validateEnum($result, $field);
810
            }
811
        }
812
813
        // Validate a custom field validator.
814 208
        if (Invalid::isValid($result)) {
815 199
            $this->callValidators($result, $field);
816
        }
817
818 208
        return $result;
819
    }
820
821
    /**
822
     * Validate an array.
823
     *
824
     * @param mixed $value The value to validate.
825
     * @param ValidationField $field The validation results to add.
826
     * @return array|Invalid Returns an array or invalid if validation fails.
827
     * @throws RefNotFoundException Throws an exception if the array has an items `$ref` that cannot be found.
828
     */
829 34
    protected function validateArray($value, ValidationField $field) {
830 34
        if ((!is_array($value) || (count($value) > 0 && !array_key_exists(0, $value))) && !$value instanceof \Traversable) {
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: (! is_array($value) || c... instanceof Traversable, Probably Intended Meaning: ! is_array($value) || (c...instanceof Traversable)
Loading history...
831 6
            $field->addTypeError($value, 'array');
832 6
            return Invalid::value();
833
        } else {
834 29
            if ((null !== $minItems = $field->val('minItems')) && count($value) < $minItems) {
0 ignored issues
show
Bug introduced by
It seems like $value can also be of type Traversable; however, parameter $var of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

834
            if ((null !== $minItems = $field->val('minItems')) && count(/** @scrutinizer ignore-type */ $value) < $minItems) {
Loading history...
835 1
                $field->addError(
836 1
                    'minItems',
837
                    [
838 1
                        'messageCode' => '{field} must contain at least {minItems} {minItems,plural,item}.',
839 1
                        'minItems' => $minItems,
840
                    ]
841
                );
842
            }
843 29
            if ((null !== $maxItems = $field->val('maxItems')) && count($value) > $maxItems) {
844 1
                $field->addError(
845 1
                    'maxItems',
846
                    [
847 1
                        'messageCode' => '{field} must contain no more than {maxItems} {maxItems,plural,item}.',
848 1
                        'maxItems' => $maxItems,
849
                    ]
850
                );
851
            }
852
853 29
            if ($field->val('uniqueItems') && count($value) > count(array_unique($value))) {
0 ignored issues
show
Bug introduced by
It seems like $value can also be of type Traversable; however, parameter $array of array_unique() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

853
            if ($field->val('uniqueItems') && count($value) > count(array_unique(/** @scrutinizer ignore-type */ $value))) {
Loading history...
854 1
                $field->addError(
855 1
                    'uniqueItems',
856
                    [
857 1
                        'messageCode' => '{field} must contain unique items.',
858
                    ]
859
                );
860
            }
861
862 29
            if ($field->val('items') !== null) {
863 21
                list ($items, $schemaPath) = $this->lookupSchema($field->val('items'), $field->getSchemaPath().'/items');
864
865
                // Validate each of the types.
866 21
                $itemValidation = new ValidationField(
867 21
                    $field->getValidation(),
868 21
                    $items,
869 21
                    '',
870 21
                    $schemaPath,
871 21
                    $field->getOptions()
872
                );
873
874 21
                $result = [];
875 21
                $count = 0;
876 21
                foreach ($value as $i => $item) {
877 21
                    $itemValidation->setName($field->getName()."/$i");
878 21
                    $validItem = $this->validateField($item, $itemValidation);
879 21
                    if (Invalid::isValid($validItem)) {
880 21
                        $result[] = $validItem;
881
                    }
882 21
                    $count++;
883
                }
884
885 21
                return empty($result) && $count > 0 ? Invalid::value() : $result;
886
            } else {
887
                // Cast the items into a proper numeric array.
888 8
                $result = is_array($value) ? array_values($value) : iterator_to_array($value);
889 8
                return $result;
890
            }
891
        }
892
    }
893
894
    /**
895
     * Validate a boolean value.
896
     *
897
     * @param mixed $value The value to validate.
898
     * @param ValidationField $field The validation results to add.
899
     * @return bool|Invalid Returns the cleaned value or invalid if validation fails.
900
     */
901 32
    protected function validateBoolean($value, ValidationField $field) {
902 32
        $value = $value === null ? $value : filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
903 32
        if ($value === null) {
904 4
            $field->addTypeError($value, 'boolean');
905 4
            return Invalid::value();
906
        }
907
908 29
        return $value;
909
    }
910
911
    /**
912
     * Validate a date time.
913
     *
914
     * @param mixed $value The value to validate.
915
     * @param ValidationField $field The validation results to add.
916
     * @return \DateTimeInterface|Invalid Returns the cleaned value or **null** if it isn't valid.
917
     */
918 14
    protected function validateDatetime($value, ValidationField $field) {
919 14
        if ($value instanceof \DateTimeInterface) {
920
            // do nothing, we're good
921 11
        } elseif (is_string($value) && $value !== '' && !is_numeric($value)) {
922
            try {
923 7
                $dt = new \DateTimeImmutable($value);
924 6
                if ($dt) {
0 ignored issues
show
introduced by
$dt is of type DateTimeImmutable, thus it always evaluated to true.
Loading history...
925 6
                    $value = $dt;
926
                } else {
927 6
                    $value = null;
928
                }
929 1
            } catch (\Throwable $ex) {
930 7
                $value = Invalid::value();
931
            }
932 4
        } elseif (is_int($value) && $value > 0) {
933
            try {
934 1
                $value = new \DateTimeImmutable('@'.(string)round($value));
935
            } catch (\Throwable $ex) {
936 1
                $value = Invalid::value();
937
            }
938
        } else {
939 3
            $value = Invalid::value();
940
        }
941
942 14
        if (Invalid::isInvalid($value)) {
943 4
            $field->addTypeError($value, 'datetime');
944
        }
945 14
        return $value;
946
    }
947
948
    /**
949
     * Validate a float.
950
     *
951
     * @param mixed $value The value to validate.
952
     * @param ValidationField $field The validation results to add.
953
     * @return float|Invalid Returns a number or **null** if validation fails.
954
     */
955 17
    protected function validateNumber($value, ValidationField $field) {
956 17
        $result = filter_var($value, FILTER_VALIDATE_FLOAT);
957 17
        if ($result === false) {
958 4
            $field->addTypeError($value, 'number');
959 4
            return Invalid::value();
960
        }
961
962 13
        $result = $this->validateNumberProperties($result, $field);
963
964 13
        return $result;
965
    }
966
    /**
967
     * Validate and integer.
968
     *
969
     * @param mixed $value The value to validate.
970
     * @param ValidationField $field The validation results to add.
971
     * @return int|Invalid Returns the cleaned value or **null** if validation fails.
972
     */
973 58
    protected function validateInteger($value, ValidationField $field) {
974 58
        if ($field->val('format') === 'timestamp') {
975 7
            return $this->validateTimestamp($value, $field);
976
        }
977
978 53
        $result = filter_var($value, FILTER_VALIDATE_INT);
979
980 53
        if ($result === false) {
981 10
            $field->addTypeError($value, 'integer');
982 10
            return Invalid::value();
983
        }
984
985 47
        $result = $this->validateNumberProperties($result, $field);
986
987 47
        return $result;
988
    }
989
990
    /**
991
     * Validate an object.
992
     *
993
     * @param mixed $value The value to validate.
994
     * @param ValidationField $field The validation results to add.
995
     * @return object|Invalid Returns a clean object or **null** if validation fails.
996
     */
997 114
    protected function validateObject($value, ValidationField $field) {
998 114
        if (!$this->isArray($value) || isset($value[0])) {
999 6
            $field->addTypeError($value, 'object');
1000 6
            return Invalid::value();
1001 114
        } elseif (is_array($field->val('properties')) || null !== $field->val('additionalProperties')) {
1002
            // Validate the data against the internal schema.
1003 107
            $value = $this->validateProperties($value, $field);
1004 7
        } elseif (!is_array($value)) {
1005 3
            $value = $this->toObjectArray($value);
1006
        }
1007
1008 112
        if (($maxProperties = $field->val('maxProperties')) && count($value) > $maxProperties) {
1009 1
            $field->addError(
1010 1
                'maxItems',
1011
                [
1012 1
                    'messageCode' => '{field} must contain no more than {maxProperties} {maxProperties,plural,item}.',
1013 1
                    'maxItems' => $maxProperties,
1014
                ]
1015
            );
1016
        }
1017
1018 112
        if (($minProperties = $field->val('minProperties')) && count($value) < $minProperties) {
1019 1
            $field->addError(
1020 1
                'minItems',
1021
                [
1022 1
                    'messageCode' => '{field} must contain at least {minProperties} {minProperties,plural,item}.',
1023 1
                    'minItems' => $minProperties,
1024
                ]
1025
            );
1026
        }
1027
1028 112
        return $value;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $value returns the type array which is incompatible with the documented return type object|Garden\Schema\Invalid.
Loading history...
1029
    }
1030
1031
    /**
1032
     * Validate data against the schema and return the result.
1033
     *
1034
     * @param array|\Traversable|\ArrayAccess $data The data to validate.
1035
     * @param ValidationField $field This argument will be filled with the validation result.
1036
     * @return array|Invalid Returns a clean array with only the appropriate properties and the data coerced to proper types.
1037
     * or invalid if there are no valid properties.
1038
     * @throws RefNotFoundException Throws an exception of a property or additional property has a `$ref` that cannot be found.
1039
     */
1040 107
    protected function validateProperties($data, ValidationField $field) {
1041 107
        $properties = $field->val('properties', []);
1042 107
        $additionalProperties = $field->val('additionalProperties');
1043 107
        $required = array_flip($field->val('required', []));
1044 107
        $isRequest = $field->isRequest();
1045 107
        $isResponse = $field->isResponse();
1046
1047 107
        if (is_array($data)) {
1048 103
            $keys = array_keys($data);
1049 103
            $clean = [];
1050
        } else {
1051 4
            $keys = array_keys(iterator_to_array($data));
0 ignored issues
show
Bug introduced by
It seems like $data can also be of type ArrayAccess; however, parameter $iterator of iterator_to_array() does only seem to accept Traversable, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1051
            $keys = array_keys(iterator_to_array(/** @scrutinizer ignore-type */ $data));
Loading history...
1052 4
            $class = get_class($data);
1053 4
            $clean = new $class;
1054
1055 4
            if ($clean instanceof \ArrayObject && $data instanceof \ArrayObject) {
1056 3
                $clean->setFlags($data->getFlags());
1057 3
                $clean->setIteratorClass($data->getIteratorClass());
1058
            }
1059
        }
1060 107
        $keys = array_combine(array_map('strtolower', $keys), $keys);
1061
1062 107
        $propertyField = new ValidationField($field->getValidation(), [], '', '', $field->getOptions());
1063
1064
        // Loop through the schema fields and validate each one.
1065 107
        foreach ($properties as $propertyName => $property) {
1066 105
            list($property, $schemaPath) = $this->lookupSchema($property, $field->getSchemaPath().'/properties/'.$propertyField->escapeRef($propertyName));
1067
1068
            $propertyField
1069 105
                ->setField($property)
1070 105
                ->setName(ltrim($field->getName().'/'.$propertyField->escapeRef($propertyName), '/'))
1071 105
                ->setSchemaPath($schemaPath)
1072
            ;
1073
1074 105
            $lName = strtolower($propertyName);
1075 105
            $isRequired = isset($required[$propertyName]);
1076
1077
            // Check to strip this field if it is readOnly or writeOnly.
1078 105
            if (($isRequest && $propertyField->val('readOnly')) || ($isResponse && $propertyField->val('writeOnly'))) {
1079 6
                unset($keys[$lName]);
1080 6
                continue;
1081
            }
1082
1083
            // Check for required fields.
1084 105
            if (!array_key_exists($lName, $keys)) {
1085 30
                if ($field->isSparse()) {
1086
                    // Sparse validation can leave required fields out.
1087 29
                } elseif ($propertyField->hasVal('default')) {
1088 3
                    $clean[$propertyName] = $propertyField->val('default');
1089 26
                } elseif ($isRequired) {
1090 30
                    $propertyField->addError('missingField', ['messageCode' => '{field} is required.']);
1091
                }
1092
            } else {
1093 93
                $value = $data[$keys[$lName]];
1094
1095 93
                if (in_array($value, [null, ''], true) && !$isRequired && !($propertyField->val('nullable') || $propertyField->hasType('null'))) {
1096 5
                    if ($propertyField->getType() !== 'string' || $value === null) {
1097 2
                        continue;
1098
                    }
1099
                }
1100
1101 91
                $clean[$propertyName] = $this->validateField($value, $propertyField);
1102
            }
1103
1104 103
            unset($keys[$lName]);
1105
        }
1106
1107
        // Look for extraneous properties.
1108 107
        if (!empty($keys)) {
1109 17
            if ($additionalProperties) {
1110 6
                list($additionalProperties, $schemaPath) = $this->lookupSchema(
1111 6
                    $additionalProperties,
1112 6
                    $field->getSchemaPath().'/additionalProperties'
1113
                );
1114
1115 6
                $propertyField = new ValidationField(
1116 6
                    $field->getValidation(),
1117 6
                    $additionalProperties,
1118 6
                    '',
1119 6
                    $schemaPath,
1120 6
                    $field->getOptions()
1121
                );
1122
1123 6
                foreach ($keys as $key) {
1124
                    $propertyField
1125 6
                        ->setName(ltrim($field->getName()."/$key", '/'));
1126
1127 6
                    $valid = $this->validateField($data[$key], $propertyField);
1128 6
                    if (Invalid::isValid($valid)) {
1129 6
                        $clean[$key] = $valid;
1130
                    }
1131
                }
1132 11
            } elseif ($this->hasFlag(Schema::VALIDATE_EXTRA_PROPERTY_NOTICE)) {
1133 2
                $msg = sprintf("%s has unexpected field(s): %s.", $field->getName() ?: 'value', implode(', ', $keys));
1134 2
                trigger_error($msg, E_USER_NOTICE);
1135 9
            } elseif ($this->hasFlag(Schema::VALIDATE_EXTRA_PROPERTY_EXCEPTION)) {
1136 2
                $field->addError('invalid', [
1137 2
                    'messageCode' => '{field} has {extra,plural,an unexpected field,unexpected fields}: {extra}.',
1138 2
                    'extra' => array_values($keys),
1139
                ]);
1140
            }
1141
        }
1142
1143 105
        return $clean;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $clean also could return the type ArrayObject which is incompatible with the documented return type Garden\Schema\Invalid|array.
Loading history...
1144
    }
1145
1146
    /**
1147
     * Validate a string.
1148
     *
1149
     * @param mixed $value The value to validate.
1150
     * @param ValidationField $field The validation results to add.
1151
     * @return string|Invalid Returns the valid string or **null** if validation fails.
1152
     */
1153 83
    protected function validateString($value, ValidationField $field) {
1154 83
        if ($field->val('format') === 'date-time') {
1155 12
            $result = $this->validateDatetime($value, $field);
1156 12
            return $result;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $result also could return the type DateTimeInterface which is incompatible with the documented return type Garden\Schema\Invalid|string.
Loading history...
1157
        }
1158
1159 72
        if (is_string($value) || is_numeric($value)) {
1160 70
            $value = $result = (string)$value;
1161
        } else {
1162 5
            $field->addTypeError($value, 'string');
1163 5
            return Invalid::value();
1164
        }
1165
1166 70
        if (($minLength = $field->val('minLength', 0)) > 0 && mb_strlen($value) < $minLength) {
1167 4
            if (!empty($field->getName()) && $minLength === 1) {
1168 2
                $field->addError('missingField', ['messageCode' => '{field} is required.']);
1169
            } else {
1170 2
                $field->addError(
1171 2
                    'minLength',
1172
                    [
1173 2
                        'messageCode' => '{field} should be at least {minLength} {minLength,plural,character} long.',
1174 2
                        'minLength' => $minLength,
1175
                    ]
1176
                );
1177
            }
1178
        }
1179 70
        if (($maxLength = $field->val('maxLength', 0)) > 0 && mb_strlen($value) > $maxLength) {
1180 1
            $field->addError(
1181 1
                'maxLength',
1182
                [
1183 1
                    'messageCode' => '{field} is {overflow} {overflow,plural,characters} too long.',
1184 1
                    'maxLength' => $maxLength,
1185 1
                    'overflow' => mb_strlen($value) - $maxLength,
1186
                ]
1187
            );
1188
        }
1189 70
        if ($pattern = $field->val('pattern')) {
1190 4
            $regex = '`'.str_replace('`', preg_quote('`', '`'), $pattern).'`';
1191
1192 4
            if (!preg_match($regex, $value)) {
1193 2
                $field->addError(
1194 2
                    'invalid',
1195
                    [
1196 2
                        'messageCode' => '{field} is in the incorrect format.',
1197
                    ]
1198
                );
1199
            }
1200
        }
1201 70
        if ($format = $field->val('format')) {
1202 11
            $type = $format;
1203
            switch ($format) {
1204 11
                case 'date':
1205
                    $result = $this->validateDatetime($result, $field);
1206
                    if ($result instanceof \DateTimeInterface) {
1207
                        $result = $result->format("Y-m-d\T00:00:00P");
1208
                    }
1209
                    break;
1210 11
                case 'email':
1211 1
                    $result = filter_var($result, FILTER_VALIDATE_EMAIL);
1212 1
                    break;
1213 10
                case 'ipv4':
1214 1
                    $type = 'IPv4 address';
1215 1
                    $result = filter_var($result, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
1216 1
                    break;
1217 9
                case 'ipv6':
1218 1
                    $type = 'IPv6 address';
1219 1
                    $result = filter_var($result, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
1220 1
                    break;
1221 8
                case 'ip':
1222 1
                    $type = 'IP address';
1223 1
                    $result = filter_var($result, FILTER_VALIDATE_IP);
1224 1
                    break;
1225 7
                case 'uri':
1226 7
                    $type = 'URI';
1227 7
                    $result = filter_var($result, FILTER_VALIDATE_URL);
1228 7
                    break;
1229
                default:
1230
                    trigger_error("Unrecognized format '$format'.", E_USER_NOTICE);
1231
            }
1232 11
            if ($result === false) {
1233 5
                $field->addTypeError($value, $type);
1234
            }
1235
        }
1236
1237 70
        if ($field->isValid()) {
1238 62
            return $result;
1239
        } else {
1240 12
            return Invalid::value();
1241
        }
1242
    }
1243
1244
    /**
1245
     * Validate a unix timestamp.
1246
     *
1247
     * @param mixed $value The value to validate.
1248
     * @param ValidationField $field The field being validated.
1249
     * @return int|Invalid Returns a valid timestamp or invalid if the value doesn't validate.
1250
     */
1251 8
    protected function validateTimestamp($value, ValidationField $field) {
1252 8
        if (is_numeric($value) && $value > 0) {
1253 3
            $result = (int)$value;
1254 5
        } elseif (is_string($value) && $ts = strtotime($value)) {
1255 1
            $result = $ts;
1256
        } else {
1257 4
            $field->addTypeError($value, 'timestamp');
1258 4
            $result = Invalid::value();
1259
        }
1260 8
        return $result;
1261
    }
1262
1263
    /**
1264
     * Validate a null value.
1265
     *
1266
     * @param mixed $value The value to validate.
1267
     * @param ValidationField $field The error collector for the field.
1268
     * @return null|Invalid Returns **null** or invalid.
1269
     */
1270
    protected function validateNull($value, ValidationField $field) {
1271
        if ($value === null) {
1272
            return null;
1273
        }
1274
        $field->addError('invalidType', ['messageCode' => 'The value should be null.']);
1275
        return Invalid::value();
1276
    }
1277
1278
    /**
1279
     * Validate a value against an enum.
1280
     *
1281
     * @param mixed $value The value to test.
1282
     * @param ValidationField $field The validation object for adding errors.
1283
     * @return mixed|Invalid Returns the value if it is one of the enumerated values or invalid otherwise.
1284
     */
1285 199
    protected function validateEnum($value, ValidationField $field) {
1286 199
        $enum = $field->val('enum');
1287 199
        if (empty($enum)) {
1288 198
            return $value;
1289
        }
1290
1291 1
        if (!in_array($value, $enum, true)) {
1292 1
            $field->addError(
1293 1
                'invalid',
1294
                [
1295 1
                    'messageCode' => 'The value must be one of: {enum}.',
1296 1
                    'enum' => $enum,
1297
                ]
1298
            );
1299 1
            return Invalid::value();
1300
        }
1301 1
        return $value;
1302
    }
1303
1304
    /**
1305
     * Call all of the filters attached to a field.
1306
     *
1307
     * @param mixed $value The field value being filtered.
1308
     * @param ValidationField $field The validation object.
1309
     * @return mixed Returns the filtered value. If there are no filters for the field then the original value is returned.
1310
     */
1311 208
    protected function callFilters($value, ValidationField $field) {
1312
        // Strip array references in the name except for the last one.
1313 208
        $key = $field->getSchemaPath();
1314 208
        if (!empty($this->filters[$key])) {
1315 2
            foreach ($this->filters[$key] as $filter) {
1316 2
                $value = call_user_func($filter, $value, $field);
1317
            }
1318
        }
1319 208
        return $value;
1320
    }
1321
1322
    /**
1323
     * Call all of the validators attached to a field.
1324
     *
1325
     * @param mixed $value The field value being validated.
1326
     * @param ValidationField $field The validation object to add errors.
1327
     */
1328 199
    protected function callValidators($value, ValidationField $field) {
1329 199
        $valid = true;
1330
1331
        // Strip array references in the name except for the last one.
1332 199
        $key = $field->getSchemaPath();
1333 199
        if (!empty($this->validators[$key])) {
1334 5
            foreach ($this->validators[$key] as $validator) {
1335 5
                $r = call_user_func($validator, $value, $field);
1336
1337 5
                if ($r === false || Invalid::isInvalid($r)) {
1338 5
                    $valid = false;
1339
                }
1340
            }
1341
        }
1342
1343
        // Add an error on the field if the validator hasn't done so.
1344 199
        if (!$valid && $field->isValid()) {
1345 1
            $field->addError('invalid', ['messageCode' => '{field} is invalid.']);
1346
        }
1347 199
    }
1348
1349
    /**
1350
     * Specify data which should be serialized to JSON.
1351
     *
1352
     * This method specifically returns data compatible with the JSON schema format.
1353
     *
1354
     * @return mixed Returns data which can be serialized by **json_encode()**, which is a value of any type other than a resource.
1355
     * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
1356
     * @link http://json-schema.org/
1357
     */
1358 16
    public function jsonSerialize() {
1359
        $fix = function ($schema) use (&$fix) {
1360 16
            if ($schema instanceof Schema) {
1361 1
                return $schema->jsonSerialize();
1362
            }
1363
1364 16
            if (!empty($schema['type'])) {
1365 15
                $types = (array)$schema['type'];
1366
1367 15
                foreach ($types as $i => &$type) {
1368
                    // Swap datetime and timestamp to other types with formats.
1369 15
                    if ($type === 'datetime') {
1370 4
                        $type = 'string';
1371 4
                        $schema['format'] = 'date-time';
1372 14
                    } elseif ($schema['type'] === 'timestamp') {
1373 2
                        $type = 'integer';
1374 15
                        $schema['format'] = 'timestamp';
1375
                    }
1376
                }
1377 15
                $types = array_unique($types);
1378 15
                $schema['type'] = count($types) === 1 ? reset($types) : $types;
1379
            }
1380
1381 16
            if (!empty($schema['items'])) {
1382 4
                $schema['items'] = $fix($schema['items']);
1383
            }
1384 16
            if (!empty($schema['properties'])) {
1385 11
                $properties = [];
1386 11
                foreach ($schema['properties'] as $key => $property) {
1387 11
                    $properties[$key] = $fix($property);
1388
                }
1389 11
                $schema['properties'] = $properties;
1390
            }
1391
1392 16
            return $schema;
1393 16
        };
1394
1395 16
        $result = $fix($this->schema);
1396
1397 16
        return $result;
1398
    }
1399
1400
    /**
1401
     * Look up a type based on its alias.
1402
     *
1403
     * @param string $alias The type alias or type name to lookup.
1404
     * @return mixed
1405
     */
1406 167
    protected function getType($alias) {
1407 167
        if (isset(self::$types[$alias])) {
1408
            return $alias;
1409
        }
1410 167
        foreach (self::$types as $type => $aliases) {
1411 167
            if (in_array($alias, $aliases, true)) {
1412 167
                return $type;
1413
            }
1414
        }
1415 11
        return null;
1416
    }
1417
1418
    /**
1419
     * Get the class that's used to contain validation information.
1420
     *
1421
     * @return Validation|string Returns the validation class.
1422
     * @deprecated
1423
     */
1424 1
    public function getValidationClass() {
1425 1
        trigger_error('Schema::getValidationClass() is deprecated. Use Schema::getValidationFactory() instead.', E_USER_DEPRECATED);
1426 1
        return $this->validationClass;
0 ignored issues
show
Deprecated Code introduced by
The property Garden\Schema\Schema::$validationClass has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1426
        return /** @scrutinizer ignore-deprecated */ $this->validationClass;
Loading history...
1427
    }
1428
1429
    /**
1430
     * Set the class that's used to contain validation information.
1431
     *
1432
     * @param Validation|string $class Either the name of a class or a class that will be cloned.
1433
     * @return $this
1434
     * @deprecated
1435
     */
1436 1
    public function setValidationClass($class) {
1437 1
        trigger_error('Schema::setValidationClass() is deprecated. Use Schema::setValidationFactory() instead.', E_USER_DEPRECATED);
1438
1439 1
        if (!is_a($class, Validation::class, true)) {
1440
            throw new \InvalidArgumentException("$class must be a subclass of ".Validation::class, 500);
1441
        }
1442
1443
        $this->setValidationFactory(function () use ($class) {
1444 1
            if ($class instanceof Validation) {
1445 1
                $result = clone $class;
1446
            } else {
1447 1
                $result = new $class;
1448
            }
1449 1
            return $result;
1450 1
        });
1451 1
        $this->validationClass = $class;
0 ignored issues
show
Deprecated Code introduced by
The property Garden\Schema\Schema::$validationClass has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1451
        /** @scrutinizer ignore-deprecated */ $this->validationClass = $class;
Loading history...
1452 1
        return $this;
1453
    }
1454
1455
    /**
1456
     * Create a new validation instance.
1457
     *
1458
     * @return Validation Returns a validation object.
1459
     */
1460 208
    protected function createValidation(): Validation {
1461 208
        return call_user_func($this->getValidationFactory());
1462
    }
1463
1464
    /**
1465
     * Check whether or not a value is an array or accessible like an array.
1466
     *
1467
     * @param mixed $value The value to check.
1468
     * @return bool Returns **true** if the value can be used like an array or **false** otherwise.
1469
     */
1470 114
    private function isArray($value) {
1471 114
        return is_array($value) || ($value instanceof \ArrayAccess && $value instanceof \Traversable);
1472
    }
1473
1474
    /**
1475
     * Cast a value to an array.
1476
     *
1477
     * @param \Traversable $value The value to convert.
1478
     * @return array Returns an array.
1479
     */
1480 3
    private function toObjectArray(\Traversable $value) {
1481 3
        $class = get_class($value);
1482 3
        if ($value instanceof \ArrayObject) {
1483 2
            return new $class($value->getArrayCopy(), $value->getFlags(), $value->getIteratorClass());
0 ignored issues
show
Bug Best Practice introduced by
The expression return new $class($value...ue->getIteratorClass()) returns the type object which is incompatible with the documented return type array.
Loading history...
1484 1
        } elseif ($value instanceof \ArrayAccess) {
1485 1
            $r = new $class;
1486 1
            foreach ($value as $k => $v) {
1487 1
                $r[$k] = $v;
1488
            }
1489 1
            return $r;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $r returns the type object which is incompatible with the documented return type array.
Loading history...
1490
        }
1491
        return iterator_to_array($value);
1492
    }
1493
1494
    /**
1495
     * Return a sparse version of this schema.
1496
     *
1497
     * A sparse schema has no required properties.
1498
     *
1499
     * @return Schema Returns a new sparse schema.
1500
     */
1501 2
    public function withSparse() {
1502 2
        $sparseSchema = $this->withSparseInternal($this, new \SplObjectStorage());
1503 2
        return $sparseSchema;
1504
    }
1505
1506
    /**
1507
     * The internal implementation of `Schema::withSparse()`.
1508
     *
1509
     * @param array|Schema $schema The schema to make sparse.
1510
     * @param \SplObjectStorage $schemas Collected sparse schemas that have already been made.
1511
     * @return mixed
1512
     */
1513 2
    private function withSparseInternal($schema, \SplObjectStorage $schemas) {
1514 2
        if ($schema instanceof Schema) {
1515 2
            if ($schemas->contains($schema)) {
1516 1
                return $schemas[$schema];
1517
            } else {
1518 2
                $schemas[$schema] = $sparseSchema = new Schema();
1519 2
                $sparseSchema->schema = $schema->withSparseInternal($schema->schema, $schemas);
1520 2
                if ($id = $sparseSchema->getID()) {
1521
                    $sparseSchema->setID($id.'Sparse');
1522
                }
1523
1524 2
                return $sparseSchema;
1525
            }
1526
        }
1527
1528 2
        unset($schema['required']);
1529
1530 2
        if (isset($schema['items'])) {
1531 1
            $schema['items'] = $this->withSparseInternal($schema['items'], $schemas);
1532
        }
1533 2
        if (isset($schema['properties'])) {
1534 2
            foreach ($schema['properties'] as $name => &$property) {
1535 2
                $property = $this->withSparseInternal($property, $schemas);
1536
            }
1537
        }
1538
1539 2
        return $schema;
1540
    }
1541
1542
    /**
1543
     * Filter a field's value using built in and custom filters.
1544
     *
1545
     * @param mixed $value The original value of the field.
1546
     * @param ValidationField $field The field information for the field.
1547
     * @return mixed Returns the filtered field or the original field value if there are no filters.
1548
     */
1549 208
    private function filterField($value, ValidationField $field) {
1550
        // Check for limited support for Open API style.
1551 208
        if (!empty($field->val('style')) && is_string($value)) {
1552 8
            $doFilter = true;
1553 8
            if ($field->hasType('boolean') && in_array($value, ['true', 'false', '0', '1'], true)) {
1554 4
                $doFilter = false;
1555 4
            } elseif ($field->hasType('integer') || $field->hasType('number') && is_numeric($value)) {
1556
                $doFilter = false;
1557
            }
1558
1559 8
            if ($doFilter) {
1560 4
                switch ($field->val('style')) {
1561 4
                    case 'form':
1562 2
                        $value = explode(',', $value);
1563 2
                        break;
1564 2
                    case 'spaceDelimited':
1565 1
                        $value = explode(' ', $value);
1566 1
                        break;
1567 1
                    case 'pipeDelimited':
1568 1
                        $value = explode('|', $value);
1569 1
                        break;
1570
                }
1571
            }
1572
        }
1573
1574 208
        $value = $this->callFilters($value, $field);
1575
1576 208
        return $value;
1577
    }
1578
1579
    /**
1580
     * Whether a offset exists.
1581
     *
1582
     * @param mixed $offset An offset to check for.
1583
     * @return boolean true on success or false on failure.
1584
     * @link http://php.net/manual/en/arrayaccess.offsetexists.php
1585
     */
1586 7
    public function offsetExists($offset) {
1587 7
        return isset($this->schema[$offset]);
1588
    }
1589
1590
    /**
1591
     * Offset to retrieve.
1592
     *
1593
     * @param mixed $offset The offset to retrieve.
1594
     * @return mixed Can return all value types.
1595
     * @link http://php.net/manual/en/arrayaccess.offsetget.php
1596
     */
1597 7
    public function offsetGet($offset) {
1598 7
        return isset($this->schema[$offset]) ? $this->schema[$offset] : null;
1599
    }
1600
1601
    /**
1602
     * Offset to set.
1603
     *
1604
     * @param mixed $offset The offset to assign the value to.
1605
     * @param mixed $value The value to set.
1606
     * @link http://php.net/manual/en/arrayaccess.offsetset.php
1607
     */
1608 1
    public function offsetSet($offset, $value) {
1609 1
        $this->schema[$offset] = $value;
1610 1
    }
1611
1612
    /**
1613
     * Offset to unset.
1614
     *
1615
     * @param mixed $offset The offset to unset.
1616
     * @link http://php.net/manual/en/arrayaccess.offsetunset.php
1617
     */
1618 1
    public function offsetUnset($offset) {
1619 1
        unset($this->schema[$offset]);
1620 1
    }
1621
1622
    /**
1623
     * Validate a field against a single type.
1624
     *
1625
     * @param mixed $value The value to validate.
1626
     * @param string $type The type to validate against.
1627
     * @param ValidationField $field Contains field and validation information.
1628
     * @return mixed Returns the valid value or `Invalid`.
1629
     */
1630 208
    protected function validateSingleType($value, $type, ValidationField $field) {
1631
        switch ($type) {
1632 208
            case 'boolean':
1633 32
                $result = $this->validateBoolean($value, $field);
1634 32
                break;
1635 188
            case 'integer':
1636 58
                $result = $this->validateInteger($value, $field);
1637 58
                break;
1638 169
            case 'number':
1639 17
                $result = $this->validateNumber($value, $field);
1640 17
                break;
1641 160
            case 'string':
1642 83
                $result = $this->validateString($value, $field);
1643 83
                break;
1644 136
            case 'timestamp':
1645 1
                trigger_error('The timestamp type is deprecated. Use an integer with a format of timestamp instead.', E_USER_DEPRECATED);
1646 1
                $result = $this->validateTimestamp($value, $field);
1647 1
                break;
1648 136
            case 'datetime':
1649 2
                trigger_error('The datetime type is deprecated. Use a string with a format of date-time instead.', E_USER_DEPRECATED);
1650 2
                $result = $this->validateDatetime($value, $field);
1651 2
                break;
1652 135
            case 'array':
1653 34
                $result = $this->validateArray($value, $field);
1654 34
                break;
1655 115
            case 'object':
1656 114
                $result = $this->validateObject($value, $field);
1657 112
                break;
1658 5
            case 'null':
1659
                $result = $this->validateNull($value, $field);
1660
                break;
1661 5
            case null:
1662
                // No type was specified so we are valid.
1663 5
                $result = $value;
1664 5
                break;
1665
            default:
1666
                throw new \InvalidArgumentException("Unrecognized type $type.", 500);
1667
        }
1668 208
        return $result;
1669
    }
1670
1671
    /**
1672
     * Validate a field against multiple basic types.
1673
     *
1674
     * The first validation that passes will be returned. If no type can be validated against then validation will fail.
1675
     *
1676
     * @param mixed $value The value to validate.
1677
     * @param string[] $types The types to validate against.
1678
     * @param ValidationField $field Contains field and validation information.
1679
     * @return mixed Returns the valid value or `Invalid`.
1680
     */
1681 29
    private function validateMultipleTypes($value, array $types, ValidationField $field) {
1682 29
        trigger_error('Multiple schema types are deprecated.', E_USER_DEPRECATED);
1683
1684
        // First check for an exact type match.
1685 29
        switch (gettype($value)) {
1686 29
            case 'boolean':
1687 4
                if (in_array('boolean', $types)) {
1688 4
                    $singleType = 'boolean';
1689
                }
1690 4
                break;
1691 26
            case 'integer':
1692 7
                if (in_array('integer', $types)) {
1693 5
                    $singleType = 'integer';
1694 2
                } elseif (in_array('number', $types)) {
1695 1
                    $singleType = 'number';
1696
                }
1697 7
                break;
1698 21
            case 'double':
1699 4
                if (in_array('number', $types)) {
1700 4
                    $singleType = 'number';
1701
                } elseif (in_array('integer', $types)) {
1702
                    $singleType = 'integer';
1703
                }
1704 4
                break;
1705 18
            case 'string':
1706 9
                if (in_array('datetime', $types) && preg_match(self::$DATE_REGEX, $value)) {
1707 1
                    $singleType = 'datetime';
1708 8
                } elseif (in_array('string', $types)) {
1709 4
                    $singleType = 'string';
1710
                }
1711 9
                break;
1712 10
            case 'array':
1713 10
                if (in_array('array', $types) && in_array('object', $types)) {
1714 1
                    $singleType = isset($value[0]) || empty($value) ? 'array' : 'object';
1715 9
                } elseif (in_array('object', $types)) {
1716
                    $singleType = 'object';
1717 9
                } elseif (in_array('array', $types)) {
1718 9
                    $singleType = 'array';
1719
                }
1720 10
                break;
1721 1
            case 'NULL':
1722
                if (in_array('null', $types)) {
1723
                    $singleType = $this->validateSingleType($value, 'null', $field);
1724
                }
1725
                break;
1726
        }
1727 29
        if (!empty($singleType)) {
1728 25
            return $this->validateSingleType($value, $singleType, $field);
1729
        }
1730
1731
        // Clone the validation field to collect errors.
1732 6
        $typeValidation = new ValidationField(new Validation(), $field->getField(), '', '', $field->getOptions());
1733
1734
        // Try and validate against each type.
1735 6
        foreach ($types as $type) {
1736 6
            $result = $this->validateSingleType($value, $type, $typeValidation);
1737 6
            if (Invalid::isValid($result)) {
1738 6
                return $result;
1739
            }
1740
        }
1741
1742
        // Since we got here the value is invalid.
1743
        $field->merge($typeValidation->getValidation());
1744
        return Invalid::value();
1745
    }
1746
1747
    /**
1748
     * Validate specific numeric validation properties.
1749
     *
1750
     * @param int|float $value The value to test.
1751
     * @param ValidationField $field Field information.
1752
     * @return int|float|Invalid Returns the number of invalid.
1753
     */
1754 57
    private function validateNumberProperties($value, ValidationField $field) {
1755 57
        $count = $field->getErrorCount();
1756
1757 57
        if ($multipleOf = $field->val('multipleOf')) {
1758 4
            $divided = $value / $multipleOf;
1759
1760 4
            if ($divided != round($divided)) {
1761 2
                $field->addError('multipleOf', ['messageCode' => '{field} is not a multiple of {multipleOf}.', 'multipleOf' => $multipleOf]);
1762
            }
1763
        }
1764
1765 57
        if ($maximum = $field->val('maximum')) {
1766 4
            $exclusive = $field->val('exclusiveMaximum');
1767
1768 4
            if ($value > $maximum || ($exclusive && $value == $maximum)) {
1769 2
                if ($exclusive) {
1770 1
                    $field->addError('maximum', ['messageCode' => '{field} must be less than {maximum}.', 'maximum' => $maximum]);
1771
                } else {
1772 1
                    $field->addError('maximum', ['messageCode' => '{field} must be less than or equal to {maximum}.', 'maximum' => $maximum]);
1773
                }
1774
1775
            }
1776
        }
1777
1778 57
        if ($minimum = $field->val('minimum')) {
1779 4
            $exclusive = $field->val('exclusiveMinimum');
1780
1781 4
            if ($value < $minimum || ($exclusive && $value == $minimum)) {
1782 2
                if ($exclusive) {
1783 1
                    $field->addError('minimum', ['messageCode' => '{field} must be greater than {minimum}.', 'minimum' => $minimum]);
1784
                } else {
1785 1
                    $field->addError('minimum', ['messageCode' => '{field} must be greater than or equal to {minimum}.', 'minimum' => $minimum]);
1786
                }
1787
1788
            }
1789
        }
1790
1791 57
        return $field->getErrorCount() === $count ? $value : Invalid::value();
1792
    }
1793
1794
    /**
1795
     * Parse a nested field name selector.
1796
     *
1797
     * Field selectors should be separated by "/" characters, but may currently be separated by "." characters which
1798
     * triggers a deprecated error.
1799
     *
1800
     * @param string $field The field selector.
1801
     * @return string Returns the field selector in the correct format.
1802
     */
1803 15
    private function parseFieldSelector(string $field): string {
1804 15
        if (strlen($field) === 0) {
1805 4
            return $field;
1806
        }
1807
1808 11
        if (strpos($field, '.') !== false) {
1809 1
            if (strpos($field, '/') === false) {
1810 1
                trigger_error('Field selectors must be separated by "/" instead of "."', E_USER_DEPRECATED);
1811
1812 1
                $parts = explode('.', $field);
1813 1
                $parts = @array_map([$this, 'parseFieldSelector'], $parts); // silence because error triggered already.
1814
1815 1
                $field = implode('/', $parts);
1816
            }
1817 11
        } elseif ($field === '[]') {
1818 1
            trigger_error('Field selectors with item selector "[]" must be converted to "items".', E_USER_DEPRECATED);
1819 1
            $field = 'items';
1820 10
        } elseif (strpos($field, '/') === false && !in_array($field, ['items', 'additionalProperties'], true)) {
1821 3
            trigger_error("Field selectors must specify full schema paths. ($field)", E_USER_DEPRECATED);
1822 3
            $field = "/properties/$field";
1823
        }
1824
1825 11
        if (strpos($field, '[]') !== false) {
1826 1
            trigger_error('Field selectors with item selector "[]" must be converted to "/items".', E_USER_DEPRECATED);
1827 1
            $field = str_replace('[]', '/items', $field);
1828
        }
1829
1830 11
        return ltrim($field, '/');
1831
    }
1832
1833
    /**
1834
     * Lookup a schema based on a schema node.
1835
     *
1836
     * The node could be a schema array, `Schema` object, or a schema reference.
1837
     *
1838
     * @param mixed $schema The schema node to lookup with.
1839
     * @param string $schemaPath The current path of the schema.
1840
     * @return array Returns an array with two elements:
1841
     * - Schema|array|\ArrayAccess The schema that was found.
1842
     * - string The path of the schema. This is either the reference or the `$path` parameter for inline schemas.
1843
     * @throws RefNotFoundException Throws an exception when a reference could not be found.
1844
     */
1845 211
    private function lookupSchema($schema, string $schemaPath) {
1846 211
        if ($schema instanceof Schema) {
1847 6
            return [$schema, $schemaPath];
1848
        } else {
1849 211
            $lookup = $this->getRefLookup();
1850 211
            $visited = [];
1851
1852 211
            while (!empty($schema['$ref'])) {
1853 10
                $schemaPath = $schema['$ref'];
1854
1855 10
                if (isset($visited[$schemaPath])) {
1856 1
                    throw new RefNotFoundException("Cyclical reference cannot be resolved. ($schemaPath)", 508);
1857
                }
1858 10
                $visited[$schemaPath] = true;
1859
1860
                try {
1861 10
                    $schema = call_user_func($lookup, $schemaPath);
1862 1
                } catch (\Exception $ex) {
1863 1
                    throw new RefNotFoundException($ex->getMessage(), $ex->getCode(), $ex);
1864
                }
1865 9
                if ($schema === null) {
1866 1
                    throw new RefNotFoundException("Schema reference could not be found. ($schemaPath)");
1867
                }
1868
            }
1869 208
            return [$schema, $schemaPath];
1870
        }
1871
    }
1872
1873
    /**
1874
     * Get the function used to resolve `$ref` lookups.
1875
     *
1876
     * @return callable Returns the current `$ref` lookup.
1877
     */
1878 211
    public function getRefLookup(): callable {
1879 211
        return $this->refLookup;
1880
    }
1881
1882
    /**
1883
     * Set the function used to resolve `$ref` lookups.
1884
     *
1885
     * @param callable $refLookup The new lookup function.
1886
     * @return $this
1887
     */
1888 10
    public function setRefLookup(callable $refLookup) {
1889 10
        $this->refLookup = $refLookup;
1890 10
        return $this;
1891
    }
1892
1893
    /**
1894
     * Get factory used to create validation objects.
1895
     *
1896
     * @return callable Returns the current factory.
1897
     */
1898 208
    public function getValidationFactory(): callable {
1899 208
        return $this->validationFactory;
1900
    }
1901
1902
    /**
1903
     * Set the factory used to create validation objects.
1904
     *
1905
     * @param callable $validationFactory The new factory.
1906
     * @return $this
1907
     */
1908 2
    public function setValidationFactory(callable $validationFactory) {
1909 2
        $this->validationFactory = $validationFactory;
1910 2
        $this->validationClass = null;
0 ignored issues
show
Deprecated Code introduced by
The property Garden\Schema\Schema::$validationClass has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1910
        /** @scrutinizer ignore-deprecated */ $this->validationClass = null;
Loading history...
1911 2
        return $this;
1912
    }
1913
}
1914