1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace League\JsonGuard; |
4
|
|
|
|
5
|
|
|
use League\JsonGuard\Exception\InvalidSchemaException; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Assertions to verify a schema is valid. |
9
|
|
|
*/ |
10
|
|
|
final class Assert |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* Validate an array has at least one element. |
14
|
|
|
* |
15
|
|
|
* @param array $value |
16
|
|
|
* @param string $keyword |
17
|
|
|
* @param string $pointer |
18
|
|
|
*/ |
19
|
28 |
|
public static function notEmpty(array $value, $keyword, $pointer) |
20
|
|
|
{ |
21
|
28 |
|
if (!empty($value)) { |
22
|
22 |
|
return; |
23
|
|
|
} |
24
|
|
|
|
25
|
6 |
|
throw InvalidSchemaException::emptyArray($keyword, $pointer); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Validate an integer is non-negative. |
30
|
|
|
* |
31
|
|
|
* @param integer $value |
32
|
|
|
* @param string $keyword |
33
|
|
|
* @param string $pointer |
34
|
|
|
*/ |
35
|
48 |
|
public static function nonNegative($value, $keyword, $pointer) |
36
|
|
|
{ |
37
|
48 |
|
if ($value >= 0) { |
38
|
32 |
|
return; |
39
|
|
|
} |
40
|
|
|
|
41
|
16 |
|
throw InvalidSchemaException::negativeValue( |
42
|
16 |
|
$value, |
43
|
16 |
|
$keyword, |
44
|
16 |
|
$pointer |
45
|
|
|
); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Validate a value is one of the allowed types. |
50
|
|
|
* |
51
|
|
|
* @param mixed $value |
52
|
|
|
* @param array|string $choices |
53
|
|
|
* @param string $keyword |
54
|
|
|
* @param string $pointer |
55
|
|
|
* |
56
|
|
|
* @throws InvalidSchemaException |
57
|
|
|
*/ |
58
|
250 |
|
public static function type($value, $choices, $keyword, $pointer) |
59
|
|
|
{ |
60
|
250 |
|
$actualType = gettype($value); |
61
|
250 |
|
$choices = is_array($choices) ? $choices : [$choices]; |
62
|
|
|
|
63
|
250 |
|
if (in_array($actualType, $choices) || |
64
|
250 |
|
(is_json_number($value) && in_array('number', $choices))) { |
65
|
194 |
|
return; |
66
|
|
|
} |
67
|
|
|
|
68
|
56 |
|
throw InvalidSchemaException::invalidParameterType( |
69
|
56 |
|
$actualType, |
70
|
56 |
|
$choices, |
71
|
56 |
|
$keyword, |
72
|
56 |
|
$pointer |
73
|
|
|
); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* @param object $schema |
78
|
|
|
* @param string $property |
79
|
|
|
* @param string $keyword |
80
|
|
|
* @param string $pointer |
81
|
|
|
*/ |
82
|
8 |
|
public static function hasProperty($schema, $property, $keyword, $pointer) |
83
|
|
|
{ |
84
|
8 |
|
if (isset($schema->$property)) { |
85
|
8 |
|
return; |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
throw InvalidSchemaException::missingProperty( |
89
|
|
|
$property, |
90
|
|
|
$keyword, |
91
|
|
|
$pointer |
92
|
|
|
); |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|