Completed
Pull Request — master (#58)
by Todd
03:43 queued 01:30
created

Schema::validateEnum()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 3
nop 2
dl 0
loc 17
ccs 11
cts 11
cp 1
crap 3
rs 9.9332
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 265
    public function __construct(array $schema = []) {
89 265
        $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 207
            return new Validation();
95
        };
96 265
    }
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 are 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('oneOfRequired', [
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 212
    public function validate($data, $options = []) {
740 212
        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 212
        $options += ['sparse' => false];
745
746
747 212
        list($schema, $schemaPath) = $this->lookupSchema($this->schema, '');
748 209
        $field = new ValidationField($this->createValidation(), $schema, '', $schemaPath, $options);
749
750 209
        $clean = $this->validateField($data, $field);
751
752 207
        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' => 'The value is invalid.']);
755
        }
756
757 207
        if (!$field->getValidation()->isValid()) {
758 72
            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 209
    protected function validateField($value, ValidationField $field) {
789 209
        $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 209
        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 209
        } 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 209
            $type = $field->getType();
803 209
            if (is_array($type)) {
804 29
                $result = $this->validateMultipleTypes($value, $type, $field);
805
            } else {
806 188
                $result = $this->validateSingleType($value, $type, $field);
807
            }
808 209
            if (Invalid::isValid($result)) {
809 200
                $result = $this->validateEnum($result, $field);
810
            }
811
        }
812
813
        // Validate a custom field validator.
814 209
        if (Invalid::isValid($result)) {
815 200
            $this->callValidators($result, $field);
816
        }
817
818 209
        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' => 'Array 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' => 'Array 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' => 'Array 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 59
    protected function validateInteger($value, ValidationField $field) {
974 59
        if ($field->val('format') === 'timestamp') {
975 7
            return $this->validateTimestamp($value, $field);
976
        }
977
978 54
        $result = filter_var($value, FILTER_VALIDATE_INT);
979
980 54
        if ($result === false) {
981 11
            $field->addTypeError($value, 'integer');
982 11
            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 115
    protected function validateObject($value, ValidationField $field) {
998 115
        if (!$this->isArray($value) || isset($value[0])) {
999 6
            $field->addTypeError($value, 'object');
1000 6
            return Invalid::value();
1001 115
        } elseif (is_array($field->val('properties')) || null !== $field->val('additionalProperties')) {
1002
            // Validate the data against the internal schema.
1003 108
            $value = $this->validateProperties($value, $field);
1004 7
        } elseif (!is_array($value)) {
1005 3
            $value = $this->toObjectArray($value);
1006
        }
1007
1008 113
        if (($maxProperties = $field->val('maxProperties')) && count($value) > $maxProperties) {
1009 1
            $field->addError(
1010 1
                'maxProperties',
1011
                [
1012 1
                    'messageCode' => 'Object must contain no more than {maxProperties} {maxProperties,plural,item}.',
1013 1
                    'maxItems' => $maxProperties,
1014
                ]
1015
            );
1016
        }
1017
1018 113
        if (($minProperties = $field->val('minProperties')) && count($value) < $minProperties) {
1019 1
            $field->addError(
1020 1
                'minProperties',
1021
                [
1022 1
                    'messageCode' => 'Object must contain at least {minProperties} {minProperties,plural,item}.',
1023 1
                    'minItems' => $minProperties,
1024
                ]
1025
            );
1026
        }
1027
1028 113
        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 108
    protected function validateProperties($data, ValidationField $field) {
1041 108
        $properties = $field->val('properties', []);
1042 108
        $additionalProperties = $field->val('additionalProperties');
1043 108
        $required = array_flip($field->val('required', []));
1044 108
        $isRequest = $field->isRequest();
1045 108
        $isResponse = $field->isResponse();
1046
1047 108
        if (is_array($data)) {
1048 104
            $keys = array_keys($data);
1049 104
            $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 108
        $keys = array_combine(array_map('strtolower', $keys), $keys);
1061
1062 108
        $propertyField = new ValidationField($field->getValidation(), [], '', '', $field->getOptions());
1063
1064
        // Loop through the schema fields and validate each one.
1065 108
        foreach ($properties as $propertyName => $property) {
1066 106
            list($property, $schemaPath) = $this->lookupSchema($property, $field->getSchemaPath().'/properties/'.$propertyField->escapeRef($propertyName));
1067
1068
            $propertyField
1069 106
                ->setField($property)
1070 106
                ->setName(ltrim($field->getName().'/'.$propertyField->escapeRef($propertyName), '/'))
1071 106
                ->setSchemaPath($schemaPath)
1072
            ;
1073
1074 106
            $lName = strtolower($propertyName);
1075 106
            $isRequired = isset($required[$propertyName]);
1076
1077
            // Check to strip this field if it is readOnly or writeOnly.
1078 106
            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 106
            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 6
                    $propertyField->addError(
1091 6
                        'required',
1092 30
                        ['messageCode' => '{property} is required.', 'property' => $propertyName]
1093
                    );
1094
                }
1095
            } else {
1096 94
                $value = $data[$keys[$lName]];
1097
1098 94
                if (in_array($value, [null, ''], true) && !$isRequired && !($propertyField->val('nullable') || $propertyField->hasType('null'))) {
1099 5
                    if ($propertyField->getType() !== 'string' || $value === null) {
1100 2
                        continue;
1101
                    }
1102
                }
1103
1104 92
                $clean[$propertyName] = $this->validateField($value, $propertyField);
1105
            }
1106
1107 104
            unset($keys[$lName]);
1108
        }
1109
1110
        // Look for extraneous properties.
1111 108
        if (!empty($keys)) {
1112 17
            if ($additionalProperties) {
1113 6
                list($additionalProperties, $schemaPath) = $this->lookupSchema(
1114 6
                    $additionalProperties,
1115 6
                    $field->getSchemaPath().'/additionalProperties'
1116
                );
1117
1118 6
                $propertyField = new ValidationField(
1119 6
                    $field->getValidation(),
1120 6
                    $additionalProperties,
1121 6
                    '',
1122 6
                    $schemaPath,
1123 6
                    $field->getOptions()
1124
                );
1125
1126 6
                foreach ($keys as $key) {
1127
                    $propertyField
1128 6
                        ->setName(ltrim($field->getName()."/$key", '/'));
1129
1130 6
                    $valid = $this->validateField($data[$key], $propertyField);
1131 6
                    if (Invalid::isValid($valid)) {
1132 6
                        $clean[$key] = $valid;
1133
                    }
1134
                }
1135 11
            } elseif ($this->hasFlag(Schema::VALIDATE_EXTRA_PROPERTY_NOTICE)) {
1136 2
                $msg = sprintf("Unexpected properties: %s.", implode(', ', $keys));
1137 2
                trigger_error($msg, E_USER_NOTICE);
1138 9
            } elseif ($this->hasFlag(Schema::VALIDATE_EXTRA_PROPERTY_EXCEPTION)) {
1139 2
                $field->addError('unexpectedProperties', [
1140 2
                    'messageCode' => 'Unexpected {extra,plural,property,properties}: {extra}.',
1141 2
                    'extra' => array_values($keys),
1142
                ]);
1143
            }
1144
        }
1145
1146 106
        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...
1147
    }
1148
1149
    /**
1150
     * Validate a string.
1151
     *
1152
     * @param mixed $value The value to validate.
1153
     * @param ValidationField $field The validation results to add.
1154
     * @return string|Invalid Returns the valid string or **null** if validation fails.
1155
     */
1156 83
    protected function validateString($value, ValidationField $field) {
1157 83
        if ($field->val('format') === 'date-time') {
1158 12
            $result = $this->validateDatetime($value, $field);
1159 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...
1160
        }
1161
1162 72
        if (is_string($value) || is_numeric($value)) {
1163 70
            $value = $result = (string)$value;
1164
        } else {
1165 5
            $field->addTypeError($value, 'string');
1166 5
            return Invalid::value();
1167
        }
1168
1169 70
        if (($minLength = $field->val('minLength', 0)) > 0 && mb_strlen($value) < $minLength) {
1170 4
            $field->addError(
1171 4
                'minLength',
1172
                [
1173 4
                    'messageCode' => 'The value should be at least {minLength} {minLength,plural,character} long.',
1174 4
                    'minLength' => $minLength,
1175
                ]
1176
            );
1177
        }
1178 70
        if (($maxLength = $field->val('maxLength', 0)) > 0 && mb_strlen($value) > $maxLength) {
1179 1
            $field->addError(
1180 1
                'maxLength',
1181
                [
1182 1
                    'messageCode' => 'The value is {overflow} {overflow,plural,characters} too long.',
1183 1
                    'maxLength' => $maxLength,
1184 1
                    'overflow' => mb_strlen($value) - $maxLength,
1185
                ]
1186
            );
1187
        }
1188 70
        if ($pattern = $field->val('pattern')) {
1189 4
            $regex = '`'.str_replace('`', preg_quote('`', '`'), $pattern).'`';
1190
1191 4
            if (!preg_match($regex, $value)) {
1192 2
                $field->addError(
1193 2
                    'pattern',
1194
                    [
1195 2
                        'messageCode' => $field->val('x-patternMessageCode'. 'The value doesn\'t match the required pattern.'),
1196
                    ]
1197
                );
1198
            }
1199
        }
1200 70
        if ($format = $field->val('format')) {
1201 11
            $type = $format;
1202 11
            switch ($format) {
1203 11
                case 'date':
1204
                    $result = $this->validateDatetime($result, $field);
1205
                    if ($result instanceof \DateTimeInterface) {
1206
                        $result = $result->format("Y-m-d\T00:00:00P");
1207
                    }
1208
                    break;
1209 11
                case 'email':
1210 1
                    $result = filter_var($result, FILTER_VALIDATE_EMAIL);
1211 1
                    break;
1212 10
                case 'ipv4':
1213 1
                    $type = 'IPv4 address';
1214 1
                    $result = filter_var($result, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
1215 1
                    break;
1216 9
                case 'ipv6':
1217 1
                    $type = 'IPv6 address';
1218 1
                    $result = filter_var($result, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
1219 1
                    break;
1220 8
                case 'ip':
1221 1
                    $type = 'IP address';
1222 1
                    $result = filter_var($result, FILTER_VALIDATE_IP);
1223 1
                    break;
1224 7
                case 'uri':
1225 7
                    $type = 'URI';
1226 7
                    $result = filter_var($result, FILTER_VALIDATE_URL);
1227 7
                    break;
1228
                default:
1229
                    trigger_error("Unrecognized format '$format'.", E_USER_NOTICE);
1230
            }
1231 11
            if ($result === false) {
1232 5
                $field->addError('format', [
1233 5
                    'format' => $format,
1234 5
                    'formatCode' => $type,
1235 5
                    'value' => $value,
1236 5
                    'messageCode' => '{value} is not a valid {formatCode}.'
1237
                ]);
1238
            }
1239
        }
1240
1241 70
        if ($field->isValid()) {
1242 62
            return $result;
1243
        } else {
1244 12
            return Invalid::value();
1245
        }
1246
    }
1247
1248
    /**
1249
     * Validate a unix timestamp.
1250
     *
1251
     * @param mixed $value The value to validate.
1252
     * @param ValidationField $field The field being validated.
1253
     * @return int|Invalid Returns a valid timestamp or invalid if the value doesn't validate.
1254
     */
1255 8
    protected function validateTimestamp($value, ValidationField $field) {
1256 8
        if (is_numeric($value) && $value > 0) {
1257 3
            $result = (int)$value;
1258 5
        } elseif (is_string($value) && $ts = strtotime($value)) {
1259 1
            $result = $ts;
1260
        } else {
1261 4
            $field->addTypeError($value, 'timestamp');
1262 4
            $result = Invalid::value();
1263
        }
1264 8
        return $result;
1265
    }
1266
1267
    /**
1268
     * Validate a null value.
1269
     *
1270
     * @param mixed $value The value to validate.
1271
     * @param ValidationField $field The error collector for the field.
1272
     * @return null|Invalid Returns **null** or invalid.
1273
     */
1274
    protected function validateNull($value, ValidationField $field) {
1275
        if ($value === null) {
1276
            return null;
1277
        }
1278
        $field->addError('type', ['messageCode' => 'The value should be null.', 'type' => 'null']);
1279
        return Invalid::value();
1280
    }
1281
1282
    /**
1283
     * Validate a value against an enum.
1284
     *
1285
     * @param mixed $value The value to test.
1286
     * @param ValidationField $field The validation object for adding errors.
1287
     * @return mixed|Invalid Returns the value if it is one of the enumerated values or invalid otherwise.
1288
     */
1289 200
    protected function validateEnum($value, ValidationField $field) {
1290 200
        $enum = $field->val('enum');
1291 200
        if (empty($enum)) {
1292 199
            return $value;
1293
        }
1294
1295 1
        if (!in_array($value, $enum, true)) {
1296 1
            $field->addError(
1297 1
                'enum',
1298
                [
1299 1
                    'messageCode' => 'The value must be one of: {enum}.',
1300 1
                    'enum' => $enum,
1301
                ]
1302
            );
1303 1
            return Invalid::value();
1304
        }
1305 1
        return $value;
1306
    }
1307
1308
    /**
1309
     * Call all of the filters attached to a field.
1310
     *
1311
     * @param mixed $value The field value being filtered.
1312
     * @param ValidationField $field The validation object.
1313
     * @return mixed Returns the filtered value. If there are no filters for the field then the original value is returned.
1314
     */
1315 209
    protected function callFilters($value, ValidationField $field) {
1316
        // Strip array references in the name except for the last one.
1317 209
        $key = $field->getSchemaPath();
1318 209
        if (!empty($this->filters[$key])) {
1319 2
            foreach ($this->filters[$key] as $filter) {
1320 2
                $value = call_user_func($filter, $value, $field);
1321
            }
1322
        }
1323 209
        return $value;
1324
    }
1325
1326
    /**
1327
     * Call all of the validators attached to a field.
1328
     *
1329
     * @param mixed $value The field value being validated.
1330
     * @param ValidationField $field The validation object to add errors.
1331
     */
1332 200
    protected function callValidators($value, ValidationField $field) {
1333 200
        $valid = true;
1334
1335
        // Strip array references in the name except for the last one.
1336 200
        $key = $field->getSchemaPath();
1337 200
        if (!empty($this->validators[$key])) {
1338 5
            foreach ($this->validators[$key] as $validator) {
1339 5
                $r = call_user_func($validator, $value, $field);
1340
1341 5
                if ($r === false || Invalid::isInvalid($r)) {
1342 5
                    $valid = false;
1343
                }
1344
            }
1345
        }
1346
1347
        // Add an error on the field if the validator hasn't done so.
1348 200
        if (!$valid && $field->isValid()) {
1349 1
            $field->addError('invalid', ['messageCode' => 'The value is invalid.']);
1350
        }
1351 200
    }
1352
1353
    /**
1354
     * Specify data which should be serialized to JSON.
1355
     *
1356
     * This method specifically returns data compatible with the JSON schema format.
1357
     *
1358
     * @return mixed Returns data which can be serialized by **json_encode()**, which is a value of any type other than a resource.
1359
     * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
1360
     * @link http://json-schema.org/
1361
     */
1362 16
    public function jsonSerialize() {
1363
        $fix = function ($schema) use (&$fix) {
1364 16
            if ($schema instanceof Schema) {
1365 1
                return $schema->jsonSerialize();
1366
            }
1367
1368 16
            if (!empty($schema['type'])) {
1369 15
                $types = (array)$schema['type'];
1370
1371 15
                foreach ($types as $i => &$type) {
1372
                    // Swap datetime and timestamp to other types with formats.
1373 15
                    if ($type === 'datetime') {
1374 4
                        $type = 'string';
1375 4
                        $schema['format'] = 'date-time';
1376 14
                    } elseif ($schema['type'] === 'timestamp') {
1377 2
                        $type = 'integer';
1378 15
                        $schema['format'] = 'timestamp';
1379
                    }
1380
                }
1381 15
                $types = array_unique($types);
1382 15
                $schema['type'] = count($types) === 1 ? reset($types) : $types;
1383
            }
1384
1385 16
            if (!empty($schema['items'])) {
1386 4
                $schema['items'] = $fix($schema['items']);
1387
            }
1388 16
            if (!empty($schema['properties'])) {
1389 11
                $properties = [];
1390 11
                foreach ($schema['properties'] as $key => $property) {
1391 11
                    $properties[$key] = $fix($property);
1392
                }
1393 11
                $schema['properties'] = $properties;
1394
            }
1395
1396 16
            return $schema;
1397 16
        };
1398
1399 16
        $result = $fix($this->schema);
1400
1401 16
        return $result;
1402
    }
1403
1404
    /**
1405
     * Look up a type based on its alias.
1406
     *
1407
     * @param string $alias The type alias or type name to lookup.
1408
     * @return mixed
1409
     */
1410 167
    protected function getType($alias) {
1411 167
        if (isset(self::$types[$alias])) {
1412
            return $alias;
1413
        }
1414 167
        foreach (self::$types as $type => $aliases) {
1415 167
            if (in_array($alias, $aliases, true)) {
1416 167
                return $type;
1417
            }
1418
        }
1419 11
        return null;
1420
    }
1421
1422
    /**
1423
     * Get the class that's used to contain validation information.
1424
     *
1425
     * @return Validation|string Returns the validation class.
1426
     * @deprecated
1427
     */
1428 1
    public function getValidationClass() {
1429 1
        trigger_error('Schema::getValidationClass() is deprecated. Use Schema::getValidationFactory() instead.', E_USER_DEPRECATED);
1430 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

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

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

1914
        /** @scrutinizer ignore-deprecated */ $this->validationClass = null;
Loading history...
1915 2
        return $this;
1916
    }
1917
}
1918