Passed
Pull Request — master (#53)
by Todd
02:43
created

Schema::parseFieldSelector()   B

Complexity

Conditions 8
Paths 11

Size

Total Lines 28
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 8

Importance

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

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

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

805
            if ((null !== $minItems = $field->val('minItems')) && count(/** @scrutinizer ignore-type */ $value) < $minItems) {
Loading history...
806 1
                $field->addError(
807 1
                    'minItems',
808
                    [
809 1
                        'messageCode' => '{field} must contain at least {minItems} {minItems,plural,item}.',
810 1
                        'minItems' => $minItems,
811 1
                        'status' => 422
812
                    ]
813
                );
814
            }
815 27
            if ((null !== $maxItems = $field->val('maxItems')) && count($value) > $maxItems) {
816 1
                $field->addError(
817 1
                    'maxItems',
818
                    [
819 1
                        'messageCode' => '{field} must contain no more than {maxItems} {maxItems,plural,item}.',
820 1
                        'maxItems' => $maxItems,
821 1
                        'status' => 422
822
                    ]
823
                );
824
            }
825
826 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

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

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