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

Schema::setID()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
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 269
    public function __construct(array $schema = []) {
89 269
        $this->schema = $schema;
90
        $this->refLookup = function (/** @scrutinizer ignore-unused */ string $_) {
91 1
            return null;
92
        };
93
        $this->validationFactory = function () {
94 208
            return new Validation();
95
        };
96 269
    }
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 1
    public function getTitle(): string {
124 1
        return $this->schema['title'] ?? '';
125
    }
126
127
    /**
128
     * Set the schema's title.
129
     *
130
     * @param string $title The new title.
131
     */
132 1
    public function setTitle(string $title) {
133 1
        $this->schema['title'] = $title;
134 1
    }
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 $this->schema['id'] ?? '';
209
    }
210
211
    /**
212
     * Set the ID for the schema.
213
     *
214
     * @param string $id The new ID.
215
     * @return $this
216
     */
217 1
    public function setID(string $id) {
218 1
        $this->schema['id'] = $id;
219
220 1
        return $this;
221
    }
222
223
    /**
224
     * Return the validation flags.
225
     *
226
     * @return int Returns a bitwise combination of flags.
227
     */
228 1
    public function getFlags(): int {
229 1
        return $this->flags;
230
    }
231
232
    /**
233
     * Set the validation flags.
234
     *
235
     * @param int $flags One or more of the **Schema::FLAG_*** constants.
236
     * @return Schema Returns the current instance for fluent calls.
237
     */
238 7
    public function setFlags(int $flags) {
239 7
        $this->flags = $flags;
240
241 7
        return $this;
242
    }
243
244
    /**
245
     * Whether or not the schema has a flag (or combination of flags).
246
     *
247
     * @param int $flag One or more of the **Schema::VALIDATE_*** constants.
248
     * @return bool Returns **true** if all of the flags are set or **false** otherwise.
249
     */
250 12
    public function hasFlag(int $flag): bool {
251 12
        return ($this->flags & $flag) === $flag;
252
    }
253
254
    /**
255
     * Set a flag.
256
     *
257
     * @param int $flag One or more of the **Schema::VALIDATE_*** constants.
258
     * @param bool $value Either true or false.
259
     * @return $this
260
     */
261 1
    public function setFlag(int $flag, bool $value) {
262 1
        if ($value) {
263 1
            $this->flags = $this->flags | $flag;
264
        } else {
265 1
            $this->flags = $this->flags & ~$flag;
266
        }
267 1
        return $this;
268
    }
269
270
    /**
271
     * Merge a schema with this one.
272
     *
273
     * @param Schema $schema A scheme instance. Its parameters will be merged into the current instance.
274
     * @return $this
275
     */
276 4
    public function merge(Schema $schema) {
277 4
        $this->mergeInternal($this->schema, $schema->getSchemaArray(), true, true);
278 4
        return $this;
279
    }
280
281
    /**
282
     * Add another schema to this one.
283
     *
284
     * Adding schemas together is analogous to array addition. When you add a schema it will only add missing information.
285
     *
286
     * @param Schema $schema The schema to add.
287
     * @param bool $addProperties Whether to add properties that don't exist in this schema.
288
     * @return $this
289
     */
290 4
    public function add(Schema $schema, $addProperties = false) {
291 4
        $this->mergeInternal($this->schema, $schema->getSchemaArray(), false, $addProperties);
292 4
        return $this;
293
    }
294
295
    /**
296
     * The internal implementation of schema merging.
297
     *
298
     * @param array &$target The target of the merge.
299
     * @param array $source The source of the merge.
300
     * @param bool $overwrite Whether or not to replace values.
301
     * @param bool $addProperties Whether or not to add object properties to the target.
302
     * @return array
303
     */
