Completed
Pull Request — master (#34)
by Todd
01:57
created

Schema::setFlags()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

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

347
        $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...
348 176
        $schema->schema = $schema->parseInternal($arr);
349 176
        return $schema;
350
    }
351
352
    /**
353
     * Parse a schema in short form into a full schema array.
354
     *
355
     * @param array $arr The array to parse into a schema.
356
     * @return array The full schema array.
357
     * @throws \InvalidArgumentException Throws an exception when an item in the schema is invalid.
358
     */
359 176
    protected function parseInternal(array $arr) {
360 176
        if (empty($arr)) {
361
            // An empty schema validates to anything.
362 6
            return [];
363 171
        } elseif (isset($arr['type'])) {
364
            // This is a long form schema and can be parsed as the root.
365
            return $this->parseNode($arr);
366
        } else {
367
            // Check for a root schema.
368 171
            $value = reset($arr);
369 171
            $key = key($arr);
370 171
            if (is_int($key)) {
371 107
                $key = $value;
372 107
                $value = null;
373
            }
374 171
            list ($name, $param) = $this->parseShortParam($key, $value);
375 171
            if (empty($name)) {
376 64
                return $this->parseNode($param, $value);
377
            }
378
        }
379
380
        // If we are here then this is n object schema.
381 110
        list($properties, $required) = $this->parseProperties($arr);
382
383
        $result = [
384 110
            'type' => 'object',
385 110
            'properties' => $properties,
386 110
            'required' => $required
387
        ];
388
389 110
        return array_filter($result);
390
    }
391
392
    /**
393
     * Parse a schema node.
394
     *
395
     * @param array $node The node to parse.
396
     * @param mixed $value Additional information from the node.
397
     * @return array Returns a JSON schema compatible node.
398
     */
399 171
    private function parseNode($node, $value = null) {
400 171
        if (is_array($value)) {
401
            // The value describes a bit more about the schema.
402 59
            switch ($node['type']) {
403 59
                case 'array':
404 11
                    if (isset($value['items'])) {
405
                        // The value includes array schema information.
406 4
                        $node = array_replace($node, $value);
407
                    } else {
408 7
                        $node['items'] = $this->parseInternal($value);
409
                    }
410 11
                    break;
411 49
                case 'object':
412
                    // The value is a schema of the object.
413 12
                    if (isset($value['properties'])) {
414
                        list($node['properties']) = $this->parseProperties($value['properties']);
415
                    } else {
416 12
                        list($node['properties'], $required) = $this->parseProperties($value);
417 12
                        if (!empty($required)) {
418 12
                            $node['required'] = $required;
419
                        }
420
                    }
421 12
                    break;
422
                default:
423 37
                    $node = array_replace($node, $value);
424 59
                    break;
425
            }
426 132
        } elseif (is_string($value)) {
427 104
            if ($node['type'] === 'array' && $arrType = $this->getType($value)) {
428 6
                $node['items'] = ['type' => $arrType];
429 100
            } elseif (!empty($value)) {
430 104
                $node['description'] = $value;
431
            }
432 33
        } elseif ($value === null) {
433
            // Parse child elements.
434 29
            if ($node['type'] === 'array' && isset($node['items'])) {
435
                // The value includes array schema information.
436
                $node['items'] = $this->parseInternal($node['items']);
437 29
            } elseif ($node['type'] === 'object' && isset($node['properties'])) {
438
                list($node['properties']) = $this->parseProperties($node['properties']);
439
440
            }
441
        }
442
443 171
        if (is_array($node)) {
444 170
            if (!empty($node['allowNull'])) {
445 1
                $node['type'] = array_merge((array)$node['type'], ['null']);
446
            }
447 170
            unset($node['allowNull']);
448
449 170
            if ($node['type'] === null || $node['type'] === []) {
450 4
                unset($node['type']);
451
            }
452
        }
453
454 171
        return $node;
455
    }
456
457
    /**
458
     * Parse the schema for an object's properties.
459
     *
460
     * @param array $arr An object property schema.
461
     * @return array Returns a schema array suitable to be placed in the **properties** key of a schema.
462
     */
463 110
    private function parseProperties(array $arr) {
464 110
        $properties = [];
465 110
        $requiredProperties = [];
466 110
        foreach ($arr as $key => $value) {
467
            // Fix a schema specified as just a value.
468 110
            if (is_int($key)) {
469 83
                if (is_string($value)) {
470 83
                    $key = $value;
471 83
                    $value = '';
472
                } else {
473
                    throw new \InvalidArgumentException("Schema at position $key is not a valid parameter.", 500);
474
                }
475
            }
476
477
            // The parameter is defined in the key.
478 110
            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

478
            list($name, $param, $required) = $this->parseShortParam($key, /** @scrutinizer ignore-type */ $value);
Loading history...
479
480 110
            $node = $this->parseNode($param, $value);
481
482 110
            $properties[$name] = $node;
483 110
            if ($required) {
484 110
                $requiredProperties[] = $name;
485
            }
486
        }
487 110
        return array($properties, $requiredProperties);
488
    }
489
490
    /**
491
     * Parse a short parameter string into a full array parameter.
492
     *
493
     * @param string $key The short parameter string to parse.
494
     * @param array $value An array of other information that might help resolve ambiguity.
495
     * @return array Returns an array in the form `[string name, array param, bool required]`.
496
     * @throws \InvalidArgumentException Throws an exception if the short param is not in the correct format.
497
     */
