-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathJsonType.php
More file actions
257 lines (213 loc) · 8.7 KB
/
JsonType.php
File metadata and controls
257 lines (213 loc) · 8.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
<?php
declare(strict_types=1);
namespace Codeception\Util;
/**
* JsonType matches JSON structures against templates.
* You can specify the type of fields in JSON or add additional validation rules.
*
* JsonType is used by REST module in `seeResponseMatchesJsonType` and `dontSeeResponseMatchesJsonType` methods.
*
* Usage example:
*
* ```php
* <?php
* $jsonType = new JsonType(['name' => 'davert', 'id' => 1, 'data' => []]);
* $jsonType->matches([
* 'name' => 'string:!empty',
* 'id' => 'integer:>0|string:>0',
* 'data' => 'array:empty',
* ]); // => true
*
* $jsonType->matches([
* 'id' => 'string',
* ]); // => `id: 1` is not of type string
* ```
*
* Class JsonType
* @package Codeception\Util
*/
class JsonType
{
/**
* @var array|JsonArray
*/
protected $jsonArray;
protected static array $customFilters = [];
/**
* Creates instance of JsonType
* Pass an array or `\Codeception\Util\JsonArray` with data.
* If non-associative array is passed - the very first element of it will be used for matching.
*
* @param $jsonArray array|JsonArray
*/
public function __construct($jsonArray)
{
if ($jsonArray instanceof JsonArray) {
$jsonArray = $jsonArray->toArray();
}
$this->jsonArray = $jsonArray;
}
/**
* Adds custom filter to JsonType list.
* You should specify a name and parameters of a filter.
*
* Example:
*
* ```php
* <?php
* JsonType::addCustomFilter('slug', function($value) {
* return strpos(' ', $value) !== false;
* });
* // => use it as 'string:slug'
*
* // add custom function to matcher with `len($val)` syntax
* // parameter matching patterns should be valid regex and start with `/` char
* JsonType::addCustomFilter('/len\((.*?)\)/', function($value, $len) {
* return strlen($value) == $len;
* });
* // use it as 'string:len(5)'
* ```
*/
public static function addCustomFilter(string $name, callable $callable): void
{
static::$customFilters[$name] = $callable;
}
/**
* Removes all custom filters
*/
public static function cleanCustomFilters(): void
{
static::$customFilters = [];
}
/**
* Checks data against passed JsonType.
* If matching fails function returns a string with a message describing failure.
* On success returns `true`.
*/
public function matches(array $jsonType): string|bool
{
if (array_key_exists(0, $this->jsonArray) && is_array($this->jsonArray[0])) {
// a list of items
$msg = '';
foreach ($this->jsonArray as $singleJsonArray) {
$res = $this->typeComparison($singleJsonArray, $jsonType);
if ($res !== true) {
$msg .= "\n" . $res;
}
}
if ($msg !== '') {
return $msg;
}
return true;
}
return $this->typeComparison($this->jsonArray, $jsonType);
}
protected function typeComparison(array $data, array $jsonType): string|bool
{
foreach ($jsonType as $key => $type) {
if (!array_key_exists($key, $data)) {
return sprintf("Key `%s` doesn't exist in ", $key) . json_encode($data, JSON_THROW_ON_ERROR);
}
if (is_array($jsonType[$key])) {
$message = $this->typeComparison($data[$key], $jsonType[$key]);
if (is_string($message)) {
return $message;
}
continue;
}
$regexMatcher = '/:regex\((((\()|(\{)|(\[)|(<)|(.)).*?(?(3)\)|(?(4)\}|(?(5)\]|(?(6)>|\7)))))\)/';
$regexes = [];
// Match the string ':regex(' and any characters until a ending regex delimiter followed by character ')'
// Place the 'any character' + delimiter matches in to an array.
preg_match_all($regexMatcher, $type, $regexes);
// Do the same match as above, but replace the the 'any character' + delimiter with a place holder ($${count}).
$filterType = preg_replace_callback($regexMatcher, function (): string {
static $count = 0;
return ':regex($$' . $count++ . ')';
}, $type);
$matchTypes = preg_split("#(?![^]\(]*\))\|#", $filterType);
$matched = false;
$currentType = strtolower(gettype($data[$key]));
if ($currentType === 'double') {
$currentType = 'float';
}
foreach ($matchTypes as $matchType) {
$filters = preg_split("#(?![^]\(]*\))\:#", $matchType);
$expectedType = strtolower(trim(array_shift($filters)));
if ($expectedType !== $currentType) {
continue;
}
$matched = true;
foreach ($filters as $filter) {
// Fill regex pattern back into the filter.
$filter = preg_replace_callback('#\$\$\d+#', function ($m) use ($regexes) {
$pos = (int)substr($m[0], 2);
return $regexes[1][$pos];
}, $filter);
$matched = $matched && $this->matchFilter($filter, $data[$key]);
}
if ($matched) {
break;
}
}
if (!$matched) {
return sprintf("`$key: %s` is of type `$type`", var_export($data[$key], true));
}
}
return true;
}
protected function matchFilter(string $filter, mixed $value)
{
$filter = trim($filter);
if (str_starts_with($filter, '!')) {
return !$this->matchFilter(substr($filter, 1), $value);
}
// apply custom filters
foreach (static::$customFilters as $customFilter => $callable) {
if (str_starts_with($customFilter, '/') && preg_match($customFilter, $filter, $matches)) {
array_shift($matches);
return call_user_func_array($callable, array_merge([$value], $matches));
}
if ($customFilter == $filter) {
return $callable($value);
}
}
if (str_starts_with($filter, '=')) {
return (string) $value === substr($filter, 1);
}
if ($filter === 'url') {
return filter_var($value, FILTER_VALIDATE_URL);
}
if ($filter === 'date') {
return preg_match(
'#^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)?(?:Z|(\+|-)([\d|:]*))?$#',
$value
);
}
if ($filter === 'email') { // from https://emailregex.com/
// @codingStandardsIgnoreStart
return preg_match('#^(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){255,})(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){65,}@)(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22))(?:\.(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-[a-z0-9]+)*\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-[a-z0-9]+)*)|(?:\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4]\d)|(?:1\d{2})|(?:[1-9]?\d))(?:\.(?:(?:25[0-5])|(?:2[0-4]\d)|(?:1\d{2})|(?:[1-9]?\d))){3}))\]))$#iD',
$value);
// @codingStandardsIgnoreEnd
}
if ($filter === 'empty') {
return empty($value);
}
if (preg_match('#^regex\((.*?)\)$#', $filter, $matches)) {
return preg_match($matches[1], (string) $value);
}
if (preg_match('#^>=(-?[\d\.]+)$#', $filter, $matches)) {
return (float)$value >= (float)$matches[1];
}
if (preg_match('#^<=(-?[\d\.]+)$#', $filter, $matches)) {
return (float)$value <= (float)$matches[1];
}
if (preg_match('#^>(-?[\d\.]+)$#', $filter, $matches)) {
return (float)$value > (float)$matches[1];
}
if (preg_match('#^<(-?[\d\.]+)$#', $filter, $matches)) {
return (float)$value < (float)$matches[1];
}
return false;
}
}