304 7
    private function mergeInternal(array &$target, array $source, $overwrite = true, $addProperties = true) {
305
        // We need to do a fix for required properties here.
306 7
        if (isset($target['properties']) && !empty($source['required'])) {
307 5
            $required = isset($target['required']) ? $target['required'] : [];
308
309 5
            if (isset($source['required']) && $addProperties) {
310 4
                $newProperties = array_diff(array_keys($source['properties']), array_keys($target['properties']));
311 4
                $newRequired = array_intersect($source['required'], $newProperties);
312
313 4
                $required = array_merge($required, $newRequired);
314
            }
315
        }
316
317
318 7
        foreach ($source as $key => $val) {
319 7
            if (is_array($val) && array_key_exists($key, $target) && is_array($target[$key])) {
320 7
                if ($key === 'properties' && !$addProperties) {
321
                    // We just want to merge the properties that exist in the destination.
322 2
                    foreach ($val as $name => $prop) {
323 2
                        if (isset($target[$key][$name])) {
324 2
                            $targetProp = &$target[$key][$name];
325
326 2
                            if (is_array($targetProp) && is_array($prop)) {
327 2
                                $this->mergeInternal($targetProp, $prop, $overwrite, $addProperties);
328 1
                            } elseif (is_array($targetProp) && $prop instanceof Schema) {
329
                                $this->mergeInternal($targetProp, $prop->getSchemaArray(), $overwrite, $addProperties);
330 1
                            } elseif ($overwrite) {
331 2
                                $targetProp = $prop;
332
                            }
333
                        }
334
                    }
335 7
                } elseif (isset($val[0]) || isset($target[$key][0])) {
336 5
                    if ($overwrite) {
337
                        // This is a numeric array, so just do a merge.
338 3
                        $merged = array_merge($target[$key], $val);
339 3
                        if (is_string($merged[0])) {
340 3
                            $merged = array_keys(array_flip($merged));
341
                        }
342 5
                        $target[$key] = $merged;
343
                    }
344
                } else {
345 7
                    $target[$key] = $this->mergeInternal($target[$key], $val, $overwrite, $addProperties);
346
                }
347 7
            } elseif (!$overwrite && array_key_exists($key, $target) && !is_array($val)) {
348
                // Do nothing, we aren't replacing.
349
            } else {
350 7
                $target[$key] = $val;
351
            }
352
        }
353
354 7
        if (isset($required)) {
355 5
            if (empty($required)) {
356 1
                unset($target['required']);
357
            } else {
358 5
                $target['required'] = $required;
359
            }
360
        }
361
362 7
        return $target;
363
    }
364
365
//    public function overlay(Schema $schema )
366
367
    /**
368
     * Returns the internal schema array.
369
     *
370
     * @return array
371
     * @see Schema::jsonSerialize()
372
     */
373 17
    public function getSchemaArray(): array {
374 17
        return $this->schema;
375
    }
376
377
    /**
378
     * Parse a short schema and return the associated schema.
379
     *
380
     * @param array $arr The schema array.
381
     * @param mixed[] $args Constructor arguments for the schema instance.
382
     * @return static Returns a new schema.
383
     */
384 179
    public static function parse(array $arr, ...$args) {
385 179
        $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

385
        $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...
386 179
        $schema->schema = $schema->parseInternal($arr);
387 177
        return $schema;
388
    }
389
390
    /**
391
     * Parse a schema in short form into a full schema array.
392
     *
393
     * @param array $arr The array to parse into a schema.
394
     * @return array The full schema array.
395
     * @throws ParseException Throws an exception when an item in the schema is invalid.
396
     */
397 179
    protected function parseInternal(array $arr): array {
398 179
        if (empty($arr)) {
399
            // An empty schema validates to anything.
400 6
            return [];
401 174
        } elseif (isset($arr['type'])) {
402
            // This is a long form schema and can be parsed as the root.
403 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...
404
        } else {
405
            // Check for a root schema.
406 173
            $value = reset($arr);
407 173
            $key = key($arr);
408 173
            if (is_int($key)) {
409 108
                $key = $value;
410 108
                $value = null;
411
            }
412 173
            list ($name, $param) = $this->parseShortParam($key, $value);
413 171
            if (empty($name)) {
414 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...
415
            }
416
        }
417
418
        // If we are here then this is n object schema.
419 111
        list($properties, $required) = $this->parseProperties($arr);
420
421
        $result = [
422 111
            'type' => 'object',
423 111
            'properties' => $properties,
424 111
            'required' => $required
425
        ];
426
427 111
        return array_filter($result);
428
    }
429
430
    /**
431
     * Parse a schema node.
432
     *
433
     * @param array|Schema $node The node to parse.
434
     * @param mixed $value Additional information from the node.
435
     * @return array|\ArrayAccess Returns a JSON schema compatible node.
436
     * @throws ParseException Throws an exception if there was a problem parsing the schema node.
437
     */