498 171
    public function parseShortParam($key, $value = []) {
499
        // Is the parameter optional?
500 171
        if (substr($key, -1) === '?') {
501 72
            $required = false;
502 72
            $key = substr($key, 0, -1);
503
        } else {
504 122
            $required = true;
505
        }
506
507
        // Check for a type.
508 171
        $parts = explode(':', $key);
509 171
        $name = $parts[0];
510 171
        $types = [];
511
512 171
        if (!empty($parts[1])) {
513 166
            $shortTypes = explode('|', $parts[1]);
514 166
            foreach ($shortTypes as $alias) {
515 166
                $found = $this->getType($alias);
516 166
                if ($found === null) {
517
                    throw new \InvalidArgumentException("Unknown type '$alias'", 500);
518
                } else {
519 166
                    $types[] = $found;
520
                }
521
            }
522
        }
523
524 171
        if ($value instanceof Schema) {
0 ignored issues
show
introduced by
$value is never a sub-type of Garden\Schema\Schema.
Loading history...
525 5
            if (count($types) === 1 && $types[0] === 'array') {
526 1
                $param = ['type' => $types[0], 'items' => $value];
527
            } else {
528 5
                $param = $value;
529
            }
530 170
        } elseif (isset($value['type'])) {
531 3
            $param = $value;
532
533 3
            if (!empty($types) && $types !== (array)$param['type']) {
534
                $typesStr = implode('|', $types);
535
                $paramTypesStr = implode('|', (array)$param['type']);
536
537 3
                throw new \InvalidArgumentException("Type mismatch between $typesStr and {$paramTypesStr} for field $name.", 500);
538
            }
539
        } else {
540 167
            if (empty($types) && !empty($parts[1])) {
541
                throw new \InvalidArgumentException("Invalid type {$parts[1]} for field $name.", 500);
542
            }
543 167
            if (empty($types)) {
544 4
                $param = ['type' => null];
545
            } else {
546 166
                $param = ['type' => count($types) === 1 ? $types[0] : $types];
547
            }
548
549
            // Parsed required strings have a minimum length of 1.
550 167
            if (in_array('string', $types) && !empty($name) && $required && (!isset($value['default']) || $value['default'] !== '')) {
551 39
                $param['minLength'] = 1;
552
            }
553
        }
554
555 171
        return [$name, $param, $required];
556
    }
557
558
    /**
559
     * Add a custom filter to change data before validation.
560
     *
561
     * @param string $fieldname The name of the field to filter, if any.
562
     *
563
     * If you are adding a filter to a deeply nested field then separate the path with dots.
564
     * @param callable $callback The callback to filter the field.
565
     * @return $this
566
     */
567 1
    public function addFilter($fieldname, callable $callback) {
568 1
        $this->filters[$fieldname][] = $callback;
569 1
        return $this;
570
    }
571
572
    /**
573
     * Add a custom validator to to validate the schema.
574
     *
575
     * @param string $fieldname The name of the field to validate, if any.
576
     *
577
     * If you are adding a validator to a deeply nested field then separate the path with dots.
578
     * @param callable $callback The callback to validate with.
579
     * @return Schema Returns `$this` for fluent calls.
580
     */
581 4
    public function addValidator($fieldname, callable $callback) {
582 4
        $this->validators[$fieldname][] = $callback;
583 4
        return $this;
584
    }
585
586
    /**
587
     * Require one of a given set of fields in the schema.
588
     *
589
     * @param array $required The field names to require.
590
     * @param string $fieldname The name of the field to attach to.
591
     * @param int $count The count of required items.
592
     * @return Schema Returns `$this` for fluent calls.
593
     */
594 3
    public function requireOneOf(array $required, $fieldname = '', $count = 1) {
595 3
        $result = $this->addValidator(
596 3
            $fieldname,
597 3
            function ($data, ValidationField $field) use ($required, $count) {
598
                // This validator does not apply to sparse validation.
599 3
                if ($field->isSparse()) {
600 1
                    return true;
601
                }
602
603 2
                $hasCount = 0;
604 2
                $flattened = [];
605
606 2
                foreach ($required as $name) {
607 2
                    $flattened = array_merge($flattened, (array)$name);
608
609 2
                    if (is_array($name)) {
610
                        // This is an array of required names. They all must match.
611 1
                        $hasCountInner = 0;
612 1
                        foreach ($name as $nameInner) {
613 1
                            if (array_key_exists($nameInner, $data)) {
614 1
                                $hasCountInner++;
615
                            } else {
616 1
                                break;
617
                            }
618
                        }
619 1
                        if ($hasCountInner >= count($name)) {
620 1
                            $hasCount++;
621
                        }
622 2
                    } elseif (array_key_exists($name, $data)) {
623 1
                        $hasCount++;
624
                    }
625
626 2
                    if ($hasCount >= $count) {
627 2
                        return true;
628
                    }
629
                }
630
631 2
                if ($count === 1) {
632 1
                    $message = 'One of {required} are required.';
633
                } else {
634 1
                    $message = '{count} of {required} are required.';
635
                }
636
637 2
                $field->addError('missingField', [
638 2
                    'messageCode' => $message,
639 2
                    'required' => $required,
640 2
                    'count' => $count
641
                ]);
642 2
                return false;
643 3
            }
644
        );
645
646 3
        return $result;
647
    }
648
649
    /**
650
     * Validate data against the schema.
651
     *
652
     * @param mixed $data The data to validate.
653
     * @param bool $sparse Whether or not this is a sparse validation.
654
     * @return mixed Returns a cleaned version of the data.
655
     * @throws ValidationException Throws an exception when the data does not validate against the schema.
656
     */
657 176
    public function validate($data, $sparse = false) {
658 176
        $field = new ValidationField($this->createValidation(), $this->schema, '', $sparse);
659
660 176
        $clean = $this->validateField($data, $field, $sparse);
661
662 174
        if (Invalid::isInvalid($clean) && $field->isValid()) {
663
            // This really shouldn't happen, but we want to protect against seeing the invalid object.
664
            $field->addError('invalid', ['messageCode' => '{field} is invalid.', 'status' => 422]);
665
        }
666
667 174
        if (!$field->getValidation()->isValid()) {
668 61
            throw new ValidationException($field->getValidation());
669
        }
670
671 127
        return $clean;
672
    }
