Passed
Push — master ( b09738...4c903b )
by Todd
35s
created

Schema::getTitle()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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

367
        $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...
368 173
        $schema->schema = $schema->parseInternal($arr);
369 172
        return $schema;
370
    }
371
372
    /**
373
     * Parse a schema in short form into a full schema array.
374
     *
375
     * @param array $arr The array to parse into a schema.
376
     * @return array The full schema array.
377
     * @throws \InvalidArgumentException Throws an exception when an item in the schema is invalid.
378
     */
379 173
    protected function parseInternal(array $arr): array {
380 173
        if (empty($arr)) {
381
            // An empty schema validates to anything.
382 6
            return [];
383 168
        } elseif (isset($arr['type'])) {
384
            // This is a long form schema and can be parsed as the root.
385
            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...
386
        } else {
387
            // Check for a root schema.
388 168
            $value = reset($arr);
389 168
            $key = key($arr);
390 168
            if (is_int($key)) {
391 105
                $key = $value;
392 105
                $value = null;
393
            }
394 168
            list ($name, $param) = $this->parseShortParam($key, $value);
395 167
            if (empty($name)) {
396 62
                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...
397
            }
398
        }
399
400
        // If we are here then this is n object schema.
401 108
        list($properties, $required) = $this->parseProperties($arr);
402
403
        $result = [
404 108
            'type' => 'object',
405 108
            'properties' => $properties,
406 108
            'required' => $required
407
        ];
408
409 108
        return array_filter($result);
410
    }
411
412
    /**
413
     * Parse a schema node.
414
     *
415
     * @param array $node The node to parse.
416
     * @param mixed $value Additional information from the node.
417
     * @return array|\ArrayAccess Returns a JSON schema compatible node.
418
     */
419 167
    private function parseNode($node, $value = null) {
420 167
        if (is_array($value)) {
421 64
            if (is_array($node['type'])) {
422
                trigger_error('Schemas with multiple types is deprecated.', E_USER_DEPRECATED);
423
            }
424
425
            // The value describes a bit more about the schema.
426 64
            switch ($node['type']) {
427 64
                case 'array':
428 11
                    if (isset($value['items'])) {
429
                        // The value includes array schema information.
430 4
                        $node = array_replace($node, $value);
431
                    } else {
432 7
                        $node['items'] = $this->parseInternal($value);
433
                    }
434 11
                    break;
435 54
                case 'object':
436
                    // The value is a schema of the object.
437 12
                    if (isset($value['properties'])) {
438
                        list($node['properties']) = $this->parseProperties($value['properties']);
439
                    } else {
440 12
                        list($node['properties'], $required) = $this->parseProperties($value);
441 12
                        if (!empty($required)) {
442 12
                            $node['required'] = $required;
443
                        }
444
                    }
445 12
                    break;
446
                default:
447 42
                    $node = array_replace($node, $value);
448 64
                    break;
449
            }
450 128
        } elseif (is_string($value)) {
451 101
            if ($node['type'] === 'array' && $arrType = $this->getType($value)) {
452 6
                $node['items'] = ['type' => $arrType];
453 97
            } elseif (!empty($value)) {
454 101
                $node['description'] = $value;
455
            }
456 32
        } elseif ($value === null) {
457
            // Parse child elements.
458 28
            if ($node['type'] === 'array' && isset($node['items'])) {
459
                // The value includes array schema information.
460
                $node['items'] = $this->parseInternal($node['items']);
461 28
            } elseif ($node['type'] === 'object' && isset($node['properties'])) {
462
                list($node['properties']) = $this->parseProperties($node['properties']);
463
464
            }
465
        }
466
467 167
        if (is_array($node)) {
468 166
            if (!empty($node['allowNull'])) {
469 1
                $node['nullable'] = true;
470
            }
471 166
            unset($node['allowNull']);
472
473 166
            if ($node['type'] === null || $node['type'] === []) {
474 4
                unset($node['type']);
475
            }
476
        }
477
478 167
        return $node;
479
    }
480
481
    /**
482
     * Parse the schema for an object's properties.
483
     *
484
     * @param array $arr An object property schema.
485
     * @return array Returns a schema array suitable to be placed in the **properties** key of a schema.
486
     */