438 172
    private function parseNode($node, $value = null) {
439 172
        if (is_array($value)) {
440 66
            if (is_array($node['type'])) {
441
                trigger_error('Schemas with multiple types are deprecated.', E_USER_DEPRECATED);
442
            }
443
444
            // The value describes a bit more about the schema.
445 66
            switch ($node['type']) {
446 66
                case 'array':
447 11
                    if (isset($value['items'])) {
448
                        // The value includes array schema information.
449 4
                        $node = array_replace($node, $value);
0 ignored issues
show
Bug introduced by
It seems like $node can also be of type Garden\Schema\Schema; however, parameter $array of array_replace() 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

449
                        $node = array_replace(/** @scrutinizer ignore-type */ $node, $value);
Loading history...
450
                    } else {
451 7
                        $node['items'] = $this->parseInternal($value);
452
                    }
453 11
                    break;
454 56
                case 'object':
455
                    // The value is a schema of the object.
456 12
                    if (isset($value['properties'])) {
457
                        list($node['properties']) = $this->parseProperties($value['properties']);
458
                    } else {
459 12
                        list($node['properties'], $required) = $this->parseProperties($value);
460 12
                        if (!empty($required)) {
461 12
                            $node['required'] = $required;
462
                        }
463
                    }
464 12
                    break;
465
                default:
466 44
                    $node = array_replace($node, $value);
467 66
                    break;
468
            }
469 132
        } elseif (is_string($value)) {
470 102
            if ($node['type'] === 'array' && $arrType = $this->getType($value)) {
471 6
                $node['items'] = ['type' => $arrType];
472 98
            } elseif (!empty($value)) {
473 102
                $node['description'] = $value;
474
            }
475 35
        } elseif ($value === null) {
476
            // Parse child elements.
477 31
            if ($node['type'] === 'array' && isset($node['items'])) {
478
                // The value includes array schema information.
479
                $node['items'] = $this->parseInternal($node['items']);
0 ignored issues
show
Bug introduced by
It seems like $node['items'] can also be of type null; however, parameter $arr of Garden\Schema\Schema::parseInternal() 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

479
                $node['items'] = $this->parseInternal(/** @scrutinizer ignore-type */ $node['items']);
Loading history...
480 31
            } elseif ($node['type'] === 'object' && isset($node['properties'])) {
481 1
                list($node['properties']) = $this->parseProperties($node['properties']);
482
            }
483
        }
484
485 172
        if (is_array($node)) {
486 171
            if (!empty($node['allowNull'])) {
487 1
                $node['nullable'] = true;
488
            }
489 171
            unset($node['allowNull']);
490
491 171
            if ($node['type'] === null || $node['type'] === []) {
492 4
                unset($node['type']);
493
            }
494
        }
495
496 172
        return $node;
497
    }
498
499
    /**
500
     * Parse the schema for an object's properties.
501
     *
502
     * @param array $arr An object property schema.
503
     * @return array Returns a schema array suitable to be placed in the **properties** key of a schema.
504
     * @throws ParseException Throws an exception if a property name cannot be determined for an array item.
505
     */