673
674
    /**
675
     * Validate data against the schema and return the result.
676
     *
677
     * @param mixed $data The data to validate.
678
     * @param bool $sparse Whether or not to do a sparse validation.
679
     * @return bool Returns true if the data is valid. False otherwise.
680
     */
681 37
    public function isValid($data, $sparse = false) {
682
        try {
683 37
            $this->validate($data, $sparse);
684 26
            return true;
685 19
        } catch (ValidationException $ex) {
686 19
            return false;
687
        }
688
    }
689
690
    /**
691
     * Validate a field.
692
     *
693
     * @param mixed $value The value to validate.
694
     * @param ValidationField $field A validation object to add errors to.
695
     * @param bool $sparse Whether or not this is a sparse validation.
696
     * @return mixed|Invalid Returns a clean version of the value with all extra fields stripped out or invalid if the value
697
     * is completely invalid.
698
     */
699 176
    protected function validateField($value, ValidationField $field, $sparse = false) {
700 176
        $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...
701
702 176
        if ($field->getField() instanceof Schema) {
703
            try {
704 5
                $result = $field->getField()->validate($value, $sparse);
705 2
            } catch (ValidationException $ex) {
706
                // The validation failed, so merge the validations together.
707 5
                $field->getValidation()->merge($ex->getValidation(), $field->getName());
708
            }
709 176
        } elseif (($value === null || ($value === '' && !$field->hasType('string'))) && $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...
710 15
            $result = null;
711
        } else {
712
            // Validate the field's type.
713 175
            $type = $field->getType();
714 175
            if (is_array($type)) {
715 39
                $result = $this->validateMultipleTypes($value, $type, $field, $sparse);
716
            } else {
717 144
                $result = $this->validateSingleType($value, $type, $field, $sparse);
718
            }
719 175
            if (Invalid::isValid($result)) {
720 173
                $result = $this->validateEnum($result, $field);
721
            }
722
        }
723
724
        // Validate a custom field validator.
725 176
        if (Invalid::isValid($result)) {
726 174
            $this->callValidators($result, $field);
727
        }
728
729 176
        return $result;
730
    }
731
732
    /**
733
     * Validate an array.
734
     *
735
     * @param mixed $value The value to validate.
736
     * @param ValidationField $field The validation results to add.
737
     * @param bool $sparse Whether or not this is a sparse validation.
738
     * @return array|Invalid Returns an array or invalid if validation fails.
739
     */
740 29
    protected function validateArray($value, ValidationField $field, $sparse = false) {
741 29
        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...
742 6
            $field->addTypeError('array');
743 6
            return Invalid::value();
744
        } else {
745 24
            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

745
            if ((null !== $minItems = $field->val('minItems')) && count(/** @scrutinizer ignore-type */ $value) < $minItems) {
Loading history...
746 1
                $field->addError(
747 1
                    'minItems',
748
                    [
749 1
                        'messageCode' => '{field} must contain at least {minItems} {minItems,plural,item}.',
750 1
                        'minItems' => $minItems,
751 1
                        'status' => 422
752
                    ]
753
                );
754
            }
755 24
            if ((null !== $maxItems = $field->val('maxItems')) && count($value) > $maxItems) {
756 1
                $field->addError(
757 1
                    'maxItems',
758
                    [
759 1
                        'messageCode' => '{field} must contain no more than {maxItems} {maxItems,plural,item}.',
760 1
                        'maxItems' => $maxItems,
761 1
                        'status' => 422
762
                    ]
763
                );
764
            }
765
766 24
            if ($field->val('items') !== null) {
767 19
                $result = [];
768
769
                // Validate each of the types.
770 19
                $itemValidation = new ValidationField(
771 19
                    $field->getValidation(),
772 19
                    $field->val('items'),
773 19
                    '',
774 19
                    $sparse
775
                );
776
777 19
                $count = 0;
778 19
                foreach ($value as $i => $item) {
779 19
                    $itemValidation->setName($field->getName()."[{$i}]");
780 19
                    $validItem = $this->validateField($item, $itemValidation, $sparse);
781 19
                    if (Invalid::isValid($validItem)) {
782 19
                        $result[] = $validItem;
783
                    }
784 19
                    $count++;
785
                }
786
787 19
                return empty($result) && $count > 0 ? Invalid::value() : $result;
788
            } else {
789
                // Cast the items into a proper numeric array.
790 5
                $result = is_array($value) ? array_values($value) : iterator_to_array($value);
791 5
                return $result;
792
            }
793
        }
794
    }
795
796
    /**
797
     * Validate a boolean value.
798
     *
799
     * @param mixed $value The value to validate.
800
     * @param ValidationField $field The validation results to add.
801
     * @return bool|Invalid Returns the cleaned value or invalid if validation fails.
802
     */
803 30
    protected function validateBoolean($value, ValidationField $field) {
804 30
        $value = $value === null ? $value : filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
805 30
        if ($value === null) {
806 4
            $field->addTypeError('boolean');
807 4
            return Invalid::value();
808
        }
809
810 27
        return $value;
811
    }
812
813
    /**
814
     * Validate a date time.
815
     *
816
     * @param mixed $value The value to validate.
817
     * @param ValidationField $field The validation results to add.
818
     * @return \DateTimeInterface|Invalid Returns the cleaned value or **null** if it isn't valid.
819
     */