487 108
    private function parseProperties(array $arr): array {
488 108
        $properties = [];
489 108
        $requiredProperties = [];
490 108
        foreach ($arr as $key => $value) {
491
            // Fix a schema specified as just a value.
492 108
            if (is_int($key)) {
493 81
                if (is_string($value)) {
494 81
                    $key = $value;
495 81
                    $value = '';
496
                } else {
497
                    throw new \InvalidArgumentException("Schema at position $key is not a valid parameter.", 500);
498
                }
499
            }
500
501
            // The parameter is defined in the key.
502 108
            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

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

793
            if ((null !== $minItems = $field->val('minItems')) && count(/** @scrutinizer ignore-type */ $value) < $minItems) {
Loading history...
794 1
                $field->addError(
795 1
                    'minItems',
796
                    [
797 1
                        'messageCode' => '{field} must contain at least {minItems} {minItems,plural,item}.',
798 1
                        'minItems' => $minItems,
799 1
                        'status' => 422
800
                    ]
801
                );
802
            }
803 27
            if ((null !== $maxItems = $field->val('maxItems')) && count($value) > $maxItems) {
804 1
                $field->addError(
805 1
                    'maxItems',
806
                    [
807 1
                        'messageCode' => '{field} must contain no more than {maxItems} {maxItems,plural,item}.',
808 1
                        'maxItems' => $maxItems,
809 1
                        'status' => 422
810
                    ]
811
                );
812
            }
813
814 27
            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

814
            if ($field->val('uniqueItems') && count($value) > count(array_unique(/** @scrutinizer ignore-type */ $value))) {
Loading history...
815 1
                $field->addError(
816 1
                    'uniqueItems',
817
                    [
818 1
                        'messageCode' => '{field} must contain unique items.',
819
                        'status' => 422,
820
                    ]
821
                );
822
            }
823
824 27
            if ($field->val('items') !== null) {
825 19
                $result = [];
826
827
                // Validate each of the types.
828 19
                $itemValidation = new ValidationField(
829 19
                    $field->getValidation(),
830 19
                    $field->val('items'),
831 19
                    '',
832 19
                    $field->getOptions()
833
                );
834
835 19
                $count = 0;
836 19
                foreach ($value as $i => $item) {
837 19
                    $itemValidation->setName($field->getName()."[{$i}]");
838 19
                    $validItem = $this->validateField($item, $itemValidation);
839 19
                    if (Invalid::isValid($validItem)) {
840 19
                        $result[] = $validItem;
841
                    }
842 19
                    $count++;
843
                }
844
845 19
                return empty($result) && $count > 0 ? Invalid::value() : $result;
846
            } else {
847
                // Cast the items into a proper numeric array.
848 8
                $result = is_array($value) ? array_values($value) : iterator_to_array($value);
849 8
                return $result;
850
            }
851
        }
852
    }
853
854
    /**
855
     * Validate a boolean value.
856
     *
857
     * @param mixed $value The value to validate.
858
     * @param ValidationField $field The validation results to add.
859
     * @return bool|Invalid Returns the cleaned value or invalid if validation fails.
860
     */
861 32
    protected function validateBoolean($value, ValidationField $field) {
862 32
        $value = $value === null ? $value : filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
863 32
        if ($value === null) {
864 4
            $field->addTypeError('boolean');
865 4
            return Invalid::value();
866
        }
867
868 29
        return $value;
869
    }
870
871
    /**
872
     * Validate a date time.
873
     *
874
     * @param mixed $value The value to validate.
875
     * @param ValidationField $field The validation results to add.
876
     * @return \DateTimeInterface|Invalid Returns the cleaned value or **null** if it isn't valid.
877
     */
878 14
    protected function validateDatetime($value, ValidationField $field) {
879 14
        if ($value instanceof \DateTimeInterface) {
880
            // do nothing, we're good
881 11
        } elseif (is_string($value) && $value !== '' && !is_numeric($value)) {
882
            try {
883 7
                $dt = new \DateTimeImmutable($value);
884 6
                if ($dt) {
0 ignored issues
show
introduced by
$dt is of type DateTimeImmutable, thus it always evaluated to true.
Loading history...
885 6
                    $value = $dt;
886
                } else {
887 6
                    $value = null;
888
                }
889 1
            } catch (\Throwable $ex) {
890 7
                $value = Invalid::value();
891
            }
892 4
        } elseif (is_int($value) && $value > 0) {
893
            try {
894 1
                $value = new \DateTimeImmutable('@'.(string)round($value));
895
            } catch (\Throwable $ex) {
896 1
                $value = Invalid::value();
897
            }
898
        } else {
899 3
            $value = Invalid::value();
900
        }
901
902 14
        if (Invalid::isInvalid($value)) {
903 4
            $field->addTypeError('datetime');
904
        }
905 14
        return $value;
906
    }
907
908
    /**
909
     * Validate a float.
910
     *
911
     * @param mixed $value The value to validate.
912
     * @param ValidationField $field The validation results to add.
913
     * @return float|Invalid Returns a number or **null** if validation fails.
914
     */
915 17
    protected function validateNumber($value, ValidationField $field) {
916 17
        $result = filter_var($value, FILTER_VALIDATE_FLOAT);
917 17
        if ($result === false) {
918 4
            $field->addTypeError('number');
919 4
            return Invalid::value();
920
        }
921
922 13
        $result = $this->validateNumberProperties($result, $field);
923
924 13
        return $result;
925
    }
926
    /**
927
     * Validate and integer.
928
     *
929
     * @param mixed $value The value to validate.
930
     * @param ValidationField $field The validation results to add.
931
     * @return int|Invalid Returns the cleaned value or **null** if validation fails.
932
     */
933 51
    protected function validateInteger($value, ValidationField $field) {
934 51
        if ($field->val('format') === 'timestamp') {
935 7
            return $this->validateTimestamp($value, $field);
936
        }
937
938 46
        $result = filter_var($value, FILTER_VALIDATE_INT);
939
940 46
        if ($result === false) {
941 9
            $field->addTypeError('integer');
942 9
            return Invalid::value();
943
        }
944
945 41
        $result = $this->validateNumberProperties($result, $field);
946
947 41
        return $result;
948
    }