506 112
    private function parseProperties(array $arr): array {
507 112
        $properties = [];
508 112
        $requiredProperties = [];
509 112
        foreach ($arr as $key => $value) {
510
            // Fix a schema specified as just a value.
511 112
            if (is_int($key)) {
512 82
                if (is_string($value)) {
513 82
                    $key = $value;
514 82
                    $value = '';
515
                } else {
516
                    throw new ParseException("Schema at position $key is not a valid parameter.", 500);
517
                }
518
            }
519
520
            // The parameter is defined in the key.
521 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

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

828
            if ((null !== $minItems = $field->val('minItems')) && count(/** @scrutinizer ignore-type */ $value) < $minItems) {
Loading history...
829 1
                $field->addError(
830 1
                    'minItems',
831
                    [
832 1
                        'messageCode' => 'Array must contain at least {minItems} {minItems,plural,item}.',
833 1
                        'minItems' => $minItems,
834
                    ]
835
                );
836
            }
837 29
            if ((null !== $maxItems = $field->val('maxItems')) && count($value) > $maxItems) {
838 1
                $field->addError(
839 1
                    'maxItems',
840
                    [
841 1
                        'messageCode' => 'Array must contain no more than {maxItems} {maxItems,plural,item}.',
842 1
                        'maxItems' => $maxItems,
843
                    ]
844
                );
845
            }
846
847 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

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

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

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

1449
        /** @scrutinizer ignore-deprecated */ $this->validationClass = $class;
Loading history...
1450 1
        return $this;
1451
    }
1452
1453
    /**
1454
     * Create a new validation instance.
1455
     *
1456
     * @return Validation Returns a validation object.
1457
     */
1458 210
    protected function createValidation(): Validation {
1459 210
        return call_user_func($this->getValidationFactory());
1460
    }
1461
1462
    /**
1463
     * Check whether or not a value is an array or accessible like an array.
1464
     *
1465
     * @param mixed $value The value to check.
1466
     * @return bool Returns **true** if the value can be used like an array or **false** otherwise.
1467
     */
1468 115
    private function isArray($value) {
1469 115
        return is_array($value) || ($value instanceof \ArrayAccess && $value instanceof \Traversable);
1470
    }
1471
1472
    /**
1473
     * Cast a value to an array.
1474
     *
1475
     * @param \Traversable $value The value to convert.
1476
     * @return array Returns an array.
1477
     */
1478 3
    private function toObjectArray(\Traversable $value) {
1479 3
        $class = get_class($value);
1480 3
        if ($value instanceof \ArrayObject) {
1481 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...
1482 1
        } elseif ($value instanceof \ArrayAccess) {
1483 1
            $r = new $class;
1484 1
            foreach ($value as $k => $v) {
1485 1
                $r[$k] = $v;
1486
            }
1487 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...
1488
        }
1489
        return iterator_to_array($value);
1490
    }
1491
1492
    /**
1493
     * Return a sparse version of this schema.
1494
     *
1495
     * A sparse schema has no required properties.
1496
     *
1497
     * @return Schema Returns a new sparse schema.
1498
     */
1499 2
    public function withSparse() {
1500 2
        $sparseSchema = $this->withSparseInternal($this, new \SplObjectStorage());
1501 2
        return $sparseSchema;
1502
    }
1503
1504
    /**
1505
     * The internal implementation of `Schema::withSparse()`.
1506
     *
1507
     * @param array|Schema $schema The schema to make sparse.
1508
     * @param \SplObjectStorage $schemas Collected sparse schemas that have already been made.
1509
     * @return mixed
1510
     */
1511 2
    private function withSparseInternal($schema, \SplObjectStorage $schemas) {
1512 2
        if ($schema instanceof Schema) {
1513 2
            if ($schemas->contains($schema)) {
1514 1
                return $schemas[$schema];
1515
            } else {
1516 2
                $schemas[$schema] = $sparseSchema = new Schema();
1517 2
                $sparseSchema->schema = $schema->withSparseInternal($schema->schema, $schemas);
1518 2
                if ($id = $sparseSchema->getID()) {
1519
                    $sparseSchema->setID($id.'Sparse');
1520
                }
1521
1522 2
                return $sparseSchema;
1523
            }
1524
        }
1525
1526 2
        unset($schema['required']);
1527
1528 2
        if (isset($schema['items'])) {
1529 1
            $schema['items'] = $this->withSparseInternal($schema['items'], $schemas);
1530
        }
1531 2
        if (isset($schema['properties'])) {
1532 2
            foreach ($schema['properties'] as $name => &$property) {
1533 2
                $property = $this->withSparseInternal($property, $schemas);
1534
            }
1535
        }
1536
1537 2
        return $schema;
1538
    }
1539
1540
    /**
1541
     * Filter a field's value using built in and custom filters.
1542
     *
1543
     * @param mixed $value The original value of the field.
1544
     * @param ValidationField $field The field information for the field.
1545
     * @return mixed Returns the filtered field or the original field value if there are no filters.
1546
     */
1547 210
    private function filterField($value, ValidationField $field) {
1548
        // Check for limited support for Open API style.
1549 210
        if (!empty($field->val('style')) && is_string($value)) {
1550 8
            $doFilter = true;
1551 8
            if ($field->hasType('boolean') && in_array($value, ['true', 'false', '0', '1'], true)) {
1552 4
                $doFilter = false;
1553 4
            } elseif ($field->hasType('integer') || $field->hasType('number') && is_numeric($value)) {
1554
                $doFilter = false;
1555
            }
1556
1557 8
            if ($doFilter) {
1558 4
                switch ($field->val('style')) {
1559 4
                    case 'form':
1560 2
                        $value = explode(',', $value);
1561 2
                        break;
1562 2
                    case 'spaceDelimited':
1563 1
                        $value = explode(' ', $value);
1564 1
                        break;
1565 1
                    case 'pipeDelimited':
1566 1
                        $value = explode('|', $value);
1567 1
                        break;
1568
                }
1569
            }
1570
        }
1571
1572 210
        $value = $this->callFilters($value, $field);
1573
1574 210
        return $value;
1575
    }
1576
1577
    /**
1578
     * Whether a offset exists.
1579
     *
1580
     * @param mixed $offset An offset to check for.
1581
     * @return boolean true on success or false on failure.
1582
     * @link http://php.net/manual/en/arrayaccess.offsetexists.php
1583
     */
1584 7
    public function offsetExists($offset) {
1585 7
        return isset($this->schema[$offset]);
1586
    }
1587
1588
    /**
1589
     * Offset to retrieve.
1590
     *
1591
     * @param mixed $offset The offset to retrieve.
1592
     * @return mixed Can return all value types.
1593
     * @link http://php.net/manual/en/arrayaccess.offsetget.php
1594
     */
1595 7
    public function offsetGet($offset) {
1596 7
        return isset($this->schema[$offset]) ? $this->schema[$offset] : null;
1597
    }
1598
1599
    /**
1600
     * Offset to set.
1601
     *
1602
     * @param mixed $offset The offset to assign the value to.
1603
     * @param mixed $value The value to set.
1604
     * @link http://php.net/manual/en/arrayaccess.offsetset.php
1605
     */
1606 1
    public function offsetSet($offset, $value) {
1607 1
        $this->schema[$offset] = $value;
1608 1
    }
1609
1610
    /**
1611
     * Offset to unset.
1612
     *
1613
     * @param mixed $offset The offset to unset.
1614
     * @link http://php.net/manual/en/arrayaccess.offsetunset.php
1615
     */
1616 1
    public function offsetUnset($offset) {
1617 1
        unset($this->schema[$offset]);
1618 1
    }
1619
1620
    /**
1621
     * Validate a field against a single type.
1622
     *
1623
     * @param mixed $value The value to validate.
1624
     * @param string $type The type to validate against.
1625
     * @param ValidationField $field Contains field and validation information.
1626
     * @return mixed Returns the valid value or `Invalid`.
1627
     * @throws \InvalidArgumentException Throws an exception when `$type` is not recognized.
1628
     * @throws RefNotFoundException Throws an exception when internal validation has a reference that isn't found.
1629
     */
1630 210
    protected function validateSingleType($value, string $type, ValidationField $field) {
1631
        switch ($type) {
1632 210
            case 'boolean':
1633 32
                $result = $this->validateBoolean($value, $field);
1634 32
                break;
1635 190
            case 'integer':
1636 59
                $result = $this->validateInteger($value, $field);
1637 59
                break;
1638 171
            case 'number':
1639 17
                $result = $this->validateNumber($value, $field);
1640 17
                break;
1641 162
            case 'string':
1642 83
                $result = $this->validateString($value, $field);
1643 83
                break;
1644 138
            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 138
            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 137
            case 'array':
1653 34
                $result = $this->validateArray($value, $field);
1654 34
                break;
1655 117
            case 'object':
1656 115
                $result = $this->validateObject($value, $field);
1657 113
                break;
1658 6
            case 'null':
1659 1
                $result = $this->validateNull($value, $field);
1660 1
                break;
1661 5
            case '':
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 210
        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' => 'The value must be 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' => 'The value must be less than {maximum}.', 'maximum' => $maximum]);
1771
                } else {
1772 1
                    $field->addError('maximum', ['messageCode' => 'The value 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' => 'The value must be greater than {minimum}.', 'minimum' => $minimum]);
1784
                } else {
1785 1
                    $field->addError('minimum', ['messageCode' => 'The value must be greater than or equal to {minimum}.', 'minimum' => $minimum]);
1786
                }
1787
            }
1788
        }