820 14
    protected function validateDatetime($value, ValidationField $field) {
821 14
        if ($value instanceof \DateTimeInterface) {
822
            // do nothing, we're good
823 11
        } elseif (is_string($value) && $value !== '' && !is_numeric($value)) {
824
            try {
825 7
                $dt = new \DateTimeImmutable($value);
826 6
                if ($dt) {
0 ignored issues
show
introduced by
$dt is of type DateTimeImmutable, thus it always evaluated to true.
Loading history...
827 6
                    $value = $dt;
828
                } else {
829 6
                    $value = null;
830
                }
831 1
            } catch (\Throwable $ex) {
832 7
                $value = Invalid::value();
833
            }
834 4
        } elseif (is_int($value) && $value > 0) {
835
            try {
836 1
                $value = new \DateTimeImmutable('@'.(string)round($value));
837
            } catch (\Throwable $ex) {
838 1
                $value = Invalid::value();
839
            }
840
        } else {
841 3
            $value = Invalid::value();
842
        }
843
844 14
        if (Invalid::isInvalid($value)) {
845 4
            $field->addTypeError('datetime');
846
        }
847 14
        return $value;
848
    }
849
850
    /**
851
     * Validate a float.
852
     *
853
     * @param mixed $value The value to validate.
854
     * @param ValidationField $field The validation results to add.
855
     * @return float|Invalid Returns a number or **null** if validation fails.
856
     */
857 13
    protected function validateNumber($value, ValidationField $field) {
858 13
        $result = filter_var($value, FILTER_VALIDATE_FLOAT);
859 13
        if ($result === false) {
860 4
            $field->addTypeError('number');
861 4
            return Invalid::value();
862
        }
863 9
        return $result;
864
    }
865
    /**
866
     * Validate and integer.
867
     *
868
     * @param mixed $value The value to validate.
869
     * @param ValidationField $field The validation results to add.
870
     * @return int|Invalid Returns the cleaned value or **null** if validation fails.
871
     */
872 38
    protected function validateInteger($value, ValidationField $field) {
873 38
        $result = filter_var($value, FILTER_VALIDATE_INT);
874
875 38
        if ($result === false) {
876 9
            $field->addTypeError('integer');
877 9
            return Invalid::value();
878
        }
879 33
        return $result;
880
    }
881
882
    /**
883
     * Validate an object.
884
     *
885
     * @param mixed $value The value to validate.
886
     * @param ValidationField $field The validation results to add.
887
     * @param bool $sparse Whether or not this is a sparse validation.
888
     * @return object|Invalid Returns a clean object or **null** if validation fails.
889
     */
890 101
    protected function validateObject($value, ValidationField $field, $sparse = false) {
891 101
        if (!$this->isArray($value) || isset($value[0])) {
892 6
            $field->addTypeError('object');
893 6
            return Invalid::value();
894 101
        } elseif (is_array($field->val('properties'))) {
895
            // Validate the data against the internal schema.
896 96
            $value = $this->validateProperties($value, $field, $sparse);
897 5
        } elseif (!is_array($value)) {
898 3
            $value = $this->toObjectArray($value);
899
        }
900 99
        return $value;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $value also could return the type array which is incompatible with the documented return type object|Garden\Schema\Invalid.
Loading history...
901
    }
902
903
    /**
904
     * Validate data against the schema and return the result.
905
     *
906
     * @param array|\Traversable&\ArrayAccess $data The data to validate.
907
     * @param ValidationField $field This argument will be filled with the validation result.
908
     * @param bool $sparse Whether or not this is a sparse validation.
909
     * @return array|Invalid Returns a clean array with only the appropriate properties and the data coerced to proper types.
910
     * or invalid if there are no valid properties.
911
     */
912 96
    protected function validateProperties($data, ValidationField $field, $sparse = false) {
913 96
        $properties = $field->val('properties', []);
914 96
        $required = array_flip($field->val('required', []));
915
916 96
        if (is_array($data)) {
0 ignored issues
show
introduced by
The condition is_array($data) is always false.
Loading history...
917 92
            $keys = array_keys($data);
918 92
            $clean = [];
919
        } else {
920 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

920
            $keys = array_keys(iterator_to_array(/** @scrutinizer ignore-type */ $data));
Loading history...
921 4
            $class = get_class($data);
922 4
            $clean = new $class;
923
924 4
            if ($clean instanceof \ArrayObject && $data instanceof \ArrayObject) {
925 3
                $clean->setFlags($data->getFlags());
926 3
                $clean->setIteratorClass($data->getIteratorClass());
927
            }
928
        }
929 96
        $keys = array_combine(array_map('strtolower', $keys), $keys);
930
931 96
        $propertyField = new ValidationField($field->getValidation(), [], null, $sparse);
932
933
        // Loop through the schema fields and validate each one.
934 96
        foreach ($properties as $propertyName => $property) {
935
            $propertyField
936 96
                ->setField($property)
937 96
                ->setName(ltrim($field->getName().".$propertyName", '.'));
938
939 96
            $lName = strtolower($propertyName);
940 96
            $isRequired = isset($required[$propertyName]);
941
942
            // First check for required fields.
943 96
            if (!array_key_exists($lName, $keys)) {
944 28
                if ($sparse) {
945
                    // Sparse validation can leave required fields out.
946 27
                } elseif ($propertyField->hasVal('default')) {
947 2
                    $clean[$propertyName] = $propertyField->val('default');
948 25
                } elseif ($isRequired) {
949 28
                    $propertyField->addError('missingField', ['messageCode' => '{field} is required.']);
950
                }
951
            } else {
952 92
                $value = $data[$keys[$lName]];
953
954 92
                if (in_array($value, [null, ''], true) && !$isRequired && !$propertyField->hasType('null')) {
955 13
                    if ($propertyField->getType() !== 'string' || $value === null) {
956 10
                        continue;
957
                    }
958
                }
959
960 82
                $clean[$propertyName] = $this->validateField($value, $propertyField, $sparse);
961
            }
962
963 94
            unset($keys[$lName]);
964
        }
965
966
        // Look for extraneous properties.
967 96
        if (!empty($keys)) {
968 19
            if ($this->hasFlag(Schema::VALIDATE_EXTRA_PROPERTY_NOTICE)) {
969 2
                $msg = sprintf("%s has unexpected field(s): %s.", $field->getName() ?: 'value', implode(', ', $keys));
970 2
                trigger_error($msg, E_USER_NOTICE);
971
            }
972
973 17
            if ($this->hasFlag(Schema::VALIDATE_EXTRA_PROPERTY_EXCEPTION)) {
974 2
                $field->addError('invalid', [
975 2
                    'messageCode' => '{field} has {extra,plural,an unexpected field,unexpected fields}: {extra}.',
976 2
                    'extra' => array_values($keys),
977 2
                    'status' => 422
978
                ]);
979
            }
980
        }
981
982 94
        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...
983
    }
