Repository navigation
Expand file tree
/
Copy pathJsonType.php
More file actions
206 lines (192 loc) · 7.27 KB
/
Copy pathJsonType.php
File metadata and controls
206 lines (192 loc) · 7.27 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
<?php
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]);
* $jsonType->matches([
* 'name' => 'string:!empty',
* 'id' => 'integer:>0|string:>0',
* ])); // => true
*
* $jsonType->matches([
* 'id' => 'string',
* ])); // => `id: 1` is not of type string
* ?>
* ```
*
* Class JsonType
* @package Codeception\Util
*/
class JsonType
{
protected $jsonArray;
protected static $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|\Codeception\Util\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)'
* ?>
* ```
*
* @param $name
* @param callable $callable
*/
public static function addCustomFilter($name, callable $callable)
{
static::$customFilters[$name] = $callable;
}
/**
* Removes all custom filters
*/
public static function cleanCustomFilters()
{
static::$customFilters = [];
}
/**
* Checks data against passed JsonType.
* If matching fails function returns a string with a message describing failure.
* On success returns `true`.
*
* @param array $jsonType
* @return bool|string
*/
public function matches(array $jsonType)
{
if (array_key_exists(0, $this->jsonArray)) {
// sequential array
if (array_key_exists(0, $this->jsonArray)) {
$msg = '';
foreach ($this->jsonArray as $array) {
$res = $this->typeComparison($array, $jsonType);
if ($res !== true) {
$msg .= "\n" . $res;
}
}
if ($msg) {
return $msg;
}
return true;
}
}
return $this->typeComparison($this->jsonArray, $jsonType);
}
protected function typeComparison($data, $jsonType)
{
foreach ($jsonType as $key => $type) {
if (!array_key_exists($key, $data)) {
return "Key `$key` doesn't exist in " . json_encode($data);
}
if (is_array($jsonType[$key])) {
$message = $this->typeComparison($data[$key], $jsonType[$key]);
if (is_string($message)) {
return $message;
}
continue;
}
$matchTypes = preg_split("#(?![^]\(]*\))\|#", $type);
$matched = false;
$currentType = strtolower(gettype($data[$key]));
if ($currentType == 'double') {
$currentType = 'float';
}
foreach ($matchTypes as $matchType) {
$filters = preg_split("#(?![^]\(]*\))\:#", $matchType);
$expectedType = trim(strtolower(array_shift($filters)));
if ($expectedType != $currentType) {
continue;
}
$matched = true;
foreach ($filters as $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($filter, $value)
{
$filter = trim($filter);
if (strpos($filter,'!') === 0) {
return !$this->matchFilter(substr($filter, 1), $value);
}
// apply custom filters
foreach (static::$customFilters as $customFilter => $callable) {
if (strpos($customFilter, '/') === 0) {
if (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 (strpos($filter, '=') === 0) {
return $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 http://emailregex.com/
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][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\]))$/iD', $value);
}
if ($filter === 'empty') {
return empty($value);
}
if (preg_match('~^regex\((.*?)\)$~', $filter, $matches)) {
return preg_match($matches[1], $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];
}
}
}