Completed
Pull Request — 6.0 (#2150)
by
unknown
06:31
created

Validate::batch()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 5
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
6
// +----------------------------------------------------------------------
7
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
8
// +----------------------------------------------------------------------
9
// | Author: liu21st <[email protected]>
10
// +----------------------------------------------------------------------
11
declare (strict_types = 1);
12
13
namespace think;
14
15
use Closure;
16
use think\exception\ValidateException;
17
use think\helper\Str;
18
use think\validate\ValidateRule;
19
20
/**
21
 * 数据验证类
22
 * @package think
0 ignored issues
show
Coding Style introduced by
Package name "think" is not valid; consider "Think" instead
Loading history...
23
 */
24
class Validate
25
{
26
    /**
27
     * 自定义验证类型
28
     * @var array
29
     */
30
    protected $type = [];
31
32
    /**
33
     * 验证类型别名
34
     * @var array
35
     */
36
    protected $alias = [
37
        '>' => 'gt', '>=' => 'egt', '<' => 'lt', '<=' => 'elt', '=' => 'eq', 'same' => 'eq',
38
    ];
39
40
    /**
41
     * 当前验证规则
42
     * @var array
43
     */
44
    protected $rule = [];
45
46
    /**
47
     * 验证提示信息
48
     * @var array
49
     */
50
    protected $message = [];
51
52
    /**
53
     * 验证字段描述
54
     * @var array
55
     */
56
    protected $field = [];
57
58
    /**
59
     * 默认规则提示
60
     * @var array
61
     */
62
    protected $typeMsg = [
63
        'require'     => ':attribute require',
64
        'must'        => ':attribute must',
65
        'number'      => ':attribute must be numeric',
66
        'integer'     => ':attribute must be integer',
67
        'float'       => ':attribute must be float',
68
        'boolean'     => ':attribute must be bool',
69
        'email'       => ':attribute not a valid email address',
70
        'mobile'      => ':attribute not a valid mobile',
71
        'array'       => ':attribute must be a array',
72
        'accepted'    => ':attribute must be yes,on or 1',
73
        'date'        => ':attribute not a valid datetime',
74
        'file'        => ':attribute not a valid file',
75
        'image'       => ':attribute not a valid image',
76
        'alpha'       => ':attribute must be alpha',
77
        'alphaNum'    => ':attribute must be alpha-numeric',
78
        'alphaDash'   => ':attribute must be alpha-numeric, dash, underscore',
79
        'activeUrl'   => ':attribute not a valid domain or ip',
80
        'chs'         => ':attribute must be chinese',
81
        'chsAlpha'    => ':attribute must be chinese or alpha',
82
        'chsAlphaNum' => ':attribute must be chinese,alpha-numeric',
83
        'chsDash'     => ':attribute must be chinese,alpha-numeric,underscore, dash',
84
        'url'         => ':attribute not a valid url',
85
        'ip'          => ':attribute not a valid ip',
86
        'dateFormat'  => ':attribute must be dateFormat of :rule',
87
        'in'          => ':attribute must be in :rule',
88
        'notIn'       => ':attribute be notin :rule',
89
        'between'     => ':attribute must between :1 - :2',
90
        'notBetween'  => ':attribute not between :1 - :2',
91
        'length'      => 'size of :attribute must be :rule',
92
        'max'         => 'max size of :attribute must be :rule',
93
        'min'         => 'min size of :attribute must be :rule',
94
        'after'       => ':attribute cannot be less than :rule',
95
        'before'      => ':attribute cannot exceed :rule',
96
        'expire'      => ':attribute not within :rule',
97
        'allowIp'     => 'access IP is not allowed',
98
        'denyIp'      => 'access IP denied',
99
        'confirm'     => ':attribute out of accord with :2',
100
        'different'   => ':attribute cannot be same with :2',
101
        'egt'         => ':attribute must greater than or equal :rule',
102
        'gt'          => ':attribute must greater than :rule',
103
        'elt'         => ':attribute must less than or equal :rule',
104
        'lt'          => ':attribute must less than :rule',
105
        'eq'          => ':attribute must equal :rule',
106
        'unique'      => ':attribute has exists',
107
        'regex'       => ':attribute not conform to the rules',
108
        'method'      => 'invalid Request method',
109
        'token'       => 'invalid token',
110
        'fileSize'    => 'filesize not match',
111
        'fileExt'     => 'extensions to upload is not allowed',
112
        'fileMime'    => 'mimetype to upload is not allowed',
113
    ];
114
115
    /**
116
     * 当前验证场景
117
     * @var string
118
     */
119
    protected $currentScene;
120
121
    /**
122
     * 内置正则验证规则
123
     * @var array
124
     */
125
    protected $defaultRegex = [
126
        'alpha'       => '/^[A-Za-z]+$/',
127
        'alphaNum'    => '/^[A-Za-z0-9]+$/',
128
        'alphaDash'   => '/^[A-Za-z0-9\-\_]+$/',
129
        'chs'         => '/^[\x{4e00}-\x{9fa5}]+$/u',
130
        'chsAlpha'    => '/^[\x{4e00}-\x{9fa5}a-zA-Z]+$/u',
131
        'chsAlphaNum' => '/^[\x{4e00}-\x{9fa5}a-zA-Z0-9]+$/u',
132
        'chsDash'     => '/^[\x{4e00}-\x{9fa5}a-zA-Z0-9\_\-]+$/u',
133
        'mobile'      => '/^1[3-9]\d{9}$/',
134
        'idCard'      => '/(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/',
135
        'zip'         => '/\d{6}/',
136
    ];
137
138
    /**
139
     * Filter_var 规则
140
     * @var array
141
     */
142
    protected $filter = [
143
        'email'   => FILTER_VALIDATE_EMAIL,
144
        'ip'      => [FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6],
145
        'integer' => FILTER_VALIDATE_INT,
146
        'url'     => FILTER_VALIDATE_URL,
147
        'macAddr' => FILTER_VALIDATE_MAC,
148
        'float'   => FILTER_VALIDATE_FLOAT,
149
    ];
150
151
    /**
152
     * 验证场景定义
153
     * @var array
154
     */
155
    protected $scene = [];
156
157
    /**
158
     * 验证失败错误信息
159
     * @var string|array
160
     */
161
    protected $error = [];
162
163
    /**
164
     * 是否批量验证
165
     * @var bool
166
     */
167
    protected $batch = false;
168
169
    /**
170
     * 验证失败是否抛出异常
171
     * @var bool
172
     */
173
    protected $failException = false;
174
175
    /**
176
     * 场景需要验证的规则
177
     * @var array
178
     */
179
    protected $only = [];
180
181
    /**
182
     * 场景需要移除的验证规则
183
     * @var array
184
     */
185
    protected $remove = [];
186
187
    /**
188
     * 场景需要追加的验证规则
189
     * @var array
190
     */
191
    protected $append = [];
192
193
    /**
194
     * 验证正则定义
195
     * @var array
196
     */
197
    protected $regex = [];
198
199
    /**
200
     * Db对象
201
     * @var Db
202
     */
203
    protected $db;
204
205
    /**
206
     * 语言对象
207
     * @var Lang
208
     */
209
    protected $lang;
210
211
    /**
212
     * 请求对象
213
     * @var Request
214
     */
215
    protected $request;
216
217
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
218
     * @var Closure[]
219
     */
220
    protected static $maker = [];
221
222
    /**
223
     * 构造方法
224
     * @access public
225
     */
226
    public function __construct()
227
    {
228
        if (!empty(static::$maker)) {
229
            foreach (static::$maker as $maker) {
230
                call_user_func($maker, $this);
231
            }
232
        }
233
    }
234
235
    /**
236
     * 设置服务注入
237
     * @access public
238
     * @param Closure $maker
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
239
     * @return void
240
     */
241
    public static function maker(Closure $maker)
242
    {
243
        static::$maker[] = $maker;
244
    }
245
246
    /**
247
     * 设置Lang对象
248
     * @access public
249
     * @param Lang $lang Lang对象
250
     * @return void
251
     */
252
    public function setLang(Lang $lang)
253
    {
254
        $this->lang = $lang;
255
    }
256
257
    /**
258
     * 设置Db对象
259
     * @access public
260
     * @param Db $db Db对象
261
     * @return void
262
     */
263
    public function setDb(Db $db)
264
    {
265
        $this->db = $db;
266
    }
267
268
    /**
269
     * 设置Request对象
270
     * @access public
271
     * @param Request $request Request对象
272
     * @return void
273
     */
274
    public function setRequest(Request $request)
275
    {
276
        $this->request = $request;
277
    }
278
279
    /**
280
     * 添加字段验证规则
281
     * @access protected
282
     * @param string|array $name 字段名称或者规则数组
283
     * @param mixed        $rule 验证规则或者字段描述信息
284
     * @return $this
285
     */
286
    public function rule($name, $rule = '')
287
    {
288
        if (is_array($name)) {
289
            $this->rule = $name + $this->rule;
290
            if (is_array($rule)) {
291
                $this->field = array_merge($this->field, $rule);
292
            }
293
        } else {
294
            $this->rule[$name] = $rule;
295
        }
296
297
        return $this;
298
    }
299
300
    /**
301
     * 注册验证(类型)规则
302
     * @access public
303
     * @param string   $type     验证规则类型
304
     * @param callable $callback callback方法(或闭包)
305
     * @param string   $message  验证失败提示信息
306
     * @return $this
307
     */
308
    public function extend(string $type, callable $callback = null, string $message = null)
309
    {
310
        $this->type[$type] = $callback;
311
312
        if ($message) {
313
            $this->typeMsg[$type] = $message;
314
        }
315
316
        return $this;
317
    }
318
319
    /**
320
     * 设置验证规则的默认提示信息
321
     * @access public
322
     * @param string|array $type 验证规则类型名称或者数组
323
     * @param string       $msg  验证提示信息
324
     * @return void
325
     */
326
    public function setTypeMsg($type, string $msg = null): void
327
    {
328
        if (is_array($type)) {
329
            $this->typeMsg = array_merge($this->typeMsg, $type);
330
        } else {
331
            $this->typeMsg[$type] = $msg;
332
        }
333
    }
334
335
    /**
336
     * 设置提示信息
337
     * @access public
338
     * @param array $message 错误信息
339
     * @return Validate
340
     */
341
    public function message(array $message)
342
    {
343
        $this->message = array_merge($this->message, $message);
344
345
        return $this;
346
    }
347
348
    /**
349
     * 设置验证场景
350
     * @access public
351
     * @param string $name 场景名
352
     * @return $this
353
     */
354
    public function scene(string $name)
355
    {
356
        // 设置当前场景
357
        $this->currentScene = $name;
358
359
        return $this;
360
    }
361
362
    /**
363
     * 判断是否存在某个验证场景
364
     * @access public
365
     * @param string $name 场景名
366
     * @return bool
367
     */
368
    public function hasScene(string $name): bool
369
    {
370
        return isset($this->scene[$name]) || method_exists($this, 'scene' . $name);
371
    }
372
373
    /**
374
     * 设置批量验证
375
     * @access public
376
     * @param bool $batch 是否批量验证
377
     * @return $this
378
     */
379
    public function batch(bool $batch = true)
380
    {
381
        $this->batch = $batch;
382
383
        return $this;
384
    }
385
386
    /**
387
     * 设置验证失败后是否抛出异常
388
     * @access protected
389
     * @param bool $fail 是否抛出异常
390
     * @return $this
391
     */
392
    public function failException(bool $fail = true)
393
    {
394
        $this->failException = $fail;
395
396
        return $this;
397
    }
398
399
    /**
400
     * 指定需要验证的字段列表
401
     * @access public
402
     * @param array $fields 字段名
403
     * @return $this
404
     */
405
    public function only(array $fields)
406
    {
407
        $this->only = $fields;
408
409
        return $this;
410
    }
411
412
    /**
413
     * 移除某个字段的验证规则
414
     * @access public
415
     * @param string|array $field 字段名
416
     * @param mixed        $rule  验证规则 true 移除所有规则
417
     * @return $this
418
     */
419
    public function remove($field, $rule = null)
420
    {
421
        if (is_array($field)) {
422
            foreach ($field as $key => $rule) {
423
                if (is_int($key)) {
424
                    $this->remove($rule);
425
                } else {
426
                    $this->remove($key, $rule);
427
                }
428
            }
429
        } else {
430
            if (is_string($rule)) {
431
                $rule = explode('|', $rule);
432
            }
433
434
            $this->remove[$field] = $rule;
435
        }
436
437
        return $this;
438
    }
439
440
    /**
441
     * 追加某个字段的验证规则
442
     * @access public
443
     * @param string|array $field 字段名
444
     * @param mixed        $rule  验证规则
445
     * @return $this
446
     */
447
    public function append($field, $rule = null)
448
    {
449
        if (is_array($field)) {
450
            foreach ($field as $key => $rule) {
451
                $this->append($key, $rule);
452
            }
453
        } else {
454
            if (is_string($rule)) {
455
                $rule = explode('|', $rule);
456
            }
457
458
            $this->append[$field] = $rule;
459
        }
460
461
        return $this;
462
    }
463
464
    /**
465
     * 数据自动验证
466
     * @access public
467
     * @param array $data  数据
468
     * @param array $rules 验证规则
469
     * @return bool
470
     */
471
    public function check(array $data, array $rules = []): bool
472
    {
473
        $this->error = [];
474
475
        if (empty($rules)) {
476
            // 读取验证规则
477
            $rules = $this->rule;
478
        }
479
480
        if ($this->currentScene) {
481
            $this->getScene($this->currentScene);
482
        }
483
484
        foreach ($this->append as $key => $rule) {
485
            if (!isset($rules[$key])) {
486
                $rules[$key] = $rule;
487
            }
488
        }
489
490
        foreach ($rules as $key => $rule) {
491
            // field => 'rule1|rule2...' field => ['rule1','rule2',...]
492
            if (strpos($key, '|')) {
493
                // 字段|描述 用于指定属性名称
494
                [$key, $title] = explode('|', $key);
495
            } else {
496
                $title = $this->field[$key] ?? $key;
497
            }
498
499
            // 场景检测
500
            if (!empty($this->only) && !in_array($key, $this->only)) {
501
                continue;
502
            }
503
504
            // 获取数据 支持二维数组
505
            $value = $this->getDataValue($data, $key);
506
507
            // 字段验证
508
            if ($rule instanceof Closure) {
509
                $result = call_user_func_array($rule, [$value, $data]);
510
            } elseif ($rule instanceof ValidateRule) {
511
                //  验证因子
512
                $result = $this->checkItem($key, $value, $rule->getRule(), $data, $rule->getTitle() ?: $title, $rule->getMsg());
513
            } else {
514
                $result = $this->checkItem($key, $value, $rule, $data, $title);
515
            }
516
517
            if (true !== $result) {
518
                // 没有返回true 则表示验证失败
519
                if (!empty($this->batch)) {
520
                    // 批量验证
521
                    $this->error[$key] = $result;
522
                } elseif ($this->failException) {
523
                    throw new ValidateException($result);
524
                } else {
525
                    $this->error = $result;
526
                    return false;
527
                }
528
            }
529
        }
530
531
        if (!empty($this->error)) {
532
            if ($this->failException) {
533
                throw new ValidateException($this->error);
534
            }
535
            return false;
536
        }
537
538
        return true;
539
    }
540
541
    /**
542
     * 根据验证规则验证数据
543
     * @access public
544
     * @param mixed $value 字段值
545
     * @param mixed $rules 验证规则
546
     * @return bool
547
     */
548
    public function checkRule($value, $rules): bool
549
    {
550
        if ($rules instanceof Closure) {
551
            return call_user_func_array($rules, [$value]);
552
        } elseif ($rules instanceof ValidateRule) {
553
            $rules = $rules->getRule();
554
        } elseif (is_string($rules)) {
555
            $rules = explode('|', $rules);
556
        }
557
558
        foreach ($rules as $key => $rule) {
559
            if ($rule instanceof Closure) {
560
                $result = call_user_func_array($rule, [$value]);
561
            } else {
562
                // 判断验证类型
563
                [$type, $rule] = $this->getValidateType($key, $rule);
564
565
                $callback = $this->type[$type] ?? [$this, $type];
566
567
                $result = call_user_func_array($callback, [$value, $rule]);
568
            }
569
570
            if (true !== $result) {
571
                if ($this->failException) {
572
                    throw new ValidateException($result);
573
                }
574
575
                return $result;
576
            }
577
        }
578
579
        return true;
580
    }
581
582
    /**
583
     * 验证单个字段规则
584
     * @access protected
585
     * @param string $field 字段名
586
     * @param mixed  $value 字段值
587
     * @param mixed  $rules 验证规则
588
     * @param array  $data  数据
589
     * @param string $title 字段描述
590
     * @param array  $msg   提示信息
591
     * @return mixed
592
     */
593
    protected function checkItem(string $field, $value, $rules, $data, string $title = '', array $msg = [])
594
    {
595
        if (isset($this->remove[$field]) && true === $this->remove[$field] && empty($this->append[$field])) {
596
            // 字段已经移除 无需验证
597
            return true;
598
        }
599
600
        // 支持多规则验证 require|in:a,b,c|... 或者 ['require','in'=>'a,b,c',...]
601
        if (is_string($rules)) {
602
            $rules = explode('|', $rules);
603
        }
604
605
        if (isset($this->append[$field])) {
606
            // 追加额外的验证规则
607
            $rules = array_unique(array_merge($rules, $this->append[$field]), SORT_REGULAR);
608
        }
609
610
        $i = 0;
611
        foreach ($rules as $key => $rule) {
612
            if ($rule instanceof Closure) {
613
                $result = call_user_func_array($rule, [$value, $data]);
614
                $info   = is_numeric($key) ? '' : $key;
615
            } else {
616
                // 判断验证类型
617
                [$type, $rule, $info] = $this->getValidateType($key, $rule);
618
619
                if (isset($this->append[$field]) && in_array($info, $this->append[$field])) {
620
621
                } elseif (isset($this->remove[$field]) && in_array($info, $this->remove[$field])) {
622
                    // 规则已经移除
623
                    $i++;
624
                    continue;
625
                }
626
627
                if (isset($this->type[$type])) {
628
                    $result = call_user_func_array($this->type[$type], [$value, $rule, $data, $field, $title]);
629
                } elseif ('must' == $info || 0 === strpos($info, 'require') || (!is_null($value) && '' !== $value)) {
630
                    $result = call_user_func_array([$this, $type], [$value, $rule, $data, $field, $title]);
631
                } else {
632
                    $result = true;
633
                }
634
            }
635
636
            if (false === $result) {
637
                // 验证失败 返回错误信息
638
                if (!empty($msg[$i])) {
639
                    $message = $msg[$i];
640
                    if (is_string($message) && strpos($message, '{%') === 0) {
641
                        $message = $this->lang->get(substr($message, 2, -1));
642
                    }
643
                } else {
644
                    $message = $this->getRuleMsg($field, $title, $info, $rule);
645
                }
646
647
                return $message;
648
            } elseif (true !== $result) {
649
                // 返回自定义错误信息
650
                if (is_string($result) && false !== strpos($result, ':')) {
651
                    $result = str_replace(':attribute', $title, $result);
652
653
                    if (strpos($result, ':rule') && is_scalar($rule)) {
654
                        $result = str_replace(':rule', (string) $rule, $result);
655
                    }
656
                }
657
658
                return $result;
659
            }
660
            $i++;
661
        }
662
663
        return $result;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $result does not seem to be defined for all execution paths leading up to this point.
Loading history...
664
    }
665
666
    /**
667
     * 获取当前验证类型及规则
668
     * @access public
669
     * @param mixed $key
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
670
     * @param mixed $rule
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
671
     * @return array
672
     */
673
    protected function getValidateType($key, $rule): array
674
    {
675
        // 判断验证类型
676
        if (!is_numeric($key)) {
677
            if (isset($this->alias[$key])) {
678
                // 判断别名
679
                $key = $this->alias[$key];
680
            }
681
            return [$key, $rule, $key];
682
        }
683
684
        if (strpos($rule, ':')) {
685
            [$type, $rule] = explode(':', $rule, 2);
686
            if (isset($this->alias[$type])) {
687
                // 判断别名
688
                $type = $this->alias[$type];
689
            }
690
            $info = $type;
691
        } elseif (method_exists($this, $rule)) {
692
            $type = $rule;
693
            $info = $rule;
694
            $rule = '';
695
        } else {
696
            $type = 'is';
697
            $info = $rule;
698
        }
699
700
        return [$type, $rule, $info];
701
    }
702
703
    /**
704
     * 验证是否和某个字段的值一致
705
     * @access public
706
     * @param mixed  $value 字段值
707
     * @param mixed  $rule  验证规则
708
     * @param array  $data  数据
709
     * @param string $field 字段名
710
     * @return bool
711
     */
712
    public function confirm($value, $rule, array $data = [], string $field = ''): bool
713
    {
714
        if ('' == $rule) {
715
            if (strpos($field, '_confirm')) {
716
                $rule = strstr($field, '_confirm', true);
717
            } else {
718
                $rule = $field . '_confirm';
719
            }
720
        }
721
722
        return $this->getDataValue($data, $rule) === $value;
723
    }
724
725
    /**
726
     * 验证是否和某个字段的值是否不同
727
     * @access public
728
     * @param mixed $value 字段值
729
     * @param mixed $rule  验证规则
730
     * @param array $data  数据
731
     * @return bool
732
     */
733
    public function different($value, $rule, array $data = []): bool
734
    {
735
        return $this->getDataValue($data, $rule) != $value;
736
    }
737
738
    /**
739
     * 验证是否大于等于某个值
740
     * @access public
741
     * @param mixed $value 字段值
742
     * @param mixed $rule  验证规则
743
     * @param array $data  数据
744
     * @return bool
745
     */
746
    public function egt($value, $rule, array $data = []): bool
747
    {
748
        return $value >= $this->getDataValue($data, $rule);
749
    }
750
751
    /**
752
     * 验证是否大于某个值
753
     * @access public
754
     * @param mixed $value 字段值
755
     * @param mixed $rule  验证规则
756
     * @param array $data  数据
757
     * @return bool
758
     */
759
    public function gt($value, $rule, array $data = []): bool
760
    {
761
        return $value > $this->getDataValue($data, $rule);
762
    }
763
764
    /**
765
     * 验证是否小于等于某个值
766
     * @access public
767
     * @param mixed $value 字段值
768
     * @param mixed $rule  验证规则
769
     * @param array $data  数据
770
     * @return bool
771
     */
772
    public function elt($value, $rule, array $data = []): bool
773
    {
774
        return $value <= $this->getDataValue($data, $rule);
775
    }
776
777
    /**
778
     * 验证是否小于某个值
779
     * @access public
780
     * @param mixed $value 字段值
781
     * @param mixed $rule  验证规则
782
     * @param array $data  数据
783
     * @return bool
784
     */
785
    public function lt($value, $rule, array $data = []): bool
786
    {
787
        return $value < $this->getDataValue($data, $rule);
788
    }
789
790
    /**
791
     * 验证是否等于某个值
792
     * @access public
793
     * @param mixed $value 字段值
794
     * @param mixed $rule  验证规则
795
     * @return bool
796
     */
797
    public function eq($value, $rule): bool
798
    {
799
        return $value == $rule;
800
    }
801
802
    /**
803
     * 必须验证
804
     * @access public
805
     * @param mixed $value 字段值
806
     * @param mixed $rule  验证规则
807
     * @return bool
808
     */
809
    public function must($value, $rule = null): bool
810
    {
811
        return !empty($value) || '0' == $value;
812
    }
813
814
    /**
815
     * 验证字段值是否为有效格式
816
     * @access public
817
     * @param mixed  $value 字段值
818
     * @param string $rule  验证规则
819
     * @param array  $data  数据
820
     * @return bool
821
     */
822
    public function is($value, string $rule, array $data = []): bool
823
    {
824
        switch (Str::camel($rule)) {
825
            case 'require':
826
                // 必须
827
                $result = !empty($value) || '0' == $value;
828
                break;
829
            case 'accepted':
830
                // 接受
831
                $result = in_array($value, ['1', 'on', 'yes']);
832
                break;
833
            case 'date':
834
                // 是否是一个有效日期
835
                $result = false !== strtotime($value);
836
                break;
837
            case 'activeUrl':
838
                // 是否为有效的网址
839
                $result = checkdnsrr($value);
840
                break;
841
            case 'boolean':
842
            case 'bool':
843
                // 是否为布尔值
844
                $result = in_array($value, [true, false, 0, 1, '0', '1'], true);
845
                break;
846
            case 'number':
847
                $result = ctype_digit((string) $value);
848
                break;
849
            case 'alphaNum':
850
                $result = ctype_alnum($value);
851
                break;
852
            case 'array':
853
                // 是否为数组
854
                $result = is_array($value);
855
                break;
856
            case 'file':
857
                $result = $value instanceof File;
858
                break;
859
            case 'image':
860
                $result = $value instanceof File && in_array($this->getImageType($value->getRealPath()), [1, 2, 3, 6]);
861
                break;
862
            case 'token':
863
                $result = $this->token($value, '__token__', $data);
864
                break;
865
            default:
866
                if (isset($this->type[$rule])) {
867
                    // 注册的验证规则
868
                    $result = call_user_func_array($this->type[$rule], [$value]);
869
                } elseif (function_exists('ctype_' . $rule)) {
870
                    // ctype验证规则
871
                    $ctypeFun = 'ctype_' . $rule;
872
                    $result   = $ctypeFun($value);
873
                } elseif (isset($this->filter[$rule])) {
874
                    // Filter_var验证规则
875
                    $result = $this->filter($value, $this->filter[$rule]);
876
                } else {
877
                    // 正则验证
878
                    $result = $this->regex($value, $rule);
879
                }
880
        }
881
882
        return $result;
883
    }
884
885
    // 判断图像类型
886
    protected function getImageType($image)
0 ignored issues
show
Coding Style introduced by
You must use "/**" style comments for a function comment
Loading history...
887
    {
888
        if (function_exists('exif_imagetype')) {
889
            return exif_imagetype($image);
890
        }
891
892
        try {
893
            $info = getimagesize($image);
894
            return $info ? $info[2] : false;
895
        } catch (\Exception $e) {
896
            return false;
897
        }
898
    }
899
900
    /**
901
     * 验证表单令牌
902
     * @access public
903
     * @param mixed $value 字段值
904
     * @param mixed $rule  验证规则
905
     * @param array $data  数据
906
     * @return bool
907
     */
908
    public function token($value, string $rule, array $data): bool
909
    {
910
        $rule = !empty($rule) ? $rule : '__token__';
911
        return $this->request->checkToken($rule, $data);
912
    }
913
914
    /**
915
     * 验证是否为合格的域名或者IP 支持A,MX,NS,SOA,PTR,CNAME,AAAA,A6, SRV,NAPTR,TXT 或者 ANY类型
916
     * @access public
917
     * @param mixed $value 字段值
918
     * @param mixed $rule  验证规则
919
     * @return bool
920
     */
921
    public function activeUrl(string $value, string $rule = 'MX'): bool
922
    {
923
        if (!in_array($rule, ['A', 'MX', 'NS', 'SOA', 'PTR', 'CNAME', 'AAAA', 'A6', 'SRV', 'NAPTR', 'TXT', 'ANY'])) {
924
            $rule = 'MX';
925
        }
926
927
        return checkdnsrr($value, $rule);
928
    }
929
930
    /**
931
     * 验证是否有效IP
932
     * @access public
933
     * @param mixed $value 字段值
934
     * @param mixed $rule  验证规则 ipv4 ipv6
935
     * @return bool
936
     */
937
    public function ip($value, string $rule = 'ipv4'): bool
938
    {
939
        if (!in_array($rule, ['ipv4', 'ipv6'])) {
940
            $rule = 'ipv4';
941
        }
942
943
        return $this->filter($value, [FILTER_VALIDATE_IP, 'ipv6' == $rule ? FILTER_FLAG_IPV6 : FILTER_FLAG_IPV4]);
944
    }
945
946
    /**
947
     * 检测上传文件后缀
948
     * @access public
949
     * @param File         $file
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
950
     * @param array|string $ext 允许后缀
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
951
     * @return bool
952
     */
953
    protected function checkExt(File $file, $ext): bool
954
    {
955
        if (is_string($ext)) {
956
            $ext = explode(',', $ext);
957
        }
958
959
        return in_array(strtolower($file->extension()), $ext);
960
    }
961
962
    /**
963
     * 检测上传文件大小
964
     * @access public
965
     * @param File    $file
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
966
     * @param integer $size 最大大小
967
     * @return bool
968
     */
969
    protected function checkSize(File $file, $size): bool
970
    {
971
        return $file->getSize() <= (int) $size;
972
    }
973
974
    /**
975
     * 检测上传文件类型
976
     * @access public
977
     * @param File         $file
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
978
     * @param array|string $mime 允许类型
979
     * @return bool
980
     */
981
    protected function checkMime(File $file, $mime): bool
982
    {
983
        if (is_string($mime)) {
984
            $mime = explode(',', $mime);
985
        }
986
987
        return in_array(strtolower($file->getMime()), $mime);
988
    }
989
990
    /**
991
     * 验证上传文件后缀
992
     * @access public
993
     * @param mixed $file 上传文件
994
     * @param mixed $rule 验证规则
995
     * @return bool
996
     */
997
    public function fileExt($file, $rule): bool
998
    {
999
        if (is_array($file)) {
1000
            foreach ($file as $item) {
1001
                if (!($item instanceof File) || !$this->checkExt($item, $rule)) {
1002
                    return false;
1003
                }
1004
            }
1005
            return true;
1006
        } elseif ($file instanceof File) {
1007
            return $this->checkExt($file, $rule);
1008
        }
1009
1010
        return false;
1011
    }
1012
1013
    /**
1014
     * 验证上传文件类型
1015
     * @access public
1016
     * @param mixed $file 上传文件
1017
     * @param mixed $rule 验证规则
1018
     * @return bool
1019
     */
1020
    public function fileMime($file, $rule): bool
1021
    {
1022
        if (is_array($file)) {
1023
            foreach ($file as $item) {
1024
                if (!($item instanceof File) || !$this->checkMime($item, $rule)) {
1025
                    return false;
1026
                }
1027
            }
1028
            return true;
1029
        } elseif ($file instanceof File) {
1030
            return $this->checkMime($file, $rule);
1031
        }
1032
1033
        return false;
1034
    }
1035
1036
    /**
1037
     * 验证上传文件大小
1038
     * @access public
1039
     * @param mixed $file 上传文件
1040
     * @param mixed $rule 验证规则
1041
     * @return bool
1042
     */
1043
    public function fileSize($file, $rule): bool
1044
    {
1045
        if (is_array($file)) {
1046
            foreach ($file as $item) {
1047
                if (!($item instanceof File) || !$this->checkSize($item, $rule)) {
1048
                    return false;
1049
                }
1050
            }
1051
            return true;
1052
        } elseif ($file instanceof File) {
1053
            return $this->checkSize($file, $rule);
1054
        }
1055
1056
        return false;
1057
    }
1058
1059
    /**
1060
     * 验证图片的宽高及类型
1061
     * @access public
1062
     * @param mixed $file 上传文件
1063
     * @param mixed $rule 验证规则
1064
     * @return bool
1065
     */
1066
    public function image($file, $rule): bool
1067
    {
1068
        if (!($file instanceof File)) {
1069
            return false;
1070
        }
1071
1072
        if ($rule) {
1073
            $rule = explode(',', $rule);
1074
1075
            [$width, $height, $type] = getimagesize($file->getRealPath());
1076
1077
            if (isset($rule[2])) {
1078
                $imageType = strtolower($rule[2]);
1079
1080
                if ('jpg' == $imageType) {
1081
                    $imageType = 'jpeg';
1082
                }
1083
1084
                if (image_type_to_extension($type, false) != $imageType) {
1085
                    return false;
1086
                }
1087
            }
1088
1089
            [$w, $h] = $rule;
1090
1091
            return $w == $width && $h == $height;
1092
        }
1093
1094
        return in_array($this->getImageType($file->getRealPath()), [1, 2, 3, 6]);
1095
    }
1096
1097
    /**
1098
     * 验证时间和日期是否符合指定格式
1099
     * @access public
1100
     * @param mixed $value 字段值
1101
     * @param mixed $rule  验证规则
1102
     * @return bool
1103
     */
1104
    public function dateFormat($value, $rule): bool
1105
    {
1106
        $info = date_parse_from_format($rule, $value);
1107
        return 0 == $info['warning_count'] && 0 == $info['error_count'];
1108
    }
1109
1110
    /**
1111
     * 验证是否唯一
1112
     * @access public
1113
     * @param mixed  $value 字段值
1114
     * @param mixed  $rule  验证规则 格式:数据表,字段名,排除ID,主键名
1115
     * @param array  $data  数据
1116
     * @param string $field 验证字段名
1117
     * @return bool
1118
     */
1119
    public function unique($value, $rule, array $data = [], string $field = ''): bool
1120
    {
1121
        if (is_string($rule)) {
1122
            $rule = explode(',', $rule);
1123
        }
1124
1125
        if (false !== strpos($rule[0], '\\')) {
1126
            // 指定模型类
1127
            $db = new $rule[0];
1128
        } else {
1129
            $db = $this->db->name($rule[0]);
0 ignored issues
show
Bug introduced by
The method name() does not exist on think\Db. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1129
            /** @scrutinizer ignore-call */ 
1130
            $db = $this->db->name($rule[0]);
Loading history...
1130
        }
1131
1132
        $key = $rule[1] ?? $field;
1133
        $map = [];
1134
1135
        if (strpos($key, '^')) {
1136
            // 支持多个字段验证
1137
            $fields = explode('^', $key);
1138
            foreach ($fields as $key) {
1139
                if (isset($data[$key])) {
1140
                    $map[] = [$key, '=', $data[$key]];
1141
                }
1142
            }
1143
        } elseif (strpos($key, '=')) {
1144
            // 支持复杂验证条件
1145
            $fields = explode('&', $key);
1146
            $map_arr=[];
1147
            foreach ($fields as $key) {
1148
                $str_map=explode('=', $key);
1149
                $map[] = [$str_map[0], '=', $str_map[1]];
1150
                $map_arr[]=$str_map[0];
1151
            }
1152
            if(!in_array($field, $map_arr)){
0 ignored issues
show
Coding Style introduced by
Expected "if (...) {\n"; found "if(...){\n"
Loading history...
Coding Style introduced by
There must be a single space between the closing parenthesis and the opening brace of a multi-line IF statement; found 0 spaces
Loading history...
1153
                $map[]=[$field,'=',$data[$field]];
1154
            }
1155
        } elseif (isset($data[$field])) {
1156
            $map[] = [$key, '=', $data[$field]];
1157
        } else {
1158
            $map = [];
1159
        }
1160
1161
        $pk = !empty($rule[3]) ? $rule[3] : $db->getPk();
1162
1163
        if (is_string($pk)) {
1164
            if (isset($rule[2])) {
1165
                $map[] = [$pk, '<>', $rule[2]];
1166
            } elseif (isset($data[$pk])) {
1167
                $map[] = [$pk, '<>', $data[$pk]];
1168
            }
1169
        }
1170
1171
        if ($db->where($map)->field($pk)->find()) {
1172
            return false;
1173
        }
1174
1175
        return true;
1176
    }
1177
1178
    /**
1179
     * 使用filter_var方式验证
1180
     * @access public
1181
     * @param mixed $value 字段值
1182
     * @param mixed $rule  验证规则
1183
     * @return bool
1184
     */
1185
    public function filter($value, $rule): bool
1186
    {
1187
        if (is_string($rule) && strpos($rule, ',')) {
1188
            [$rule, $param] = explode(',', $rule);
1189
        } elseif (is_array($rule)) {
1190
            $param = $rule[1] ?? null;
1191
            $rule  = $rule[0];
1192
        } else {
1193
            $param = null;
1194
        }
1195
1196
        return false !== filter_var($value, is_int($rule) ? $rule : filter_id($rule), $param);
1197
    }
1198
1199
    /**
1200
     * 验证某个字段等于某个值的时候必须
1201
     * @access public
1202
     * @param mixed $value 字段值
1203
     * @param mixed $rule  验证规则
1204
     * @param array $data  数据
1205
     * @return bool
1206
     */
1207
    public function requireIf($value, $rule, array $data = []): bool
1208
    {
1209
        [$field, $val] = explode(',', $rule);
1210
1211
        if ($this->getDataValue($data, $field) == $val) {
1212
            return !empty($value) || '0' == $value;
1213
        }
1214
1215
        return true;
1216
    }
1217
1218
    /**
1219
     * 通过回调方法验证某个字段是否必须
1220
     * @access public
1221
     * @param mixed $value 字段值
1222
     * @param mixed $rule  验证规则
1223
     * @param array $data  数据
1224
     * @return bool
1225
     */
1226
    public function requireCallback($value, $rule, array $data = []): bool
1227
    {
1228
        $result = call_user_func_array([$this, $rule], [$value, $data]);
1229
1230
        if ($result) {
1231
            return !empty($value) || '0' == $value;
1232
        }
1233
1234
        return true;
1235
    }
1236
1237
    /**
1238
     * 验证某个字段有值的情况下必须
1239
     * @access public
1240
     * @param mixed $value 字段值
1241
     * @param mixed $rule  验证规则
1242
     * @param array $data  数据
1243
     * @return bool
1244
     */
1245
    public function requireWith($value, $rule, array $data = []): bool
1246
    {
1247
        $val = $this->getDataValue($data, $rule);
1248
1249
        if (!empty($val)) {
1250
            return !empty($value) || '0' == $value;
1251
        }
1252
1253
        return true;
1254
    }
1255
1256
    /**
1257
     * 验证某个字段没有值的情况下必须
1258
     * @access public
1259
     * @param mixed $value 字段值
1260
     * @param mixed $rule  验证规则
1261
     * @param array $data  数据
1262
     * @return bool
1263
     */
1264
    public function requireWithout($value, $rule, array $data = []): bool
1265
    {
1266
        $val = $this->getDataValue($data, $rule);
1267
1268
        if (empty($val)) {
1269
            return !empty($value) || '0' == $value;
1270
        }
1271
1272
        return true;
1273
    }
1274
1275
    /**
1276
     * 验证是否在范围内
1277
     * @access public
1278
     * @param mixed $value 字段值
1279
     * @param mixed $rule  验证规则
1280
     * @return bool
1281
     */
1282
    public function in($value, $rule): bool
1283
    {
1284
        return in_array($value, is_array($rule) ? $rule : explode(',', $rule));
1285
    }
1286
1287
    /**
1288
     * 验证是否不在某个范围
1289
     * @access public
1290
     * @param mixed $value 字段值
1291
     * @param mixed $rule  验证规则
1292
     * @return bool
1293
     */
1294
    public function notIn($value, $rule): bool
1295
    {
1296
        return !in_array($value, is_array($rule) ? $rule : explode(',', $rule));
1297
    }
1298
1299
    /**
1300
     * between验证数据
0 ignored issues
show
Coding Style introduced by
Doc comment short description must start with a capital letter
Loading history...
1301
     * @access public
1302
     * @param mixed $value 字段值
1303
     * @param mixed $rule  验证规则
1304
     * @return bool
1305
     */
1306
    public function between($value, $rule): bool
1307
    {
1308
        if (is_string($rule)) {
1309
            $rule = explode(',', $rule);
1310
        }
1311
        [$min, $max] = $rule;
1312
1313
        return $value >= $min && $value <= $max;
1314
    }
1315
1316
    /**
1317
     * 使用notbetween验证数据
1318
     * @access public
1319
     * @param mixed $value 字段值
1320
     * @param mixed $rule  验证规则
1321
     * @return bool
1322
     */
1323
    public function notBetween($value, $rule): bool
1324
    {
1325
        if (is_string($rule)) {
1326
            $rule = explode(',', $rule);
1327
        }
1328
        [$min, $max] = $rule;
1329
1330
        return $value < $min || $value > $max;
1331
    }
1332
1333
    /**
1334
     * 验证数据长度
1335
     * @access public
1336
     * @param mixed $value 字段值
1337
     * @param mixed $rule  验证规则
1338
     * @return bool
1339
     */
1340
    public function length($value, $rule): bool
1341
    {
1342
        if (is_array($value)) {
1343
            $length = count($value);
1344
        } elseif ($value instanceof File) {
1345
            $length = $value->getSize();
1346
        } else {
1347
            $length = mb_strlen((string) $value);
1348
        }
1349
1350
        if (is_string($rule) && strpos($rule, ',')) {
1351
            // 长度区间
1352
            [$min, $max] = explode(',', $rule);
1353
            return $length >= $min && $length <= $max;
1354
        }
1355
1356
        // 指定长度
1357
        return $length == $rule;
1358
    }
1359
1360
    /**
1361
     * 验证数据最大长度
1362
     * @access public
1363
     * @param mixed $value 字段值
1364
     * @param mixed $rule  验证规则
1365
     * @return bool
1366
     */
1367
    public function max($value, $rule): bool
1368
    {
1369
        if (is_array($value)) {
1370
            $length = count($value);
1371
        } elseif ($value instanceof File) {
1372
            $length = $value->getSize();
1373
        } else {
1374
            $length = mb_strlen((string) $value);
1375
        }
1376
1377
        return $length <= $rule;
1378
    }
1379
1380
    /**
1381
     * 验证数据最小长度
1382
     * @access public
1383
     * @param mixed $value 字段值
1384
     * @param mixed $rule  验证规则
1385
     * @return bool
1386
     */
1387
    public function min($value, $rule): bool
1388
    {
1389
        if (is_array($value)) {
1390
            $length = count($value);
1391
        } elseif ($value instanceof File) {
1392
            $length = $value->getSize();
1393
        } else {
1394
            $length = mb_strlen((string) $value);
1395
        }
1396
1397
        return $length >= $rule;
1398
    }
1399
1400
    /**
1401
     * 验证日期
1402
     * @access public
1403
     * @param mixed $value 字段值
1404
     * @param mixed $rule  验证规则
1405
     * @param array $data  数据
1406
     * @return bool
1407
     */
1408
    public function after($value, $rule, array $data = []): bool
1409
    {
1410
        return strtotime($value) >= strtotime($rule);
1411
    }
1412
1413
    /**
1414
     * 验证日期
1415
     * @access public
1416
     * @param mixed $value 字段值
1417
     * @param mixed $rule  验证规则
1418
     * @param array $data  数据
1419
     * @return bool
1420
     */
1421
    public function before($value, $rule, array $data = []): bool
1422
    {
1423
        return strtotime($value) <= strtotime($rule);
1424
    }
1425
1426
    /**
1427
     * 验证日期
1428
     * @access public
1429
     * @param mixed $value 字段值
1430
     * @param mixed $rule  验证规则
1431
     * @param array $data  数据
1432
     * @return bool
1433
     */
1434
    public function afterWith($value, $rule, array $data = []): bool
1435
    {
1436
        $rule = $this->getDataValue($data, $rule);
1437
        return !is_null($rule) && strtotime($value) >= strtotime($rule);
1438
    }
1439
1440
    /**
1441
     * 验证日期
1442
     * @access public
1443
     * @param mixed $value 字段值
1444
     * @param mixed $rule  验证规则
1445
     * @param array $data  数据
1446
     * @return bool
1447
     */
1448
    public function beforeWith($value, $rule, array $data = []): bool
1449
    {
1450
        $rule = $this->getDataValue($data, $rule);
1451
        return !is_null($rule) && strtotime($value) <= strtotime($rule);
1452
    }
1453
1454
    /**
1455
     * 验证有效期
1456
     * @access public
1457
     * @param mixed $value 字段值
1458
     * @param mixed $rule  验证规则
1459
     * @return bool
1460
     */
1461
    public function expire($value, $rule): bool
1462
    {
1463
        if (is_string($rule)) {
1464
            $rule = explode(',', $rule);
1465
        }
1466
1467
        [$start, $end] = $rule;
1468
1469
        if (!is_numeric($start)) {
1470
            $start = strtotime($start);
1471
        }
1472
1473
        if (!is_numeric($end)) {
1474
            $end = strtotime($end);
1475
        }
1476
1477
        return time() >= $start && time() <= $end;
1478
    }
1479
1480
    /**
1481
     * 验证IP许可
1482
     * @access public
1483
     * @param mixed $value 字段值
1484
     * @param mixed $rule  验证规则
1485
     * @return bool
1486
     */
1487
    public function allowIp($value, $rule): bool
1488
    {
1489
        return in_array($value, is_array($rule) ? $rule : explode(',', $rule));
1490
    }
1491
1492
    /**
1493
     * 验证IP禁用
1494
     * @access public
1495
     * @param mixed $value 字段值
1496
     * @param mixed $rule  验证规则
1497
     * @return bool
1498
     */
1499
    public function denyIp($value, $rule): bool
1500
    {
1501
        return !in_array($value, is_array($rule) ? $rule : explode(',', $rule));
1502
    }
1503
1504
    /**
1505
     * 使用正则验证数据
1506
     * @access public
1507
     * @param mixed $value 字段值
1508
     * @param mixed $rule  验证规则 正则规则或者预定义正则名
1509
     * @return bool
1510
     */
1511
    public function regex($value, $rule): bool
1512
    {
1513
        if (isset($this->regex[$rule])) {
1514
            $rule = $this->regex[$rule];
1515
        } elseif (isset($this->defaultRegex[$rule])) {
1516
            $rule = $this->defaultRegex[$rule];
1517
        }
1518
1519
        if (is_string($rule) && 0 !== strpos($rule, '/') && !preg_match('/\/[imsU]{0,4}$/', $rule)) {
1520
            // 不是正则表达式则两端补上/
1521
            $rule = '/^' . $rule . '$/';
1522
        }
1523
1524
        return is_scalar($value) && 1 === preg_match($rule, (string) $value);
1525
    }
1526
1527
    /**
1528
     * 获取错误信息
1529
     * @return array|string
1530
     */
1531
    public function getError()
1532
    {
1533
        return $this->error;
1534
    }
1535
1536
    /**
1537
     * 获取数据值
1538
     * @access protected
1539
     * @param array  $data 数据
1540
     * @param string $key  数据标识 支持二维
1541
     * @return mixed
1542
     */
1543
    protected function getDataValue(array $data, $key)
1544
    {
1545
        if (is_numeric($key)) {
1546
            $value = $key;
1547
        } elseif (is_string($key) && strpos($key, '.')) {
1548
            // 支持多维数组验证
1549
            foreach (explode('.', $key) as $key) {
0 ignored issues
show
introduced by
$key is overwriting one of the parameters of this function.
Loading history...
1550
                if (!isset($data[$key])) {
1551
                    $value = null;
1552
                    break;
1553
                }
1554
                $value = $data = $data[$key];
1555
            }
1556
        } else {
1557
            $value = $data[$key] ?? null;
1558
        }
1559
1560
        return $value;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $value does not seem to be defined for all execution paths leading up to this point.
Loading history...
1561
    }
1562
1563
    /**
1564
     * 获取验证规则的错误提示信息
1565
     * @access protected
1566
     * @param string $attribute 字段英文名
1567
     * @param string $title     字段描述名
1568
     * @param string $type      验证规则名称
1569
     * @param mixed  $rule      验证规则数据
1570
     * @return string|array
1571
     */
1572
    protected function getRuleMsg(string $attribute, string $title, string $type, $rule)
1573
    {
1574
        if (isset($this->message[$attribute . '.' . $type])) {
1575
            $msg = $this->message[$attribute . '.' . $type];
1576
        } elseif (isset($this->message[$attribute][$type])) {
1577
            $msg = $this->message[$attribute][$type];
1578
        } elseif (isset($this->message[$attribute])) {
1579
            $msg = $this->message[$attribute];
1580
        } elseif (isset($this->typeMsg[$type])) {
1581
            $msg = $this->typeMsg[$type];
1582
        } elseif (0 === strpos($type, 'require')) {
1583
            $msg = $this->typeMsg['require'];
1584
        } else {
1585
            $msg = $title . $this->lang->get('not conform to the rules');
1586
        }
1587
1588
        if (is_array($msg)) {
1589
            return $this->errorMsgIsArray($msg, $rule, $title);
1590
        }
1591
1592
        return $this->parseErrorMsg($msg, $rule, $title);
1593
    }
1594
1595
    /**
1596
     * 获取验证规则的错误提示信息
1597
     * @access protected
1598
     * @param string $msg   错误信息
1599
     * @param mixed  $rule  验证规则数据
1600
     * @param string $title 字段描述名
1601
     * @return string
1602
     */
1603
    protected function parseErrorMsg(string $msg, $rule, string $title)
1604
    {
1605
        if (0 === strpos($msg, '{%')) {
1606
            $msg = $this->lang->get(substr($msg, 2, -1));
1607
        } elseif ($this->lang->has($msg)) {
1608
            $msg = $this->lang->get($msg);
1609
        }
1610
1611
        if (is_array($msg)) {
1612
            return $this->errorMsgIsArray($msg, $rule, $title);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->errorMsgIs...ay($msg, $rule, $title) returns the type array which is incompatible with the documented return type string.
Loading history...
1613
        }
1614
1615
        if (is_scalar($rule) && false !== strpos($msg, ':')) {
1616
            // 变量替换
1617
            if (is_string($rule) && strpos($rule, ',')) {
1618
                $array = array_pad(explode(',', $rule), 3, '');
1619
            } else {
1620
                $array = array_pad([], 3, '');
1621
            }
1622
1623
            $msg = str_replace(
1624
                [':attribute', ':1', ':2', ':3'],
1625
                [$title, $array[0], $array[1], $array[2]],
1626
                $msg);
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 12 spaces, but found 16.
Loading history...
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
1627
1628
            if (strpos($msg, ':rule')) {
1629
                $msg = str_replace(':rule', (string) $rule, $msg);
1630
            }
1631
        }
1632
1633
        return $msg;
1634
    }
1635
1636
    /**
1637
     * 错误信息数组处理
1638
     * @access protected
1639
     * @param array $msg   错误信息
1640
     * @param mixed  $rule  验证规则数据
1641
     * @param string $title 字段描述名
1642
     * @return array
1643
     */
1644
    protected function errorMsgIsArray(array $msg, $rule, string $title)
1645
    {
1646
        foreach ($msg as $key => $val) {
1647
            if (is_string($val)) {
1648
                $msg[$key] = $this->parseErrorMsg($val, $rule, $title);
1649
            }
1650
        }
1651
        return $msg;
1652
    }
1653
1654
    /**
1655
     * 获取数据验证的场景
1656
     * @access protected
1657
     * @param string $scene 验证场景
1658
     * @return void
1659
     */
1660
    protected function getScene(string $scene): void
1661
    {
1662
        $this->only = $this->append = $this->remove = [];
1663
1664
        if (method_exists($this, 'scene' . $scene)) {
1665
            call_user_func([$this, 'scene' . $scene]);
1666
        } elseif (isset($this->scene[$scene])) {
1667
            // 如果设置了验证适用场景
1668
            $this->only = $this->scene[$scene];
1669
        }
1670
    }
1671
1672
    /**
1673
     * 动态方法 直接调用is方法进行验证
1674
     * @access public
1675
     * @param string $method 方法名
1676
     * @param array  $args   调用参数
1677
     * @return bool
1678
     */
1679
    public function __call($method, $args)
1680
    {
1681
        if ('is' == strtolower(substr($method, 0, 2))) {
1682
            $method = substr($method, 2);
1683
        }
1684
1685
        array_push($args, lcfirst($method));
1686
1687
        return call_user_func_array([$this, 'is'], $args);
1688
    }
1689
}
1690