-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidation.php
More file actions
425 lines (385 loc) · 11.3 KB
/
Validation.php
File metadata and controls
425 lines (385 loc) · 11.3 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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
<?php
namespace Colibri\Validation;
use Colibri\Util\Arr;
use Colibri\Util\Str;
/**
* Organize Validation of your data.
*/
class Validation
{
/** @var string */
public static $requiredMessage = 'поле \'%s\' является обязательным для заполнения.';
/** @var string */
public static $minLengthMessage = 'поле \'%s\' должно быть не меньше %d символов.';
/** @var string */
public static $maxLengthMessage = 'поле \'%s\' не должно быть больше %d символов.';
/** @var string */
public static $regexMessage = 'поле \'%s\' не удовлетворяет условию.';
/** @var string */
public static $isIntGt0Message = 'поле \'%s\' должно быть целым числом больше 0.';
/** @var string */
public static $isJSONMessage = 'поле \'%s\' должно быть строкой в формате JSON.';
/** @var string */
public static $isEmailMessage = 'поле \'%s\' должно содержать существующий почтовый ящик.';
/** @var string */
public static $isEqualMessage = 'поля \'%s\' должны быть одинаковыми.';
/**
* @var array occurred validation errors
*/
protected $errors = [];
/**
* @var array scope of data to validate
*/
protected $scope = [];
/**
* Validation constructor.
*
* @param array $scope initial scope of data to validate
*/
public function __construct(array $scope = null)
{
if ($scope !== null) {
$this->scope = $scope;
}
}
/**
* Adds additional data to existing scope.
*
* @param array $scope
*
* @return $this
*/
public function extendScope(array $scope)
{
$this->scope = array_merge($this->scope, $scope);
return $this;
}
/**
* Resets scope with new one & resets the errors.
*
* @param array $scope
*
* @return $this
*/
public function setScope(array $scope)
{
$this->scope = $scope;
$this->errors = [];
return $this;
}
/**
* @return array
*/
public function errors(): array
{
return $this->errors;
}
/**
* Adds specified error $message for $key.
*
* @param $key
* @param $message
*/
public function addError($key, $message)
{
$this->errors[$key] = $message;
}
/**
* @param string $method
* @param string|array $key
* @param string $message
* @param callable $check
*
* @return $this
*/
private function check(string $method, $key, string $message = null, callable $check)
{
if (is_array($key)) {
foreach ($key as $name) {
$this->$method($name, $message);
}
} else {
if (isset($this->scope[$key]) && ! $check($key)) {
$this->errors[$key] = sprintf($message !== null ? $message : self::${$method . 'Message'}, $key);
}
}
return $this;
}
/**
* 'Required' validation rule. Checks if specified by $key data exists in scope.
*
* @param string|array $key
* @param string $message
*
* @return $this
*/
public function required($key, $message = null)
{
if (is_array($key)) {
foreach ($key as $name) {
$this->required($name, $message);
}
} else {
if ( ! (isset($this->scope[$key]) && ! empty($this->scope[$key]))) {
$this->errors[$key] = sprintf($message !== null ? $message : self::$requiredMessage, $key);
}
}
return $this;
}
/**
* 'MinLength' validation rule. Checks that specified by $key data not shorter than $minLength.
*
* @param string|array $key
* @param int|array $minLength
* @param string $message
*
* @return $this
*/
public function minLength($key, $minLength, $message = null)
{
if (is_array($key)) {
foreach ($key as $k => $name) {
$this->minLength($name, is_array($minLength) ? $minLength[$k] : $minLength, $message);
}
} else {
if (isset($this->scope[$key]) && mb_strlen($this->scope[$key]) < $minLength) {
$this->errors[$key] = sprintf($message !== null ? $message : self::$minLengthMessage, $key, $minLength);
}
}
return $this;
}
/**
* 'MaxLength' validation rule. Checks that specified by $key data not longer than $maxLength.
*
* @param string|array $key
* @param int|array $maxLength
* @param string $message
*
* @return $this
*/
public function maxLength($key, $maxLength, $message = null)
{
if (is_array($key)) {
foreach ($key as $k => $name) {
$this->maxLength($name, is_array($maxLength) ? $maxLength[$k] : $maxLength, $message);
}
} else {
if (isset($this->scope[$key]) && mb_strlen($this->scope[$key]) > $maxLength) {
$this->errors[$key] = sprintf($message !== null ? $message : self::$maxLengthMessage, $key, $maxLength);
}
}
return $this;
}
/**
* 'Regex' validation rule. Checks that specified by $key data matches to $pattern.
*
* @param string|array $key
* @param string $pattern
* @param string $message
*
* @return $this
*/
public function regex($key, $pattern, $message = null)
{
if (is_array($key)) {
foreach ($key as $k => $name) {
$this->regex($name, is_array($pattern) ? $pattern[$k] : $pattern, $message);
}
} else {
if (isset($this->scope[$key]) && ! (bool)preg_match($pattern, $this->scope[$key])) {
$this->errors[$key] = sprintf($message !== null ? $message : self::$regexMessage, $key);
}
}
return $this;
}
/**
* 'IsIntGt0' validation rule. Checks that specified by $key data is integer and greater than zero.
*
* @param string|array $key
* @param string $message
*
* @return $this
*/
public function isIntGt0($key, $message = null)
{
return $this->check(__FUNCTION__, $key, $message, function ($key) {
return Str::isInt($this->scope[$key]) && ((int)$this->scope[$key]) > 0;
});
}
/**
* 'IsJSON' validation rule. Checks that specified by $key data stores a JSON string.
*
* @param string|array $key
* @param string $message
*
* @return $this
*/
public function isJSON($key, $message = null)
{
return $this->check(__FUNCTION__, $key, $message, function ($key) {
return Str::isJSON($this->scope[$key]);
});
}
/**
* 'IsEmail' validation rule. Checks that specified by $key data stores a string with email.
*
* @param string|array $key
* @param string $message
*
* @return $this
*/
public function isEmail($key, $message = null)
{
return $this->check(__FUNCTION__, $key, $message, function ($key) {
return Str::isEmail($this->scope[$key]);
});
}
/**
* 'IsEqual' validation rule. Checks that specified by $keys values are equal.
*
* @param array $keys
* @param string $message
*
* @return $this
*/
public function isEqual(array $keys, $message = null)
{
$existingKey = null;
foreach ($keys as $key) {
if (isset($this->scope[$key])) {
$existingKey = $key;
break;
}
}
if ($existingKey === null) {
return $this;
}
foreach ($keys as $key) {
if (isset($this->scope[$key]) && $this->scope[$key] != $this->scope[$existingKey]) {
$keysList = implode("', '", $keys);
$this->errors[$key] = sprintf($message !== null ? $message : self::$isEqualMessage, $keysList);
}
}
return $this;
}
/**
* 'Is' validation rule. Custom rule specified by $checkFunc().
*
* @param callable $checkFunc
* @param string|array $key
* @param string $message
*
* @return static
*/
public function is($checkFunc, $key, $message)
{
if (is_array($key)) {
foreach ($key as $name) {
$this->is($checkFunc, $name, $message);
}
} else {
if (isset($this->scope[$key]) && ! call_user_func($checkFunc, $this->scope[$key])) {
$this->errors[$key] = sprintf($message, $key);
}
}
return $this;
}
/**
* 'Is' validation rule. Custom rule specified by $checkFunc(). Checks that data NOT satisfies to rule.
*
* @param callable $checkFunc
* @param string|array $key
* @param string $message
*
* @return $this
*/
public function isNot($checkFunc, $key, $message)
{
if (is_array($key)) {
foreach ($key as $name) {
$this->isNot($checkFunc, $name, $message);
}
} else {
if (isset($this->scope[$key]) && call_user_func($checkFunc, $this->scope[$key])) {
$this->errors[$key] = sprintf($message, $key);
}
}
return $this;
}
/**
* Checks if scope data is valid or not.
*
* @return bool
*/
public function valid()
{
return ! (bool)count($this->errors);
}
/**
* Calls $callback if scope is valid.
*
* @param \Closure $callback
*
* @return $this
*/
public function ifIsValid(\Closure $callback)
{
if ($this->valid()) {
$callback($this->scope);
}
return $this;
}
/**
* Calls $callback if scope is NOT valid.
*
* @param \Closure $callback
*
* @return $this
*/
public function ifNotValid(\Closure $callback)
{
if ( ! $this->valid()) {
$callback($this->errors);
}
return $this;
}
/** @noinspection PhpDocRedundantThrowsInspection */
/**
* Validates the data scope.
*
* @return $this
*
* @throws ValidationException
*/
public function validate()
{
$this->ifNotValid(function (array $errors) {
/* @noinspection PhpUnhandledExceptionInspection */
throw new ValidationException($errors);
});
return $this;
}
/**
* Creates new Validation instance with $scope injected.
*
* @param array $scope
*
* @return static
*/
public static function forScope(array $scope)
{
return new static($scope);
}
/**
* Gets from $_POST only needed keys and use new as scope.
* Creates new Validation instance with this scope.
*
* @param array $keys list of keys in $_POST array that must be validates
*
* @return Validation
*/
public static function forPostOnly(array $keys)
{
return static::forScope(Arr::only($_POST, $keys));
}
}