1789
1790 57
        return $field->getErrorCount() === $count ? $value : Invalid::value();
1791
    }
1792
1793
    /**
1794
     * Parse a nested field name selector.
1795
     *
1796
     * Field selectors should be separated by "/" characters, but may currently be separated by "." characters which
1797
     * triggers a deprecated error.
1798
     *
1799
     * @param string $field The field selector.
1800
     * @return string Returns the field selector in the correct format.
1801
     */
1802 15
    private function parseFieldSelector(string $field): string {
1803 15
        if (strlen($field) === 0) {
1804 4
            return $field;
1805
        }
1806
1807 11
        if (strpos($field, '.') !== false) {
1808 1
            if (strpos($field, '/') === false) {
1809 1
                trigger_error('Field selectors must be separated by "/" instead of "."', E_USER_DEPRECATED);
1810
1811 1
                $parts = explode('.', $field);
1812 1
                $parts = @array_map([$this, 'parseFieldSelector'], $parts); // silence because error triggered already.
1813
1814 1
                $field = implode('/', $parts);
1815
            }
1816 11
        } elseif ($field === '[]') {
1817 1
            trigger_error('Field selectors with item selector "[]" must be converted to "items".', E_USER_DEPRECATED);
1818 1
            $field = 'items';
1819 10
        } elseif (strpos($field, '/') === false && !in_array($field, ['items', 'additionalProperties'], true)) {
1820 3
            trigger_error("Field selectors must specify full schema paths. ($field)", E_USER_DEPRECATED);
1821 3
            $field = "/properties/$field";
1822
        }
1823
1824 11
        if (strpos($field, '[]') !== false) {
1825 1
            trigger_error('Field selectors with item selector "[]" must be converted to "/items".', E_USER_DEPRECATED);
1826 1
            $field = str_replace('[]', '/items', $field);
1827
        }
1828
1829 11
        return ltrim($field, '/');
1830
    }