949
950
    /**
951
     * Validate an object.
952
     *
953
     * @param mixed $value The value to validate.
954
     * @param ValidationField $field The validation results to add.
955
     * @return object|Invalid Returns a clean object or **null** if validation fails.
956
     */
957 104
    protected function validateObject($value, ValidationField $field) {
958 104
        if (!$this->isArray($value) || isset($value[0])) {
959 6
            $field->addTypeError('object');
960 6
            return Invalid::value();
961 104
        } elseif (is_array($field->val('properties')) || null !== $field->val('additionalProperties')) {
962
            // Validate the data against the internal schema.
963 97
            $value = $this->validateProperties($value, $field);
964 7
        } elseif (!is_array($value)) {
965 3
            $value = $this->toObjectArray($value);
966
        }
967
968 102
        if (($maxProperties = $field->val('maxProperties')) && count($value) > $maxProperties) {
969 1
            $field->addError(
970 1
                'maxItems',
971
                [
972 1
                    'messageCode' => '{field} must contain no more than {maxProperties} {maxProperties,plural,item}.',
973 1
                    'maxItems' => $maxProperties,
974 1
                    'status' => 422
975
                ]
976
            );
977
        }
978
979 102
        if (($minProperties = $field->val('minProperties')) && count($value) < $minProperties) {
980 1
            $field->addError(
981 1
                'minItems',
982
                [
983 1
                    'messageCode' => '{field} must contain at least {minProperties} {minProperties,plural,item}.',
984 1
                    'minItems' => $minProperties,
985 1
                    'status' => 422
986
                ]
987
            );
988
        }
989
990 102
        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...
991
    }
992
993
    /**
994
     * Validate data against the schema and return the result.
995
     *
996
     * @param array|\Traversable&\ArrayAccess $data The data to validate.
997
     * @param ValidationField $field This argument will be filled with the validation result.
998
     * @return array|Invalid Returns a clean array with only the appropriate properties and the data coerced to proper types.
999
     * or invalid if there are no valid properties.
1000
     */
1001 97
    protected function validateProperties($data, ValidationField $field) {
1002 97
        $properties = $field->val('properties', []);
1003 97
        $additionalProperties = $field->val('additionalProperties');
1004 97
        $required = array_flip($field->val('required', []));
1005
1006 97
        if (is_array($data)) {
0 ignored issues
show
introduced by
The condition is_array($data) is always false.
Loading history...
1007 93
            $keys = array_keys($data);
1008 93
            $clean = [];
1009
        } else {
1010 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

1010
            $keys = array_keys(iterator_to_array(/** @scrutinizer ignore-type */ $data));
Loading history...
1011 4
            $class = get_class($data);
1012 4
            $clean = new $class;
1013
1014 4
            if ($clean instanceof \ArrayObject && $data instanceof \ArrayObject) {
1015 3
                $clean->setFlags($data->getFlags());
1016 3
                $clean->setIteratorClass($data->getIteratorClass());
1017
            }
1018
        }
1019 97
        $keys = array_combine(array_map('strtolower', $keys), $keys);
1020
1021 97
        $propertyField = new ValidationField($field->getValidation(), [], null, $field->getOptions());
1022
1023
        // Loop through the schema fields and validate each one.
1024 97
        foreach ($properties as $propertyName => $property) {
1025
            $propertyField
1026 96
                ->setField($property)
1027 96
                ->setName(ltrim($field->getName().".$propertyName", '.'));
1028
1029 96
            $lName = strtolower($propertyName);
1030 96
            $isRequired = isset($required[$propertyName]);
1031
1032
            // First check for required fields.
1033 96
            if (!array_key_exists($lName, $keys)) {
1034 26
                if ($field->isSparse()) {
1035
                    // Sparse validation can leave required fields out.
1036 25
                } elseif ($propertyField->hasVal('default')) {
1037 2
                    $clean[$propertyName] = $propertyField->val('default');
1038 23
                } elseif ($isRequired) {
1039 26
                    $propertyField->addError('missingField', ['messageCode' => '{field} is required.']);
1040
                }
1041
            } else {
1042 85
                $value = $data[$keys[$lName]];
1043
1044 85
                if (in_array($value, [null, ''], true) && !$isRequired && !($propertyField->val('nullable') || $propertyField->hasType('null'))) {
1045 5
                    if ($propertyField->getType() !== 'string' || $value === null) {
1046 2
                        continue;
1047
                    }
1048
                }
1049
1050 83
                $clean[$propertyName] = $this->validateField($value, $propertyField);
1051
            }
1052
1053 94
            unset($keys[$lName]);
1054
        }
1055
1056
        // Look for extraneous properties.
1057 97
        if (!empty($keys)) {
1058 14
            if ($additionalProperties) {
1059 3
                $propertyField = new ValidationField($field->getValidation(), $additionalProperties, null, $field->getOptions());
1060
1061 3
                foreach ($keys as $key) {
1062
                    $propertyField
1063 3
                        ->setName(ltrim($field->getName().".$key", '.'));
1064
1065 3
                    $valid = $this->validateField($data[$key], $propertyField);
1066 3
                    if (Invalid::isValid($valid)) {
1067 3
                        $clean[$key] = $valid;
1068
                    }
1069
                }
1070 11
            } elseif ($this->hasFlag(Schema::VALIDATE_EXTRA_PROPERTY_NOTICE)) {
1071 2
                $msg = sprintf("%s has unexpected field(s): %s.", $field->getName() ?: 'value', implode(', ', $keys));
1072 2
                trigger_error($msg, E_USER_NOTICE);
1073 9
            } elseif ($this->hasFlag(Schema::VALIDATE_EXTRA_PROPERTY_EXCEPTION)) {
1074 2
                $field->addError('invalid', [
1075 2
                    'messageCode' => '{field} has {extra,plural,an unexpected field,unexpected fields}: {extra}.',
1076 2
                    'extra' => array_values($keys),
1077 2
                    'status' => 422
1078
                ]);
1079
            }
1080
        }
1081
1082 95
        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...
1083
    }
