forked from inhere/php-validate
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScopedValidatorsTrait.php
More file actions
708 lines (617 loc) · 19.1 KB
/
ScopedValidatorsTrait.php
File metadata and controls
708 lines (617 loc) · 19.1 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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
<?php declare(strict_types=1);
/**
* Created by PhpStorm.
* User: inhere
* Date: 2017-03-17
* Time: 11:26
*/
namespace Inhere\Validate\Traits;
use Inhere\Validate\AbstractValidation;
use Inhere\Validate\Filter\Filters;
use Inhere\Validate\Helper;
use Inhere\Validate\Validators;
use Inhere\ValidateTest\Example\DataModel;
use InvalidArgumentException;
use function array_shift;
use function function_exists;
use function getimagesize;
use function in_array;
use function is_object;
use function is_string;
use function method_exists;
use function strrchr;
use function strtolower;
use function trim;
use const UPLOAD_ERR_OK;
/**
* trait ScopedValidatorsTrait - deps the current validation instance.
* - user custom validators
* - some validators of require context data.
*
* @package Inhere\Validate\Traits
*/
trait ScopedValidatorsTrait
{
/** @var array user custom adds validators(current scope) */
protected array $_validators = [];
/**
* @see $_FILES
* @var array[]
*/
private array $uploadedFiles = [];
/*******************************************************************************
* custom validators
******************************************************************************/
/**
* add a custom validator
*
* ```
* $v = Validation::make($_POST)
* ->addValidator('my-validator', function($val [, $arg1, $arg2 ... ]){
* return $val === 23;
* });
* $v->validate();
* ```
*
* @param string $name
* @param callable $callback
* @param string $message
*
* @return AbstractValidation|ScopedValidatorsTrait|DataModel
*/
public function addValidator(string $name, callable $callback, string $message = ''): self
{
return $this->setValidator($name, $callback, $message);
}
/**
* add a custom validator
*
* @param string $name
* @param callable $callback
* @param string $message
*
* @return static
*/
public function setValidator(string $name, callable $callback, string $message = ''): self
{
if ($name = trim($name)) {
$this->_validators[$name] = $callback;
if ($message) {
$this->setMessage($name, $message);
}
}
return $this;
}
/**
* @param string $name
*
* @return null|callable
*/
public function getValidator(string $name): ?callable
{
return $this->_validators[$name] ?? null;
}
/**
* @param string $name
*
* @return bool
*/
public function hasValidator(string $name): bool
{
return isset($this->_validators[$name]);
}
/**
* @param array $validators
*
* @return $this
*/
public function addValidators(array $validators): self
{
foreach ($validators as $name => $validator) {
$this->addValidator($name, $validator);
}
return $this;
}
/**
* @return array
*/
public function getValidators(): array
{
return $this->_validators;
}
/**
* @param string $name
*/
public function delValidator(string $name): void
{
if (isset($this->_validators[$name])) {
unset($this->_validators[$name]);
}
}
/**
* clear validators
*/
public function clearValidators(): void
{
$this->_validators = [];
}
/*******************************************************************************
* fields(required*, file) validators
******************************************************************************/
/**
* 验证字段必须存在,且输入数据不为空。
* The verification field must exist and the input data is not empty.
*
* @param string $field
* @param mixed|null $value
*
* @return bool
* - True field exists and value is not empty.
* - False field not exists or value is empty.
* @see Validators::isEmpty() 如何鉴定为空
*/
public function required(string $field, mixed $value = null): bool
{
if (null !== $value) {
$val = $value;
} elseif (null === ($val = $this->getByPath($field))) {
// check uploaded files
if (!isset($this->uploadedFiles[$field])) {
return false;
}
$val = $this->uploadedFiles[$field];
}
return !Validators::isEmpty($val);
}
/**
* 如果指定的另一个字段( anotherField )值等于任何一个 value 时,此字段为 必填 (refer laravel)
*
* returns:
* - TRUE check successful
* - FALSE check failed
* - NULL skip check the field
*
* @param string $field
* @param mixed $fieldVal
* @param string $anotherField
* @param array|string|int $values
*
* @return bool|null
*/
public function requiredIf(string $field, mixed $fieldVal, string $anotherField, array|string|int $values): ?bool
{
if (isset($this->data[$anotherField])) {
$anotherVal = $this->data[$anotherField];
// if (in_array($anotherVal, (array)$values, true)) {
if (Helper::inArray($anotherVal, (array)$values)) {
return $this->required($field, $fieldVal);
}
}
return null;
}
/**
* 如果指定的另一个字段( anotherField )值等于任何一个 value 时,此字段为 不必填(refer laravel)
*
* @param string $field
* @param mixed $fieldVal
* @param string $anotherField
* @param array|string $values
*
* @return bool|null
* @see requiredIf()
*/
public function requiredUnless(string $field, mixed $fieldVal, string $anotherField, array|string $values): ?bool
{
if (isset($this->data[$anotherField])) {
$anotherVal = $this->data[$anotherField];
// if (in_array($anotherVal, (array)$values, true)) {
if (Helper::inArray($anotherVal, (array)$values)) {
return null;
}
}
return $this->required($field, $fieldVal);
}
/**
* 如果指定的其他字段中的 任意一个 有值且不为空,则此字段为 必填(refer laravel)
*
* @param string $field
* @param mixed $fieldVal
* @param array|string $fields
*
* @return bool|null
* @see requiredIf()
*/
public function requiredWith(string $field, mixed $fieldVal, array|string $fields): ?bool
{
foreach ((array)$fields as $name) {
if ($this->required($name)) {
return $this->required($field, $fieldVal);
}
}
return null;
}
/**
* 如果指定的 所有字段 都有值且不为空,则此字段为 必填(refer laravel)
*
* @param string $field
* @param mixed $fieldVal
* @param array|string $fields
*
* @return bool|null
* @see requiredIf()
*/
public function requiredWithAll(string $field, mixed $fieldVal, array|string $fields): ?bool
{
$allHasValue = true;
foreach ((array)$fields as $name) {
if (!$this->required($name)) {
$allHasValue = false;
break;
}
}
return $allHasValue ? $this->required($field, $fieldVal) : null;
}
/**
* 如果缺少 任意一个 指定的字段值,则此字段为 必填(refer laravel)
*
* @param string $field
* @param mixed $fieldVal
* @param array|string $fields
*
* @return bool|null
* @see requiredIf()
*/
public function requiredWithout(string $field, mixed $fieldVal, array|string $fields): ?bool
{
$allHasValue = true;
foreach ((array)$fields as $name) {
if (!$this->required($name)) {
$allHasValue = false;
break;
}
}
return $allHasValue ? null : $this->required($field, $fieldVal);
}
/**
* 如果所有指定的字段 都没有 值,则此字段为 必填(refer laravel)
*
* @param string $field
* @param mixed $fieldVal
* @param array|string $fields
*
* @return bool|null
* @see requiredIf()
*/
public function requiredWithoutAll(string $field, mixed $fieldVal, array|string $fields): ?bool
{
$allNoValue = true;
foreach ((array)$fields as $name) {
if ($this->required($name)) {
$allNoValue = false;
break;
}
}
return $allNoValue ? $this->required($field, $fieldVal) : null;
}
/*******************************************************************************
* Files validators(require context data)
******************************************************************************/
/**
* 验证的字段必须是成功上传的文件
*
* @param string $field
* @param array|string|null $suffixes e.g ['jpg', 'jpeg', 'png', 'gif', 'bmp']
*
* @return bool
*/
public function fileValidator(string $field, null|array|string $suffixes = null): bool
{
if (!$file = $this->uploadedFiles[$field] ?? null) {
return false;
}
if (!isset($file['error']) || ($file['error'] !== UPLOAD_ERR_OK)) {
return false;
}
if (!$suffixes) {
return true;
}
if (!$suffix = trim((string)strrchr($file['name'], '.'), '.')) {
return false;
}
$suffixes = is_string($suffixes) ? Filters::explode($suffixes) : $suffixes;
return in_array(strtolower($suffix), $suffixes, true);
}
/**
* 验证的字段必须是成功上传的图片文件
*
* @param string $field
* @param array|string|null $suffixes e.g ['jpg', 'jpeg', 'png', 'gif', 'bmp']
*
* @return bool
*/
public function imageValidator(string $field, null|array|string $suffixes = null): bool
{
if (!$file = $this->uploadedFiles[$field] ?? null) {
return false;
}
if (!isset($file['error']) || ($file['error'] !== UPLOAD_ERR_OK)) {
return false;
}
if (!$tmpFile = $file['tmp_name'] ?? null) {
return false;
}
// getimagesize() 判定某个文件是否为图片的有效手段, 常用在文件上传验证
// Note: 本函数不需要 GD 图像库
// list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
$imgInfo = @getimagesize($tmpFile);
if ($imgInfo && $imgInfo[2]) {
$mime = strtolower($imgInfo['mime']); // 支持不标准扩展名
// 是否是图片
if (!in_array($mime, Helper::$imgMimeTypes, true)) {
return false;
}
if (!$suffixes) {
return true;
}
$suffix = Helper::getImageExtByMime($mime);
$suffixes = is_string($suffixes) ? Filters::explode($suffixes) : $suffixes;
return in_array($suffix, $suffixes, true);
}
return false;
}
/**
* 验证的文件必须与给定 MIME 类型之一匹配
* ['video', 'mimeTypes', 'video/avi,video/mpeg,video/quicktime']
*
* @param string $field
* @param array|string $types
*
* @return bool
*/
public function mimeTypesValidator(string $field, array|string $types): bool
{
if (!$file = $this->uploadedFiles[$field] ?? null) {
return false;
}
if (!isset($file['error']) || ($file['error'] !== UPLOAD_ERR_OK)) {
return false;
}
if (!$tmpFile = $file['tmp_name'] ?? null) {
return false;
}
$mime = Helper::getMimeType($tmpFile);
$types = is_string($types) ? Filters::explode($types) : (array)$types;
return in_array($mime, $types, true);
}
/**
* 验证的文件必须具有与列出的其中一个扩展名相对应的 MIME 类型
* ['photo', 'mimes', 'jpeg,bmp,png']
*
* @param string $field
* @param array|string|null $types
* return bool
*
* @todo
*/
public function mimesValidator(string $field, null|array|string $types = null): void
{
}
/*******************************************************************************
* Field compare validators
******************************************************************************/
/**
* 字段值比较:当前字段值是否与给定的字段值相同
*
* @param mixed $val
* @param string $compareField
*
* @return bool
*/
public function compareValidator(mixed $val, string $compareField): bool
{
return $compareField && ($val === $this->getByPath($compareField));
}
public function eqFieldValidator($val, string $compareField): bool
{
return $this->compareValidator($val, $compareField);
}
/**
* 字段值比较:当前字段值是否与给定的字段值不相同
*
* @param mixed $val
* @param string $compareField
*
* @return bool
*/
public function neqFieldValidator(mixed $val, string $compareField): bool
{
return $compareField && ($val !== $this->getByPath($compareField));
}
/**
* 字段值比较:当前字段值 要小于 给定字段的值
*
* @param int|string $val
* @param string $compareField
*
* @return bool
*/
public function ltFieldValidator(int|string $val, string $compareField): bool
{
$maxVal = $this->getByPath($compareField);
if ($maxVal === null) {
return false;
}
return Validators::lt($val, $maxVal);
}
/**
* 字段值比较:当前字段值 要小于等于 给定字段的值
*
* @param int|string $val
* @param string $compareField
*
* @return bool
*/
public function lteFieldValidator(int|string $val, string $compareField): bool
{
$maxVal = $this->getByPath($compareField);
if ($maxVal === null) {
return false;
}
return Validators::lte($val, $maxVal);
}
/**
* 字段值比较:当前字段值 要大于 给定字段的值
*
* @param int|string $val
* @param string $compareField
*
* @return bool
*/
public function gtFieldValidator(int|string $val, string $compareField): bool
{
$minVal = $this->getByPath($compareField);
if ($minVal === null) {
return false;
}
return Validators::gt($val, $minVal);
}
/**
* 字段值比较:当前字段值 要大于等于 给定字段的值
*
* @param int|string $val
* @param string $compareField
*
* @return bool
*/
public function gteFieldValidator(int|string $val, string $compareField): bool
{
$minVal = $this->getByPath($compareField);
if ($minVal === null) {
return false;
}
return Validators::gte($val, $minVal);
}
/**
* 验证的 字段值 必须存在于另一个字段(anotherField)的值中。
*
* @param mixed $val
* @param string $anotherField
*
* @return bool
*/
public function inFieldValidator(mixed $val, string $anotherField): bool
{
if ($anotherField && $dict = $this->getByPath($anotherField)) {
return Validators::in($val, $dict);
}
return false;
}
/**
* 比较两个日期字段的 间隔天数 是否符合要求
*
* @param string $val
* @param string $compareField
* @param int $expected
* @param string $op
*
* @todo
*/
public function intervalDayValidator(string $val, string $compareField, int $expected, string $op = '>='): void
{
}
/**
* 对数组中的每个值都应用给定的验证器,并且要全部通过
* `['foo.*.id', 'each', 'number']`
* `['goods.*', 'each', 'string']`
*
* @param array $values
* @param mixed ...$args
* - string|\Closure $validator
* - ... args for $validator
*
* @return bool
* @throws InvalidArgumentException
*/
public function eachValidator(array $values, ...$args): bool
{
if (!$validator = array_shift($args)) {
throw new InvalidArgumentException('must setting a validator for \'each\' validate.');
}
foreach ($values as $value) {
$passed = false;
if (is_object($validator) && method_exists($validator, '__invoke')) {
$passed = $validator($value, ...$args);
} elseif (is_string($validator)) {
// special for required
if ('required' === $validator) {
$passed = !Validators::isEmpty($value);
} elseif (isset($this->_validators[$validator])) {
$callback = $this->_validators[$validator];
$passed = $callback($value, ...$args);
} elseif (method_exists($this, $method = $validator . 'Validator')) {
$passed = $this->$method($value, ...$args);
} elseif (method_exists(Validators::class, $validator)) {
$passed = Validators::$validator($value, ...$args);
// it is function name
} elseif (function_exists($validator)) {
$passed = $validator($value, ...$args);
} else {
throw new InvalidArgumentException("The validator [$validator] don't exists!");
}
}
if (!$passed) {
return false;
}
}
return true;
}
/*******************************************************************************
* getter/setter/helper
******************************************************************************/
/**
* @param string $name
*
* @return bool
*/
public static function isCheckFile(string $name): bool
{
return str_contains(Helper::$fileValidators, '|' . $name . '|');
}
/**
* @param string $name
* @param array $args
* @return bool
*/
public static function isCheckRequired(string $name, array $args = []): bool
{
// the $arg.0 is validator name.
$name = $name === 'each' ? ((string)($args[0] ?? '')) : $name;
return str_starts_with($name, 'required');
}
/**
* @param string $field
*
* @return array|null
*/
public function getUploadedFile(string $field): ?array
{
return $this->uploadedFiles[$field] ?? null;
}
/**
* @return array
*/
public function getUploadedFiles(): array
{
return $this->uploadedFiles;
}
/**
* @param array $uploadedFiles
*
* @return static
*/
public function setUploadedFiles(array $uploadedFiles): static
{
$this->uploadedFiles = $uploadedFiles;
return $this;
}
}