1831
1832
    /**
1833
     * Lookup a schema based on a schema node.
1834
     *
1835
     * The node could be a schema array, `Schema` object, or a schema reference.
1836
     *
1837
     * @param mixed $schema The schema node to lookup with.
1838
     * @param string $schemaPath The current path of the schema.
1839
     * @return array Returns an array with two elements:
1840
     * - Schema|array|\ArrayAccess The schema that was found.
1841
     * - string The path of the schema. This is either the reference or the `$path` parameter for inline schemas.
1842
     * @throws RefNotFoundException Throws an exception when a reference could not be found.
1843
     */
1844 214
    private function lookupSchema($schema, string $schemaPath) {
1845 214
        if ($schema instanceof Schema) {
1846 6
            return [$schema, $schemaPath];
1847
        } else {
1848 214
            $lookup = $this->getRefLookup();
1849 214
            $visited = [];
1850
1851 214
            while (!empty($schema['$ref'])) {
1852 11
                $schemaPath = $schema['$ref'];
1853
1854 11
                if (isset($visited[$schemaPath])) {
1855 1
                    throw new RefNotFoundException("Cyclical reference cannot be resolved. ($schemaPath)", 508);
1856
                }
1857 11
                $visited[$schemaPath] = true;
1858
1859
                try {
1860 11
                    $schema = call_user_func($lookup, $schemaPath);
1861 1
                } catch (\Exception $ex) {
1862 1
                    throw new RefNotFoundException($ex->getMessage(), $ex->getCode(), $ex);
1863
                }
1864 10
                if ($schema === null) {
1865 2
                    throw new RefNotFoundException("Schema reference could not be found. ($schemaPath)");
1866
                }
1867
            }
1868 210
            return [$schema, $schemaPath];
1869
        }
1870
    }
1871
1872
    /**
1873
     * Get the function used to resolve `$ref` lookups.
1874
     *
1875
     * @return callable Returns the current `$ref` lookup.
1876
     */
1877 214
    public function getRefLookup(): callable {
1878 214
        return $this->refLookup;
1879
    }
1880
1881
    /**
1882
     * Set the function used to resolve `$ref` lookups.
1883
     *
1884
     * @param callable $refLookup The new lookup function.
1885
     * @return $this
1886
     */
1887 10
    public function setRefLookup(callable $refLookup) {
1888 10
        $this->refLookup = $refLookup;
1889 10
        return $this;
1890
    }
1891
1892
    /**
1893
     * Get factory used to create validation objects.
1894
     *
1895
     * @return callable Returns the current factory.
1896
     */
1897 210
    public function getValidationFactory(): callable {
1898 210
        return $this->validationFactory;
1899
    }
1900
1901
    /**
1902
     * Set the factory used to create validation objects.
1903
     *
1904
     * @param callable $validationFactory The new factory.
1905
     * @return $this
1906
     */
1907 2
    public function setValidationFactory(callable $validationFactory) {
1908 2
        $this->validationFactory = $validationFactory;
1909 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

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