1084
1085
    /**
1086
     * Validate a string.
1087
     *
1088
     * @param mixed $value The value to validate.
1089
     * @param ValidationField $field The validation results to add.
1090
     * @return string|Invalid Returns the valid string or **null** if validation fails.
1091
     */
1092 75
    protected function validateString($value, ValidationField $field) {
1093 75
        if ($field->val('format') === 'date-time') {
1094 12
            $result = $this->validateDatetime($value, $field);
1095 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...
1096
        }
1097
1098 64
        if (is_string($value) || is_numeric($value)) {
1099 62
            $value = $result = (string)$value;
1100
        } else {
1101 5
            $field->addTypeError('string');
1102 5
            return Invalid::value();
1103
        }
1104
1105 62
        if (($minLength = $field->val('minLength', 0)) > 0 && mb_strlen($value) < $minLength) {
1106 4
            if (!empty($field->getName()) && $minLength === 1) {
1107 2
                $field->addError('missingField', ['messageCode' => '{field} is required.', 'status' => 422]);
1108
            } else {
1109 2
                $field->addError(
1110 2
                    'minLength',
1111
                    [
1112 2
                        'messageCode' => '{field} should be at least {minLength} {minLength,plural,character} long.',
1113 2
                        'minLength' => $minLength,
1114 2
                        'status' => 422
1115
                    ]
1116
                );
1117
            }
1118
        }
1119 62
        if (($maxLength = $field->val('maxLength', 0)) > 0 && mb_strlen($value) > $maxLength) {
1120 1
            $field->addError(
1121 1
                'maxLength',
1122
                [
1123 1
                    'messageCode' => '{field} is {overflow} {overflow,plural,characters} too long.',
1124 1
                    'maxLength' => $maxLength,
1125 1
                    'overflow' => mb_strlen($value) - $maxLength,
1126 1
                    'status' => 422
1127
                ]
1128
            );
1129
        }
1130 62
        if ($pattern = $field->val('pattern')) {
1131 4
            $regex = '`'.str_replace('`', preg_quote('`', '`'), $pattern).'`';
1132
1133 4
            if (!preg_match($regex, $value)) {
1134 2
                $field->addError(
1135 2
                    'invalid',
1136
                    [
1137 2
                        'messageCode' => '{field} is in the incorrect format.',
1138
                        'status' => 422
1139
                    ]
1140
                );
1141
            }
1142
        }
1143 62
        if ($format = $field->val('format')) {
1144 11
            $type = $format;
1145
            switch ($format) {
1146 11
                case 'date':
1147
                    $result = $this->validateDatetime($result, $field);
1148
                    if ($result instanceof \DateTimeInterface) {
1149
                        $result = $result->format("Y-m-d\T00:00:00P");
1150
                    }
1151
                    break;
1152 11
                case 'email':
1153 1
                    $result = filter_var($result, FILTER_VALIDATE_EMAIL);
1154 1
                    break;
1155 10
                case 'ipv4':
1156 1
                    $type = 'IPv4 address';
1157 1
                    $result = filter_var($result, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
1158 1
                    break;
1159 9
                case 'ipv6':
1160 1
                    $type = 'IPv6 address';
1161 1
                    $result = filter_var($result, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
1162 1
                    break;
1163 8
                case 'ip':
1164 1
                    $type = 'IP address';
1165 1
                    $result = filter_var($result, FILTER_VALIDATE_IP);
1166 1
                    break;
1167 7
                case 'uri':
1168 7
                    $type = 'URI';
1169 7
                    $result = filter_var($result, FILTER_VALIDATE_URL);
1170 7
                    break;
1171
                default:
1172
                    trigger_error("Unrecognized format '$format'.", E_USER_NOTICE);
1173
            }
1174 11
            if ($result === false) {
1175 5
                $field->addTypeError($type);
1176
            }
1177
        }
1178
1179 62
        if ($field->isValid()) {
1180 54
            return $result;
1181
        } else {
1182 12
            return Invalid::value();
1183
        }
1184
    }
1185
1186
    /**
1187
     * Validate a unix timestamp.
1188
     *
1189
     * @param mixed $value The value to validate.
1190
     * @param ValidationField $field The field being validated.
1191
     * @return int|Invalid Returns a valid timestamp or invalid if the value doesn't validate.
1192
     */
1193 8
    protected function validateTimestamp($value, ValidationField $field) {
1194 8
        if (is_numeric($value) && $value > 0) {
1195 3
            $result = (int)$value;
1196 5
        } elseif (is_string($value) && $ts = strtotime($value)) {
1197 1
            $result = $ts;
1198
        } else {
1199 4
            $field->addTypeError('timestamp');
1200 4
            $result = Invalid::value();
1201
        }
1202 8
        return $result;
1203
    }
1204
1205
    /**
1206
     * Validate a null value.
1207
     *
1208
     * @param mixed $value The value to validate.
1209
     * @param ValidationField $field The error collector for the field.
1210
     * @return null|Invalid Returns **null** or invalid.
1211
     */
1212
    protected function validateNull($value, ValidationField $field) {
1213
        if ($value === null) {
1214
            return null;
1215
        }
1216
        $field->addError('invalid', ['messageCode' => '{field} should be null.', 'status' => 422]);
1217
        return Invalid::value();
1218
    }
1219
1220
    /**
1221
     * Validate a value against an enum.
1222
     *
1223
     * @param mixed $value The value to test.
1224
     * @param ValidationField $field The validation object for adding errors.
1225
     * @return mixed|Invalid Returns the value if it is one of the enumerated values or invalid otherwise.
1226
     */
1227 185
    protected function validateEnum($value, ValidationField $field) {
1228 185
        $enum = $field->val('enum');
1229 185
        if (empty($enum)) {
1230 184
            return $value;
1231
        }
1232
1233 1
        if (!in_array($value, $enum, true)) {
1234 1
            $field->addError(
1235 1
                'invalid',
1236
                [
1237 1
                    'messageCode' => '{field} must be one of: {enum}.',
1238 1
                    'enum' => $enum,
1239 1
                    'status' => 422
1240
                ]
1241
            );
1242 1
            return Invalid::value();
1243
        }
1244 1
        return $value;
1245
    }
1246
1247
    /**
1248
     * Call all of the filters attached to a field.
1249
     *
1250
     * @param mixed $value The field value being filtered.
1251
     * @param ValidationField $field The validation object.
1252
     * @return mixed Returns the filtered value. If there are no filters for the field then the original value is returned.
1253
     */
1254 193
    protected function callFilters($value, ValidationField $field) {
1255
        // Strip array references in the name except for the last one.
1256 193
        $key = preg_replace(['`\[\d+\]$`', '`\[\d+\]`'], ['[]', ''], $field->getName());
1257 193
        if (!empty($this->filters[$key])) {
1258 1
            foreach ($this->filters[$key] as $filter) {
1259 1
                $value = call_user_func($filter, $value, $field);
1260
            }
1261
        }
1262 193
        return $value;
1263
    }
1264
1265
    /**
1266
     * Call all of the validators attached to a field.
1267
     *
1268
     * @param mixed $value The field value being validated.
1269
     * @param ValidationField $field The validation object to add errors.
1270
     */
1271 185
    protected function callValidators($value, ValidationField $field) {
1272 185
        $valid = true;
1273
1274
        // Strip array references in the name except for the last one.
1275 185
        $key = preg_replace(['`\[\d+\]$`', '`\[\d+\]`'], ['[]', ''], $field->getName());
1276 185
        if (!empty($this->validators[$key])) {
1277 4
            foreach ($this->validators[$key] as $validator) {
1278 4
                $r = call_user_func($validator, $value, $field);
1279
1280 4
                if ($r === false || Invalid::isInvalid($r)) {
1281 4
                    $valid = false;
1282
                }
1283
            }
1284
        }
1285
1286
        // Add an error on the field if the validator hasn't done so.
1287 185
        if (!$valid && $field->isValid()) {
1288
            $field->addError('invalid', ['messageCode' => '{field} is invalid.', 'status' => 422]);
1289
        }
1290 185
    }
1291
1292
    /**
1293
     * Specify data which should be serialized to JSON.
1294
     *
1295
     * This method specifically returns data compatible with the JSON schema format.
1296
     *
1297
     * @return mixed Returns data which can be serialized by **json_encode()**, which is a value of any type other than a resource.
1298
     * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
1299
     * @link http://json-schema.org/
1300
     */
1301
    public function jsonSerialize() {
1302 16
        $fix = function ($schema) use (&$fix) {
1303 16
            if ($schema instanceof Schema) {
1304 1
                return $schema->jsonSerialize();
1305
            }
1306
1307 16
            if (!empty($schema['type'])) {
1308 15
                $types = (array)$schema['type'];
1309
1310 15
                foreach ($types as $i => &$type) {
1311
                    // Swap datetime and timestamp to other types with formats.
1312 15
                    if ($type === 'datetime') {
1313 4
                        $type = 'string';
1314 4
                        $schema['format'] = 'date-time';
1315 14
                    } elseif ($schema['type'] === 'timestamp') {
1316 2
                        $type = 'integer';
1317 15
                        $schema['format'] = 'timestamp';
1318
                    }
1319
                }
1320 15
                $types = array_unique($types);
1321 15
                $schema['type'] = count($types) === 1 ? reset($types) : $types;
1322
            }
1323
1324 16
            if (!empty($schema['items'])) {
1325 4
                $schema['items'] = $fix($schema['items']);
1326
            }
1327 16
            if (!empty($schema['properties'])) {
1328 11
                $properties = [];
1329 11
                foreach ($schema['properties'] as $key => $property) {
1330 11
                    $properties[$key] = $fix($property);
1331
                }
1332 11
                $schema['properties'] = $properties;
1333
            }
1334
1335 16
            return $schema;
1336 16
        };
1337
1338 16
        $result = $fix($this->schema);
1339
1340 16
        return $result;
1341
    }
1342
1343
    /**
1344
     * Look up a type based on its alias.
1345
     *
1346
     * @param string $alias The type alias or type name to lookup.
1347
     * @return mixed
1348
     */
1349 163
    protected function getType($alias) {
1350 163
        if (isset(self::$types[$alias])) {
1351
            return $alias;
1352
        }
1353 163
        foreach (self::$types as $type => $aliases) {
1354 163
            if (in_array($alias, $aliases, true)) {
1355 163
                return $type;
1356
            }
1357
        }
1358 9
        return null;
1359
    }
1360
1361
    /**
1362
     * Get the class that's used to contain validation information.
1363
     *
1364
     * @return Validation|string Returns the validation class.
1365
     */
1366 193
    public function getValidationClass() {
1367 193
        return $this->validationClass;
1368
    }
1369
1370
    /**
1371
     * Set the class that's used to contain validation information.
1372
     *
1373
     * @param Validation|string $class Either the name of a class or a class that will be cloned.
1374
     * @return $this
1375
     */
1376 1
    public function setValidationClass($class) {
1377 1
        if (!is_a($class, Validation::class, true)) {
1378
            throw new \InvalidArgumentException("$class must be a subclass of ".Validation::class, 500);
1379
        }
1380
1381 1
        $this->validationClass = $class;
1382 1
        return $this;
1383
    }
1384
1385
    /**
1386
     * Create a new validation instance.
1387
     *
1388
     * @return Validation Returns a validation object.
1389
     */
1390 193
    protected function createValidation() {
1391 193
        $class = $this->getValidationClass();
1392
1393 193
        if ($class instanceof Validation) {
1394 1
            $result = clone $class;
1395
        } else {
1396 193
            $result = new $class;
1397
        }
1398 193
        return $result;
1399
    }
1400
1401
    /**
1402
     * Check whether or not a value is an array or accessible like an array.
1403
     *
1404
     * @param mixed $value The value to check.
1405
     * @return bool Returns **true** if the value can be used like an array or **false** otherwise.
1406
     */
1407 104
    private function isArray($value) {
1408 104
        return is_array($value) || ($value instanceof \ArrayAccess && $value instanceof \Traversable);
1409
    }
1410
1411
    /**
1412
     * Cast a value to an array.
1413
     *
1414
     * @param \Traversable $value The value to convert.
1415
     * @return array Returns an array.
1416
     */
1417 3
    private function toObjectArray(\Traversable $value) {
1418 3
        $class = get_class($value);
1419 3
        if ($value instanceof \ArrayObject) {
1420 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...
1421 1
        } elseif ($value instanceof \ArrayAccess) {
1422 1
            $r = new $class;
1423 1
            foreach ($value as $k => $v) {
1424 1
                $r[$k] = $v;
1425
            }
1426 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...
1427
        }
1428
        return iterator_to_array($value);
1429
    }
1430
1431
    /**
1432
     * Return a sparse version of this schema.
1433
     *
1434
     * A sparse schema has no required properties.
1435
     *
1436
     * @return Schema Returns a new sparse schema.
1437
     */
1438 2
    public function withSparse() {
1439 2
        $sparseSchema = $this->withSparseInternal($this, new \SplObjectStorage());
1440 2
        return $sparseSchema;
1441
    }
1442
1443
    /**
1444
     * The internal implementation of `Schema::withSparse()`.
1445
     *
1446
     * @param array|Schema $schema The schema to make sparse.
1447
     * @param \SplObjectStorage $schemas Collected sparse schemas that have already been made.
1448
     * @return mixed
1449
     */
1450 2
    private function withSparseInternal($schema, \SplObjectStorage $schemas) {
1451 2
        if ($schema instanceof Schema) {
1452 2
            if ($schemas->contains($schema)) {
1453 1
                return $schemas[$schema];
1454
            } else {
1455 2
                $schemas[$schema] = $sparseSchema = new Schema();
1456 2
                $sparseSchema->schema = $schema->withSparseInternal($schema->schema, $schemas);
1457 2
                if ($id = $sparseSchema->getID()) {
1458
                    $sparseSchema->setID($id.'Sparse');
1459
                }
1460
1461 2
                return $sparseSchema;
1462
            }
1463
        }
1464
1465 2
        unset($schema['required']);
1466
1467 2
        if (isset($schema['items'])) {
1468 1
            $schema['items'] = $this->withSparseInternal($schema['items'], $schemas);
1469
        }
1470 2
        if (isset($schema['properties'])) {
1471 2
            foreach ($schema['properties'] as $name => &$property) {
1472 2
                $property = $this->withSparseInternal($property, $schemas);
1473
            }
1474
        }
1475
1476 2
        return $schema;
1477
    }
1478
1479
    /**
1480
     * Filter a field's value using built in and custom filters.
1481
     *
1482
     * @param mixed $value The original value of the field.
1483
     * @param ValidationField $field The field information for the field.
1484
     * @return mixed Returns the filtered field or the original field value if there are no filters.
1485
     */
1486 193
    private function filterField($value, ValidationField $field) {
1487
        // Check for limited support for Open API style.
1488 193
        if (!empty($field->val('style')) && is_string($value)) {
1489 8
            $doFilter = true;
1490 8
            if ($field->hasType('boolean') && in_array($value, ['true', 'false', '0', '1'], true)) {
1491 4
                $doFilter = false;
1492 4
            } elseif ($field->hasType('integer') || $field->hasType('number') && is_numeric($value)) {
1493
                $doFilter = false;
1494
            }
1495
1496 8
            if ($doFilter) {
1497 4
                switch ($field->val('style')) {
1498 4
                    case 'form':
1499 2
                        $value = explode(',', $value);
1500 2
                        break;
1501 2
                    case 'spaceDelimited':
1502 1
                        $value = explode(' ', $value);
1503 1
                        break;
1504 1
                    case 'pipeDelimited':
1505 1
                        $value = explode('|', $value);
1506 1
                        break;
1507
                }
1508
            }
1509
        }
1510
1511 193
        $value = $this->callFilters($value, $field);
1512
1513 193
        return $value;
1514
    }
1515
1516
    /**
1517
     * Whether a offset exists.
1518
     *
1519
     * @param mixed $offset An offset to check for.
1520
     * @return boolean true on success or false on failure.
1521
     * @link http://php.net/manual/en/arrayaccess.offsetexists.php
1522
     */
1523 6
    public function offsetExists($offset) {
1524 6
        return isset($this->schema[$offset]);
1525
    }
1526
1527
    /**
1528
     * Offset to retrieve.
1529
     *
1530
     * @param mixed $offset The offset to retrieve.
1531
     * @return mixed Can return all value types.
1532
     * @link http://php.net/manual/en/arrayaccess.offsetget.php
1533
     */
1534 6
    public function offsetGet($offset) {
1535 6
        return isset($this->schema[$offset]) ? $this->schema[$offset] : null;
1536
    }
1537
1538
    /**
1539
     * Offset to set.
1540
     *
1541
     * @param mixed $offset The offset to assign the value to.
1542
     * @param mixed $value The value to set.
1543
     * @link http://php.net/manual/en/arrayaccess.offsetset.php
1544
     */
1545 1
    public function offsetSet($offset, $value) {
1546 1
        $this->schema[$offset] = $value;
1547 1
    }
1548
1549
    /**
1550
     * Offset to unset.
1551
     *
1552
     * @param mixed $offset The offset to unset.
1553
     * @link http://php.net/manual/en/arrayaccess.offsetunset.php
1554
     */
1555 1
    public function offsetUnset($offset) {
1556 1
        unset($this->schema[$offset]);
1557 1
    }
1558
1559
    /**
1560
     * Validate a field against a single type.
1561
     *
1562
     * @param mixed $value The value to validate.
1563
     * @param string $type The type to validate against.
1564
     * @param ValidationField $field Contains field and validation information.
1565
     * @return mixed Returns the valid value or `Invalid`.
1566
     */
1567 193
    protected function validateSingleType($value, $type, ValidationField $field) {
1568
        switch ($type) {
1569 193
            case 'boolean':
1570 32
                $result = $this->validateBoolean($value, $field);
1571 32
                break;
1572 173
            case 'integer':
1573 51
                $result = $this->validateInteger($value, $field);
1574 51
                break;
1575 158
            case 'number':
1576 17
                $result = $this->validateNumber($value, $field);
1577 17
                break;
1578 149
            case 'string':
1579 75
                $result = $this->validateString($value, $field);
1580 75
                break;
1581 125
            case 'timestamp':
1582 1
                trigger_error('The timestamp type is deprecated. Use an integer with a format of timestamp instead.', E_USER_DEPRECATED);
1583 1
                $result = $this->validateTimestamp($value, $field);
1584 1
                break;
1585 125
            case 'datetime':
1586 2
                trigger_error('The datetime type is deprecated. Use a string with a format of date-time instead.', E_USER_DEPRECATED);
1587 2
                $result = $this->validateDatetime($value, $field);
1588 2
                break;
1589 124
            case 'array':
1590 32
                $result = $this->validateArray($value, $field);
1591 32
                break;
1592 105
            case 'object':
1593 104
                $result = $this->validateObject($value, $field);
1594 102
                break;
1595 3
            case 'null':
1596
                $result = $this->validateNull($value, $field);
1597
                break;
1598 3
            case null:
1599
                // No type was specified so we are valid.
1600 3
                $result = $value;
1601 3
                break;
1602
            default:
1603
                throw new \InvalidArgumentException("Unrecognized type $type.", 500);
1604
        }
1605 193
        return $result;
1606
    }
1607
1608
    /**
1609
     * Validate a field against multiple basic types.
1610
     *
1611
     * The first validation that passes will be returned. If no type can be validated against then validation will fail.
1612
     *
1613
     * @param mixed $value The value to validate.
1614
     * @param string[] $types The types to validate against.
1615
     * @param ValidationField $field Contains field and validation information.
1616
     * @return mixed Returns the valid value or `Invalid`.
1617
     */
1618 29
    private function validateMultipleTypes($value, array $types, ValidationField $field) {
1619 29
        trigger_error('Multiple schema types are deprecated.', E_USER_DEPRECATED);
1620
1621
        // First check for an exact type match.
1622 29
        switch (gettype($value)) {
1623 29
            case 'boolean':
1624 4
                if (in_array('boolean', $types)) {
1625 4
                    $singleType = 'boolean';
1626
                }
1627 4
                break;
1628 26
            case 'integer':
1629 7
                if (in_array('integer', $types)) {
1630 5
                    $singleType = 'integer';
1631 2
                } elseif (in_array('number', $types)) {
1632 1
                    $singleType = 'number';
1633
                }
1634 7
                break;
1635 21
            case 'double':
1636 4
                if (in_array('number', $types)) {
1637 4
                    $singleType = 'number';
1638
                } elseif (in_array('integer', $types)) {
1639
                    $singleType = 'integer';
1640
                }
1641 4
                break;
1642 18
            case 'string':
1643 9
                if (in_array('datetime', $types) && preg_match(self::$DATE_REGEX, $value)) {
1644 1
                    $singleType = 'datetime';
1645 8
                } elseif (in_array('string', $types)) {
1646 4
                    $singleType = 'string';
1647
                }
1648 9
                break;
1649 10
            case 'array':
1650 10
                if (in_array('array', $types) && in_array('object', $types)) {
1651 1
                    $singleType = isset($value[0]) || empty($value) ? 'array' : 'object';
1652 9
                } elseif (in_array('object', $types)) {
1653
                    $singleType = 'object';
1654 9
                } elseif (in_array('array', $types)) {
1655 9
                    $singleType = 'array';
1656
                }
1657 10
                break;
1658 1
            case 'NULL':
1659
                if (in_array('null', $types)) {
1660
                    $singleType = $this->validateSingleType($value, 'null', $field);
1661
                }
1662
                break;
1663
        }
1664 29
        if (!empty($singleType)) {
1665 25
            return $this->validateSingleType($value, $singleType, $field);
1666
        }
1667
1668
        // Clone the validation field to collect errors.
1669 6
        $typeValidation = new ValidationField(new Validation(), $field->getField(), '', $field->getOptions());
1670
1671
        // Try and validate against each type.
1672 6
        foreach ($types as $type) {
1673 6
            $result = $this->validateSingleType($value, $type, $typeValidation);
1674 6
            if (Invalid::isValid($result)) {
1675 6
                return $result;
1676
            }
1677
        }
1678
1679
        // Since we got here the value is invalid.
1680
        $field->merge($typeValidation->getValidation());
1681
        return Invalid::value();
1682
    }
1683
1684
    /**
1685
     * Validate specific numeric validation properties.
1686
     *
1687
     * @param int|float $value The value to test.
1688
     * @param ValidationField $field Field information.
1689
     * @return int|float|Invalid Returns the number of invalid.
1690
     */
1691 51
    private function validateNumberProperties($value, ValidationField $field) {
1692 51
        $count = $field->getErrorCount();
1693
1694 51
        if ($multipleOf = $field->val('multipleOf')) {
1695 4
            $divided = $value / $multipleOf;
1696
1697 4
            if ($divided != round($divided)) {
1698 2
                $field->addError('multipleOf', ['messageCode' => '{field} is not a multiple of {multipleOf}.', 'status' => 422, 'multipleOf' => $multipleOf]);
1699
            }
1700
        }
1701
1702 51
        if ($maximum = $field->val('maximum')) {
1703 4
            $exclusive = $field->val('exclusiveMaximum');
1704
1705 4
            if ($value > $maximum || ($exclusive && $value == $maximum)) {
1706 2
                if ($exclusive) {
1707 1
                    $field->addError('maximum', ['messageCode' => '{field} is greater than or equal to {maximum}.', 'status' => 422, 'maximum' => $maximum]);
1708
                } else {
1709 1
                    $field->addError('maximum', ['messageCode' => '{field} is greater than {maximum}.', 'status' => 422, 'maximum' => $maximum]);
1710
                }
1711
1712
            }
1713
        }
1714
1715 51
        if ($minimum = $field->val('minimum')) {
1716 4
            $exclusive = $field->val('exclusiveMinimum');
1717
1718 4
            if ($value < $minimum || ($exclusive && $value == $minimum)) {
1719 2
                if ($exclusive) {
1720 1
                    $field->addError('minimum', ['messageCode' => '{field} is greater than or equal to {minimum}.', 'status' => 422, 'minimum' => $minimum]);
1721
                } else {
1722 1
                    $field->addError('minimum', ['messageCode' => '{field} is greater than {minimum}.', 'status' => 422, 'minimum' => $minimum]);
1723
                }
1724
1725
            }
1726
        }
1727
1728 51
        return $field->getErrorCount() === $count ? $value : Invalid::value();
1729
    }
1730
}
1731