984
985
    /**
986
     * Validate a string.
987
     *
988
     * @param mixed $value The value to validate.
989
     * @param ValidationField $field The validation results to add.
990
     * @return string|Invalid Returns the valid string or **null** if validation fails.
991
     */
992 66
    protected function validateString($value, ValidationField $field) {
993 66
        if (is_string($value) || is_numeric($value)) {
994 64
            $value = $result = (string)$value;
995
        } else {
996 5
            $field->addTypeError('string');
997 5
            return Invalid::value();
998
        }
999
1000 64
        if (($minLength = $field->val('minLength', 0)) > 0 && mb_strlen($value) < $minLength) {
1001 4
            if (!empty($field->getName()) && $minLength === 1) {
1002 2
                $field->addError('missingField', ['messageCode' => '{field} is required.', 'status' => 422]);
1003
            } else {
1004 2
                $field->addError(
1005 2
                    'minLength',
1006
                    [
1007 2
                        'messageCode' => '{field} should be at least {minLength} {minLength,plural,character} long.',
1008 2
                        'minLength' => $minLength,
1009 2
                        'status' => 422
1010
                    ]
1011
                );
1012
            }
1013
        }
1014 64
        if (($maxLength = $field->val('maxLength', 0)) > 0 && mb_strlen($value) > $maxLength) {
1015 1
            $field->addError(
1016 1
                'maxLength',
1017
                [
1018 1
                    'messageCode' => '{field} is {overflow} {overflow,plural,characters} too long.',
1019 1
                    'maxLength' => $maxLength,
1020 1
                    'overflow' => mb_strlen($value) - $maxLength,
1021 1
                    'status' => 422
1022
                ]
1023
            );
1024
        }
1025 64
        if ($pattern = $field->val('pattern')) {
1026 4
            $regex = '`'.str_replace('`', preg_quote('`', '`'), $pattern).'`';
1027
1028 4
            if (!preg_match($regex, $value)) {
1029 2
                $field->addError(
1030 2
                    'invalid',
1031
                    [
1032 2
                        'messageCode' => '{field} is in the incorrect format.',
1033
                        'status' => 422
1034
                    ]
1035
                );
1036
            }
1037
        }
1038 64
        if ($format = $field->val('format')) {
1039 15
            $type = $format;
1040
            switch ($format) {
1041 15
                case 'date-time':
1042 4
                    $result = $this->validateDatetime($result, $field);
1043 4
                    if ($result instanceof \DateTimeInterface) {
1044 4
                        $result = $result->format(\DateTime::RFC3339);
1045
                    }
1046 4
                    break;
1047 11
                case 'email':
1048 1
                    $result = filter_var($result, FILTER_VALIDATE_EMAIL);
1049 1
                    break;
1050 10
                case 'ipv4':
1051 1
                    $type = 'IPv4 address';
1052 1
                    $result = filter_var($result, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
1053 1
                    break;
1054 9
                case 'ipv6':
1055 1
                    $type = 'IPv6 address';
1056 1
                    $result = filter_var($result, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
1057 1
                    break;
1058 8
                case 'ip':
1059 1
                    $type = 'IP address';
1060 1
                    $result = filter_var($result, FILTER_VALIDATE_IP);
1061 1
                    break;
1062 7
                case 'uri':
1063 7
                    $type = 'URI';
1064 7
                    $result = filter_var($result, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED | FILTER_FLAG_SCHEME_REQUIRED);
1065 7
                    break;
1066
                default:
1067
                    trigger_error("Unrecognized format '$format'.", E_USER_NOTICE);
1068
            }
1069 15
            if ($result === false) {
1070 5
                $field->addTypeError($type);
1071
            }
1072
        }
1073
1074 64
        if ($field->isValid()) {
1075 56
            return $result;
1076
        } else {
1077 12
            return Invalid::value();
1078
        }
1079
    }
1080
1081
    /**
1082
     * Validate a unix timestamp.
1083
     *
1084
     * @param mixed $value The value to validate.
1085
     * @param ValidationField $field The field being validated.
1086
     * @return int|Invalid Returns a valid timestamp or invalid if the value doesn't validate.
1087
     */
1088 8
    protected function validateTimestamp($value, ValidationField $field) {
1089 8
        if (is_numeric($value) && $value > 0) {
1090 3
            $result = (int)$value;
1091 5
        } elseif (is_string($value) && $ts = strtotime($value)) {
1092 1
            $result = $ts;
1093
        } else {
1094 4
            $field->addTypeError('timestamp');
1095 4
            $result = Invalid::value();
1096
        }
1097 8
        return $result;
1098
    }
1099
1100
    /**
1101
     * Validate a null value.
1102
     *
1103
     * @param mixed $value The value to validate.
1104
     * @param ValidationField $field The error collector for the field.
1105
     * @return null|Invalid Returns **null** or invalid.
1106
     */
1107 1
    protected function validateNull($value, ValidationField $field) {
1108 1
        if ($value === null) {
1109
            return null;
1110
        }
1111 1
        $field->addError('invalid', ['messageCode' => '{field} should be null.', 'status' => 422]);
1112 1
        return Invalid::value();
1113
    }
1114
1115
    /**
1116
     * Validate a value against an enum.
1117
     *
1118
     * @param mixed $value The value to test.
1119
     * @param ValidationField $field The validation object for adding errors.
1120
     * @return mixed|Invalid Returns the value if it is one of the enumerated values or invalid otherwise.
1121
     */
1122 173
    protected function validateEnum($value, ValidationField $field) {
1123 173
        $enum = $field->val('enum');
1124 173
        if (empty($enum)) {
1125 172
            return $value;
1126
        }
1127
1128 1
        if (!in_array($value, $enum, true)) {
1129 1
            $field->addError(
1130 1
                'invalid',
1131
                [
1132 1
                    'messageCode' => '{field} must be one of: {enum}.',
1133 1
                    'enum' => $enum,
1134 1
                    'status' => 422
1135
                ]
1136
            );
1137 1
            return Invalid::value();
1138
        }
1139 1
        return $value;
1140
    }
1141
1142
    /**
1143
     * Call all of the filters attached to a field.
1144
     *
1145
     * @param mixed $value The field value being filtered.
1146
     * @param ValidationField $field The validation object.
1147
     * @return mixed Returns the filtered value. If there are no filters for the field then the original value is returned.
1148
     */
1149 176
    protected function callFilters($value, ValidationField $field) {
1150
        // Strip array references in the name except for the last one.
1151 176
        $key = preg_replace(['`\[\d+\]$`', '`\[\d+\]`'], ['[]', ''], $field->getName());
1152 176
        if (!empty($this->filters[$key])) {
1153 1
            foreach ($this->filters[$key] as $filter) {
1154 1
                $value = call_user_func($filter, $value, $field);
1155
            }
1156
        }
1157 176
        return $value;
1158
    }
1159
1160
    /**
1161
     * Call all of the validators attached to a field.
1162
     *
1163
     * @param mixed $value The field value being validated.
1164
     * @param ValidationField $field The validation object to add errors.
1165
     */
1166 174
    protected function callValidators($value, ValidationField $field) {
1167 174
        $valid = true;
1168
1169
        // Strip array references in the name except for the last one.
1170 174
        $key = preg_replace(['`\[\d+\]$`', '`\[\d+\]`'], ['[]', ''], $field->getName());
1171 174
        if (!empty($this->validators[$key])) {
1172 4
            foreach ($this->validators[$key] as $validator) {
1173 4
                $r = call_user_func($validator, $value, $field);
1174
1175 4
                if ($r === false || Invalid::isInvalid($r)) {
1176 4
                    $valid = false;
1177
                }
1178
            }
1179
        }
1180
1181
        // Add an error on the field if the validator hasn't done so.
1182 174
        if (!$valid && $field->isValid()) {
1183
            $field->addError('invalid', ['messageCode' => '{field} is invalid.', 'status' => 422]);
1184
        }
1185 174
    }
1186
1187
    /**
1188
     * Specify data which should be serialized to JSON.
1189
     *
1190
     * This method specifically returns data compatible with the JSON schema format.
1191
     *
1192
     * @return mixed Returns data which can be serialized by **json_encode()**, which is a value of any type other than a resource.
1193
     * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
1194
     * @link http://json-schema.org/
1195
     */
1196
    public function jsonSerialize() {
1197 16
        $fix = function ($schema) use (&$fix) {
1198 16
            if ($schema instanceof Schema) {
1199 1
                return $schema->jsonSerialize();
1200
            }
1201
1202 16
            if (!empty($schema['type'])) {
1203 15
                $types = (array)$schema['type'];
1204
1205 15
                foreach ($types as $i => &$type) {
1206
                    // Swap datetime and timestamp to other types with formats.
1207 15
                    if ($type === 'datetime') {
1208 5
                        $type = 'string';
1209 5
                        $schema['format'] = 'date-time';
1210 14
                    } elseif ($schema['type'] === 'timestamp') {
1211 3
                        $type = 'integer';
1212 15
                        $schema['format'] = 'timestamp';
1213
                    }
1214
                }
1215 15
                $types = array_unique($types);
1216 15
                $schema['type'] = count($types) === 1 ? reset($types) : $types;
1217
            }
1218
1219 16
            if (!empty($schema['items'])) {
1220 4
                $schema['items'] = $fix($schema['items']);
1221
            }
1222 16
            if (!empty($schema['properties'])) {
1223 11
                $properties = [];
1224 11
                foreach ($schema['properties'] as $key => $property) {
1225 11
                    $properties[$key] = $fix($property);
1226
                }
1227 11
                $schema['properties'] = $properties;
1228
            }
1229
1230 16
            return $schema;
1231 16
        };
1232
1233 16
        $result = $fix($this->schema);
1234
1235 16
        return $result;
1236
    }
1237
1238
    /**
1239
     * Look up a type based on its alias.
1240
     *
1241
     * @param string $alias The type alias or type name to lookup.
1242
     * @return mixed
1243
     */
1244 166
    protected function getType($alias) {
1245 166
        if (isset(self::$types[$alias])) {
1246
            return $alias;
1247
        }
1248 166
        foreach (self::$types as $type => $aliases) {
1249 166
            if (in_array($alias, $aliases, true)) {
1250 166
                return $type;
1251
            }
1252
        }
1253 9
        return null;
1254
    }
1255
1256
    /**
1257
     * Get the class that's used to contain validation information.
1258
     *
1259
     * @return Validation|string Returns the validation class.
1260
     */
1261 176
    public function getValidationClass() {
1262 176
        return $this->validationClass;
1263
    }
1264
1265
    /**
1266
     * Set the class that's used to contain validation information.
1267
     *
1268
     * @param Validation|string $class Either the name of a class or a class that will be cloned.
1269
     * @return $this
1270
     */
1271 1
    public function setValidationClass($class) {
1272 1
        if (!is_a($class, Validation::class, true)) {
1273
            throw new \InvalidArgumentException("$class must be a subclass of ".Validation::class, 500);
1274
        }
1275
1276 1
        $this->validationClass = $class;
1277 1
        return $this;
1278
    }
1279
1280
    /**
1281
     * Create a new validation instance.
1282
     *
1283
     * @return Validation Returns a validation object.
1284
     */
1285 176
    protected function createValidation() {
1286 176
        $class = $this->getValidationClass();
1287
1288 176
        if ($class instanceof Validation) {
1289 1
            $result = clone $class;
1290
        } else {
1291 176
            $result = new $class;
1292
        }
1293 176
        return $result;
1294
    }
1295
1296
    /**
1297
     * Check whether or not a value is an array or accessible like an array.
1298
     *
1299
     * @param mixed $value The value to check.
1300
     * @return bool Returns **true** if the value can be used like an array or **false** otherwise.
1301
     */
1302 101
    private function isArray($value) {
1303 101
        return is_array($value) || ($value instanceof \ArrayAccess && $value instanceof \Traversable);
1304
    }
1305
1306
    /**
1307
     * Cast a value to an array.
1308
     *
1309
     * @param \Traversable $value The value to convert.
1310
     * @return array Returns an array.
1311
     */
1312 3
    private function toObjectArray(\Traversable $value) {
1313 3
        $class = get_class($value);
1314 3
        if ($value instanceof \ArrayObject) {
1315 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...
1316 1
        } elseif ($value instanceof \ArrayAccess) {
1317 1
            $r = new $class;
1318 1
            foreach ($value as $k => $v) {
1319 1
                $r[$k] = $v;
1320
            }
1321 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...
1322
        }
1323
        return iterator_to_array($value);
1324
    }
1325
1326
    /**
1327
     * Return a sparse version of this schema.
1328
     *
1329
     * A sparse schema has no required properties.
1330
     *
1331
     * @return Schema Returns a new sparse schema.
1332
     */
1333 2
    public function withSparse() {
1334 2
        $sparseSchema = $this->withSparseInternal($this, new \SplObjectStorage());
1335 2
        return $sparseSchema;
1336
    }
1337
1338
    /**
1339
     * The internal implementation of `Schema::withSparse()`.
1340
     *
1341
     * @param array|Schema $schema The schema to make sparse.
1342
     * @param \SplObjectStorage $schemas Collected sparse schemas that have already been made.
1343
     * @return mixed
1344
     */
1345 2
    private function withSparseInternal($schema, \SplObjectStorage $schemas) {
1346 2
        if ($schema instanceof Schema) {
1347 2
            if ($schemas->contains($schema)) {
1348 1
                return $schemas[$schema];
1349
            } else {
1350 2
                $schemas[$schema] = $sparseSchema = new Schema();
1351 2
                $sparseSchema->schema = $schema->withSparseInternal($schema->schema, $schemas);
1352 2
                if ($id = $sparseSchema->getID()) {
1353
                    $sparseSchema->setID($id.'Sparse');
1354
                }
1355
1356 2
                return $sparseSchema;
1357
            }
1358
        }
1359
1360 2
        unset($schema['required']);
1361
1362 2
        if (isset($schema['items'])) {
1363 1
            $schema['items'] = $this->withSparseInternal($schema['items'], $schemas);
1364
        }
1365 2
        if (isset($schema['properties'])) {
1366 2
            foreach ($schema['properties'] as $name => &$property) {
1367 2
                $property = $this->withSparseInternal($property, $schemas);
1368
            }
1369
        }
1370
1371 2
        return $schema;
1372
    }
1373
1374
    /**
1375
     * Filter a field's value using built in and custom filters.
1376
     *
1377
     * @param mixed $value The original value of the field.
1378
     * @param ValidationField $field The field information for the field.
1379
     * @return mixed Returns the filtered field or the original field value if there are no filters.
1380
     */
1381 176
    private function filterField($value, ValidationField $field) {
1382
        // Check for limited support for Open API style.
1383 176
        if (!empty($field->val('style')) && is_string($value)) {
1384 8
            $doFilter = true;
1385 8
            if ($field->hasType('boolean') && in_array($value, ['true', 'false', '0', '1'], true)) {
1386 4
                $doFilter = false;
1387 4
            } elseif ($field->hasType('integer') || $field->hasType('number') && is_numeric($value)) {
1388
                $doFilter = false;
1389
            }
1390
1391 8
            if ($doFilter) {
1392 4
                switch ($field->val('style')) {
1393 4
                    case 'form':
1394 2
                        $value = explode(',', $value);
1395 2
                        break;
1396 2
                    case 'spaceDelimited':
1397 1
                        $value = explode(' ', $value);
1398 1
                        break;
1399 1
                    case 'pipeDelimited':
1400 1
                        $value = explode('|', $value);
1401 1
                        break;
1402
                }
1403
            }
1404
        }
1405
1406 176
        $value = $this->callFilters($value, $field);
1407
1408 176
        return $value;
1409
    }
1410
1411
    /**
1412
     * Whether a offset exists.
1413
     *
1414
     * @param mixed $offset An offset to check for.
1415
     * @return boolean true on success or false on failure.
1416
     * @link http://php.net/manual/en/arrayaccess.offsetexists.php
1417
     */
1418 6
    public function offsetExists($offset) {
1419 6
        return isset($this->schema[$offset]);
1420
    }
1421
1422
    /**
1423
     * Offset to retrieve.
1424
     *
1425
     * @param mixed $offset The offset to retrieve.
1426
     * @return mixed Can return all value types.
1427
     * @link http://php.net/manual/en/arrayaccess.offsetget.php
1428
     */
1429 2
    public function offsetGet($offset) {
1430 2
        return isset($this->schema[$offset]) ? $this->schema[$offset] : null;
1431
    }
1432
1433
    /**
1434
     * Offset to set.
1435
     *
1436
     * @param mixed $offset The offset to assign the value to.
1437
     * @param mixed $value The value to set.
1438
     * @link http://php.net/manual/en/arrayaccess.offsetset.php
1439
     */
1440 1
    public function offsetSet($offset, $value) {
1441 1
        $this->schema[$offset] = $value;
1442 1
    }
1443
1444
    /**
1445
     * Offset to unset.
1446
     *
1447
     * @param mixed $offset The offset to unset.
1448
     * @link http://php.net/manual/en/arrayaccess.offsetunset.php
1449
     */
1450 1
    public function offsetUnset($offset) {
1451 1
        unset($this->schema[$offset]);
1452 1
    }
1453
1454
    /**
1455
     * Validate a field against a single type.
1456
     *
1457
     * @param mixed $value The value to validate.
1458
     * @param string $type The type to validate against.
1459
     * @param ValidationField $field Contains field and validation information.
1460
     * @param bool $sparse Whether or not this should be a sparse validation.
1461
     * @return mixed Returns the valid value or `Invalid`.
1462
     */
1463 175
    protected function validateSingleType($value, $type, ValidationField $field, $sparse) {
1464
        switch ($type) {
1465 175
            case 'boolean':
1466 30
                $result = $this->validateBoolean($value, $field);
1467 30
                break;
1468 155
            case 'integer':
1469 38
                $result = $this->validateInteger($value, $field);
1470 38
                break;
1471 149
            case 'number':
1472 13
                $result = $this->validateNumber($value, $field);
1473 13
                break;
1474 144
            case 'string':
1475 66
                $result = $this->validateString($value, $field);
1476 66
                break;
1477 123
            case 'timestamp':
1478 8
                $result = $this->validateTimestamp($value, $field);
1479 8
                break;
1480 122
            case 'datetime':
1481 10
                $result = $this->validateDatetime($value, $field);
1482 10
                break;
1483 118
            case 'array':
1484 29
                $result = $this->validateArray($value, $field, $sparse);
1485 29
                break;
1486 102
            case 'object':
1487 101
                $result = $this->validateObject($value, $field, $sparse);
1488 99
                break;
1489 3
            case 'null':
1490 1
                $result = $this->validateNull($value, $field);
1491 1
                break;
1492 2
            case null:
1493
                // No type was specified so we are valid.
1494 2
                $result = $value;
1495 2
                break;
1496
            default:
1497
                throw new \InvalidArgumentException("Unrecognized type $type.", 500);
1498
        }
1499 175
        return $result;
1500
    }
1501
1502
    /**
1503
     * Validate a field against multiple basic types.
1504
     *
1505
     * The first validation that passes will be returned. If no type can be validated against then validation will fail.
1506
     *
1507
     * @param mixed $value The value to validate.
1508
     * @param string[] $types The types to validate against.
1509
     * @param ValidationField $field Contains field and validation information.
1510
     * @param bool $sparse Whether or not this should be a sparse validation.
1511
     * @return mixed Returns the valid value or `Invalid`.
1512
     */
1513 39
    private function validateMultipleTypes($value, array $types, ValidationField $field, $sparse) {
1514
        // First check for an exact type match.
1515 39
        switch (gettype($value)) {
1516 39
            case 'boolean':
1517 5
                if (in_array('boolean', $types)) {
1518 5
                    $singleType = 'boolean';
1519
                }
1520 5
                break;
1521 35
            case 'integer':
1522 9
                if (in_array('integer', $types)) {
1523 6
                    $singleType = 'integer';
1524 3
                } elseif (in_array('number', $types)) {
1525 1
                    $singleType = 'number';
1526
                }
1527 9
                break;
1528 28
            case 'double':
1529 5
                if (in_array('number', $types)) {
1530 5
                    $singleType = 'number';
1531
                } elseif (in_array('integer', $types)) {
1532
                    $singleType = 'integer';
1533
                }
1534 5
                break;
1535 24
            case 'string':
1536 12
                if (in_array('datetime', $types) && preg_match(self::$DATE_REGEX, $value)) {
1537 1
                    $singleType = 'datetime';
1538 11
                } elseif (in_array('string', $types)) {
1539 7
                    $singleType = 'string';
1540
                }
1541 12
                break;
1542 13
            case 'array':
1543 12
                if (in_array('array', $types) && in_array('object', $types)) {
1544 1
                    $singleType = isset($value[0]) || empty($value) ? 'array' : 'object';
1545 11
                } elseif (in_array('object', $types)) {
1546 1
                    $singleType = 'object';
1547 10
                } elseif (in_array('array', $types)) {
1548 10
                    $singleType = 'array';
1549
                }
1550 12
                break;
1551 2
            case 'NULL':
1552
                if (in_array('null', $types)) {
1553
                    $singleType = $this->validateSingleType($value, 'null', $field, $sparse);
1554
                }
1555
                break;
1556
        }
1557 39
        if (!empty($singleType)) {
1558 33
            return $this->validateSingleType($value, $singleType, $field, $sparse);
1559
        }
1560
1561
        // Clone the validation field to collect errors.
1562 8
        $typeValidation = new ValidationField(new Validation(), $field->getField(), '', $sparse);
1563
1564
        // Try and validate against each type.
1565 8
        foreach ($types as $type) {
1566 8
            $result = $this->validateSingleType($value, $type, $typeValidation, $sparse);
1567 8
            if (Invalid::isValid($result)) {
1568 8
                return $result;
1569
            }
1570
        }
1571
1572
        // Since we got here the value is invalid.
1573
        $field->merge($typeValidation->getValidation());
1574
        return Invalid::value();
1575
    }
1576
}
1577