Passed
Pull Request — 8.0 (#2893)
by
unknown
14:34
created

Validate::beforeWith()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 3
dl 0
loc 4
ccs 0
cts 2
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2023 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
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'         => '/^[\p{Han}]+$/u',
130
        'chsAlpha'    => '/^[\p{Han}a-zA-Z]+$/u',
131
        'chsAlphaNum' => '/^[\p{Han}a-zA-Z0-9]+$/u',
132
        'chsDash'     => '/^[\p{Han}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{3}$)/',
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
    /**
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
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(string|array $name, $rule = '')
287
    {
288
        if (is_array($name)) {
0 ignored issues
show
introduced by
The condition is_array($name) is always true.
Loading history...
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(string|array $type, string $msg = null): void
327
    {
328
        if (is_array($type)) {
0 ignored issues
show
introduced by
The condition is_array($type) is always true.
Loading history...
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(string|array $field, $rule = null)
420
    {
421
        if (is_array($field)) {
0 ignored issues
show
introduced by
The condition is_array($field) is always true.
Loading history...
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(string|array $field, $rule = null)
448
    {
449
        if (is_array($field)) {
0 ignored issues
show
introduced by
The condition is_array($field) is always true.
Loading history...
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 ($this->currentScene) {
476
            $this->getScene($this->currentScene);
477
        }
478
479
        if (empty($rules)) {
480
            // 读取验证规则
481
            $rules = $this->rule;
482
        }
483
484
        foreach ($this->append as $key => $rule) {
485
            if (!isset($rules[$key])) {
486
                $rules[$key] = $rule;
487
                unset($this->append[$key]);
488
            }
489
        }
490
491
        foreach ($rules as $key => $rule) {
492
            // field => 'rule1|rule2...' field => ['rule1','rule2',...]
493
            if (str_contains($key, '|')) {
494
                // 字段|描述 用于指定属性名称
495
                [$key, $title] = explode('|', $key);
496
            } else {
497
                $title = $this->field[$key] ?? $key;
498
            }
499
500
            // 场景检测
501
            if (!empty($this->only) && !in_array($key, $this->only)) {
502
                continue;
503
            }
504
505
            // 获取数据 支持二维数组
506
            $value = $this->getDataValue($data, $key);
507
508
            // 字段验证
509
            if ($rule instanceof Closure) {
510
                $result = call_user_func_array($rule, [$value, $data]);
511
            } elseif ($rule instanceof ValidateRule) {
512
                //  验证因子
513
                $result = $this->checkItem($key, $value, $rule->getRule(), $data, $rule->getTitle() ?: $title, $rule->getMsg());
514
            } else {
515
                $result = $this->checkItem($key, $value, $rule, $data, $title);
516
            }
517
518
            if (true !== $result) {
519
                // 没有返回true 则表示验证失败
520
                if (!empty($this->batch)) {
521
                    // 批量验证
522
                    $this->error[$key] = $result;
523
                } elseif ($this->failException) {
524
                    throw new ValidateException($result);
525
                } else {
526
                    $this->error = $result;
527
                    return false;
528
                }
529
            }
530
        }
531
532
        if (!empty($this->error)) {
533
            if ($this->failException) {
534
                throw new ValidateException($this->error);
535
            }
536
            return false;
537
        }
538
539
        return true;
540
    }
541
542
    /**
543
     * 根据验证规则验证数据
544
     * @access public
545
     * @param mixed $value 字段值
546
     * @param mixed $rules 验证规则
547
     * @return bool
548
     */
549
    public function checkRule($value, $rules): bool
550
    {
551
        if ($rules instanceof Closure) {
552
            return call_user_func_array($rules, [$value]);
553
        } elseif ($rules instanceof ValidateRule) {
554
            $rules = $rules->getRule();
555
        } elseif (is_string($rules)) {
556
            $rules = explode('|', $rules);
557
        }
558
559
        foreach ($rules as $key => $rule) {
560
            if ($rule instanceof Closure) {
561
                $result = call_user_func_array($rule, [$value]);
562
            } else {
563
                // 判断验证类型
564
                [$type, $rule] = $this->getValidateType($key, $rule);
565
566
                $callback = $this->type[$type] ?? [$this, $type];
567
568
                $result = call_user_func_array($callback, [$value, $rule]);
569
            }
570
571
            if (true !== $result) {
572
                if ($this->failException) {
573
                    throw new ValidateException($result);
574
                }
575
576
                return $result;
577
            }
578
        }
579
580
        return true;
581
    }
582
583
    /**
584
     * 验证单个字段规则
585
     * @access protected
586
     * @param string $field 字段名
587
     * @param mixed  $value 字段值
588
     * @param mixed  $rules 验证规则
589
     * @param array  $data  数据
590
     * @param string $title 字段描述
591
     * @param array  $msg   提示信息
592
     * @return mixed
593
     */
594
    protected function checkItem(string $field, $value, $rules, $data, string $title = '', array $msg = [])
595
    {
596
        if (isset($this->remove[$field]) && true === $this->remove[$field] && empty($this->append[$field])) {
597
            // 字段已经移除 无需验证
598
            return true;
599
        }
600
601
        // 支持多规则验证 require|in:a,b,c|... 或者 ['require','in'=>'a,b,c',...]
602
        if (is_string($rules)) {
603
            $rules = explode('|', $rules);
604
        }
605
606
        if (isset($this->append[$field])) {
607
            // 追加额外的验证规则
608
            $rules = array_unique(array_merge($rules, $this->append[$field]), SORT_REGULAR);
609
            unset($this->append[$field]);
610
        }
611
612
        if (empty($rules)) {
613
            return true;
614
        }
615
616
        $i = 0;
617
        foreach ($rules as $key => $rule) {
618
            if ($rule instanceof Closure) {
619
                $result = call_user_func_array($rule, [$value, $data]);
620
                $info   = is_numeric($key) ? '' : $key;
621
            } else {
622
                // 判断验证类型
623
                [$type, $rule, $info] = $this->getValidateType($key, $rule);
624
625
                if (isset($this->append[$field]) && in_array($info, $this->append[$field])) {
626
                } elseif (isset($this->remove[$field]) && in_array($info, $this->remove[$field])) {
627
                    // 规则已经移除
628
                    $i++;
629
                    continue;
630
                }
631
632
                if (isset($this->type[$type])) {
633
                    $result = call_user_func_array($this->type[$type], [$value, $rule, $data, $field, $title]);
634
                } elseif ('must' == $info || str_starts_with($info, 'require') || (!is_null($value) && '' !== $value)) {
635
                    $result = call_user_func_array([$this, $type], [$value, $rule, $data, $field, $title]);
636
                } else {
637
                    $result = true;
638
                }
639
            }
640
641
            if (false === $result) {
642
                // 验证失败 返回错误信息
643
                if (!empty($msg[$i])) {
644
                    $message = $msg[$i];
645
                    if (is_string($message) && str_starts_with($message, '{%')) {
646
                        $message = $this->lang->get(substr($message, 2, -1));
647
                    }
648
                } else {
649
                    $message = $this->getRuleMsg($field, $title, $info, $rule);
650
                }
651
652
                return $message;
653
            } elseif (true !== $result) {
654
                // 返回自定义错误信息
655
                if (is_string($result) && str_contains($result, ':')) {
656
                    $result = str_replace(':attribute', $title, $result);
657
658
                    if (str_contains($result, ':rule') && is_scalar($rule)) {
659
                        $result = str_replace(':rule', (string) $rule, $result);
660
                    }
661
                }
662
663
                return $result;
664
            }
665
            $i++;
666
        }
667
668
        return $result ?? true;
669
    }
670
671
    /**
672
     * 获取当前验证类型及规则
673
     * @access public
674
     * @param mixed $key
675
     * @param mixed $rule
676
     * @return array
677
     */
678
    protected function getValidateType($key, $rule): array
679
    {
680
        // 判断验证类型
681
        if (!is_numeric($key)) {
682
            if (isset($this->alias[$key])) {
683
                // 判断别名
684
                $key = $this->alias[$key];
685
            }
686
            return [$key, $rule, $key];
687
        }
688
689
        if (str_contains($rule, ':')) {
690
            [$type, $rule] = explode(':', $rule, 2);
691
            if (isset($this->alias[$type])) {
692
                // 判断别名
693
                $type = $this->alias[$type];
694
            }
695
            $info = $type;
696
        } elseif (method_exists($this, $rule)) {
697
            $type = $rule;
698
            $info = $rule;
699
            $rule = '';
700
        } else {
701
            $type = 'is';
702
            $info = $rule;
703
        }
704
705
        return [$type, $rule, $info];
706
    }
707
708
    /**
709
     * 验证是否和某个字段的值一致
710
     * @access public
711
     * @param mixed  $value 字段值
712
     * @param mixed  $rule  验证规则
713
     * @param array  $data  数据
714
     * @param string $field 字段名
715
     * @return bool
716
     */
717
    public function confirm($value, $rule, array $data = [], string $field = ''): bool
718
    {
719
        if ('' == $rule) {
720
            if (str_contains($field, '_confirm')) {
721
                $rule = strstr($field, '_confirm', true);
722
            } else {
723
                $rule = $field . '_confirm';
724
            }
725
        }
726
727
        return $this->getDataValue($data, $rule) === $value;
728
    }
729
730
    /**
731
     * 验证是否和某个字段的值是否不同
732
     * @access public
733
     * @param mixed $value 字段值
734
     * @param mixed $rule  验证规则
735
     * @param array $data  数据
736
     * @return bool
737
     */
738
    public function different($value, $rule, array $data = []): bool
739
    {
740
        return $this->getDataValue($data, $rule) != $value;
741
    }
742
743
    /**
744
     * 验证是否大于等于某个值
745
     * @access public
746
     * @param mixed $value 字段值
747
     * @param mixed $rule  验证规则
748
     * @param array $data  数据
749
     * @return bool
750
     */
751
    public function egt($value, $rule, array $data = []): bool
752
    {
753
        return $value >= $this->getDataValue($data, $rule);
754
    }
755
756
    /**
757
     * 验证是否大于某个值
758
     * @access public
759
     * @param mixed $value 字段值
760
     * @param mixed $rule  验证规则
761
     * @param array $data  数据
762
     * @return bool
763
     */
764
    public function gt($value, $rule, array $data = []): bool
765
    {
766
        return $value > $this->getDataValue($data, $rule);
767
    }
768
769
    /**
770
     * 验证是否小于等于某个值
771
     * @access public
772
     * @param mixed $value 字段值
773
     * @param mixed $rule  验证规则
774
     * @param array $data  数据
775
     * @return bool
776
     */
777
    public function elt($value, $rule, array $data = []): bool
778
    {
779
        return $value <= $this->getDataValue($data, $rule);
780
    }
781
782
    /**
783
     * 验证是否小于某个值
784
     * @access public
785
     * @param mixed $value 字段值
786
     * @param mixed $rule  验证规则
787
     * @param array $data  数据
788
     * @return bool
789
     */
790
    public function lt($value, $rule, array $data = []): bool
791
    {
792
        return $value < $this->getDataValue($data, $rule);
793
    }
794
795
    /**
796
     * 验证是否等于某个值
797
     * @access public
798
     * @param mixed $value 字段值
799
     * @param mixed $rule  验证规则
800
     * @return bool
801
     */
802
    public function eq($value, $rule): bool
803
    {
804
        return $value == $rule;
805
    }
806
807
    /**
808
     * 必须验证
809
     * @access public
810
     * @param mixed $value 字段值
811
     * @param mixed $rule  验证规则
812
     * @return bool
813
     */
814
    public function must($value, $rule = null): bool
815
    {
816
        return !empty($value) || '0' == $value;
817
    }
818
819
    /**
820
     * 验证字段值是否为有效格式
821
     * @access public
822
     * @param mixed  $value 字段值
823
     * @param string $rule  验证规则
824
     * @param array  $data  数据
825
     * @return bool
826
     */
827
    public function is($value, string $rule, array $data = []): bool
828
    {
829
        $call = function ($value, $rule) {
830
            if (isset($this->type[$rule])) {
831
                // 注册的验证规则
832
                $result = call_user_func_array($this->type[$rule], [$value]);
833
            } elseif (function_exists('ctype_' . $rule)) {
834
                // ctype验证规则
835
                $ctypeFun = 'ctype_' . $rule;
836
                $result   = $ctypeFun($value);
837
            } elseif (isset($this->filter[$rule])) {
838
                // Filter_var验证规则
839
                $result = $this->filter($value, $this->filter[$rule]);
840
            } else {
841
                // 正则验证
842
                $result = $this->regex($value, $rule);
843
            }
844
            return $result;
845
        };
846
847
        return match (Str::camel($rule)) {
848
            'require'   =>  !empty($value) || '0' == $value, // 必须
849
            'accepted'  =>  in_array($value, ['1', 'on', 'yes']), // 接受
850
            'date'      =>  false !== strtotime($value),                // 是否是一个有效日期
851
            'activeUrl' =>  checkdnsrr($value), // 是否为有效的网址
852
            'boolean','bool'    =>  in_array($value, [true, false, 0, 1, '0', '1'], true),                // 是否为布尔值
853
            'number'    =>  ctype_digit((string) $value),
854
            'alphaNum'  =>  ctype_alnum($value),
855
            'array'     =>  is_array($value),                // 是否为数组
856
            'file'      =>  $value instanceof File,
857
            'image'     =>  $value instanceof File && in_array($this->getImageType($value->getRealPath()), [1, 2, 3, 6]),
858
            'token'     =>  $this->token($value, '__token__', $data),
859
            default     =>  $call($value, $rule),
860
        };
861
    }
862
863
    // 判断图像类型
864
    protected function getImageType($image)
865
    {
866
        if (function_exists('exif_imagetype')) {
867
            return exif_imagetype($image);
868
        }
869
870
        try {
871
            $info = getimagesize($image);
872
            return $info ? $info[2] : false;
873
        } catch (\Exception $e) {
874
            return false;
875
        }
876
    }
877
878
    /**
879
     * 验证表单令牌
880
     * @access public
881
     * @param mixed $value 字段值
882
     * @param mixed $rule  验证规则
883
     * @param array $data  数据
884
     * @return bool
885
     */
886
    public function token($value, string $rule, array $data): bool
887
    {
888
        $rule = !empty($rule) ? $rule : '__token__';
889
        return $this->request->checkToken($rule, $data);
890
    }
891
892
    /**
893
     * 验证是否为合格的域名或者IP 支持A,MX,NS,SOA,PTR,CNAME,AAAA,A6, SRV,NAPTR,TXT 或者 ANY类型
894
     * @access public
895
     * @param mixed $value 字段值
896
     * @param mixed $rule  验证规则
897
     * @return bool
898
     */
899
    public function activeUrl(string $value, string $rule = 'MX'): bool
900
    {
901
        if (!in_array($rule, ['A', 'MX', 'NS', 'SOA', 'PTR', 'CNAME', 'AAAA', 'A6', 'SRV', 'NAPTR', 'TXT', 'ANY'])) {
902
            $rule = 'MX';
903
        }
904
905
        return checkdnsrr($value, $rule);
906
    }
907
908
    /**
909
     * 验证是否有效IP
910
     * @access public
911
     * @param mixed $value 字段值
912
     * @param mixed $rule  验证规则 ipv4 ipv6
913
     * @return bool
914
     */
915
    public function ip($value, string $rule = 'ipv4'): bool
916
    {
917
        if (!in_array($rule, ['ipv4', 'ipv6'])) {
918
            $rule = 'ipv4';
919
        }
920
921
        return $this->filter($value, [FILTER_VALIDATE_IP, 'ipv6' == $rule ? FILTER_FLAG_IPV6 : FILTER_FLAG_IPV4]);
922
    }
923
924
    /**
925
     * 检测上传文件后缀
926
     * @access public
927
     * @param File         $file
928
     * @param array|string $ext 允许后缀
929
     * @return bool
930
     */
931
    protected function checkExt(File $file, $ext): bool
932
    {
933
        if (is_string($ext)) {
934
            $ext = explode(',', $ext);
935
        }
936
937
        return in_array(strtolower($file->extension()), $ext);
938
    }
939
940
    /**
941
     * 检测上传文件大小
942
     * @access public
943
     * @param File    $file
944
     * @param integer $size 最大大小
945
     * @return bool
946
     */
947
    protected function checkSize(File $file, $size): bool
948
    {
949
        return $file->getSize() <= (int) $size;
950
    }
951
952
    /**
953
     * 检测上传文件类型
954
     * @access public
955
     * @param File         $file
956
     * @param array|string $mime 允许类型
957
     * @return bool
958
     */
959
    protected function checkMime(File $file, $mime): bool
960
    {
961
        if (is_string($mime)) {
962
            $mime = explode(',', $mime);
963
        }
964
965
        return in_array(strtolower($file->getMime()), $mime);
966
    }
967
968
    /**
969
     * 验证上传文件后缀
970
     * @access public
971
     * @param mixed $file 上传文件
972
     * @param mixed $rule 验证规则
973
     * @return bool
974
     */
975
    public function fileExt($file, $rule): bool
976
    {
977
        if (is_array($file)) {
978
            foreach ($file as $item) {
979
                if (!($item instanceof File) || !$this->checkExt($item, $rule)) {
980
                    return false;
981
                }
982
            }
983
            return true;
984
        } elseif ($file instanceof File) {
985
            return $this->checkExt($file, $rule);
986
        }
987
988
        return false;
989
    }
990
991
    /**
992
     * 验证上传文件类型
993
     * @access public
994
     * @param mixed $file 上传文件
995
     * @param mixed $rule 验证规则
996
     * @return bool
997
     */
998
    public function fileMime($file, $rule): bool
999
    {
1000
        if (is_array($file)) {
1001
            foreach ($file as $item) {
1002
                if (!($item instanceof File) || !$this->checkMime($item, $rule)) {
1003
                    return false;
1004
                }
1005
            }
1006
            return true;
1007
        } elseif ($file instanceof File) {
1008
            return $this->checkMime($file, $rule);
1009
        }
1010
1011
        return false;
1012
    }
1013
1014
    /**
1015
     * 验证上传文件大小
1016
     * @access public
1017
     * @param mixed $file 上传文件
1018
     * @param mixed $rule 验证规则
1019
     * @return bool
1020
     */
1021
    public function fileSize($file, $rule): bool
1022
    {
1023
        if (is_array($file)) {
1024
            foreach ($file as $item) {
1025
                if (!($item instanceof File) || !$this->checkSize($item, $rule)) {
1026
                    return false;
1027
                }
1028
            }
1029
            return true;
1030
        } elseif ($file instanceof File) {
1031
            return $this->checkSize($file, $rule);
1032
        }
1033
1034
        return false;
1035
    }
1036
1037
    /**
1038
     * 验证图片的宽高及类型
1039
     * @access public
1040
     * @param mixed $file 上传文件
1041
     * @param mixed $rule 验证规则
1042
     * @return bool
1043
     */
1044
    public function image($file, $rule): bool
1045
    {
1046
        if (!($file instanceof File)) {
1047
            return false;
1048
        }
1049
1050
        if ($rule) {
1051
            $rule = explode(',', $rule);
1052
1053
            [$width, $height, $type] = getimagesize($file->getRealPath());
1054
1055
            if (isset($rule[2])) {
1056
                $imageType = strtolower($rule[2]);
1057
1058
                if ('jpg' == $imageType) {
1059
                    $imageType = 'jpeg';
1060
                }
1061
1062
                if (image_type_to_extension($type, false) != $imageType) {
1063
                    return false;
1064
                }
1065
            }
1066
1067
            [$w, $h] = $rule;
1068
1069
            return $w == $width && $h == $height;
1070
        }
1071
1072
        return in_array($this->getImageType($file->getRealPath()), [1, 2, 3, 6]);
1073
    }
1074
1075
    /**
1076
     * 验证时间和日期是否符合指定格式
1077
     * @access public
1078
     * @param mixed $value 字段值
1079
     * @param mixed $rule  验证规则
1080
     * @return bool
1081
     */
1082
    public function dateFormat($value, $rule): bool
1083
    {
1084
        $info = date_parse_from_format($rule, $value);
1085
        return 0 == $info['warning_count'] && 0 == $info['error_count'];
1086
    }
1087
1088
    /**
1089
     * 验证是否唯一
1090
     * @access public
1091
     * @param mixed  $value 字段值
1092
     * @param mixed  $rule  验证规则 格式:数据表,字段名,排除ID,主键名
1093
     * @param array  $data  数据
1094
     * @param string $field 验证字段名
1095
     * @return bool
1096
     */
1097
    public function unique($value, $rule, array $data = [], string $field = ''): bool
1098
    {
1099
        if (is_string($rule)) {
1100
            $rule = explode(',', $rule);
1101
        }
1102
1103
        if (str_contains($rule[0], '\\')) {
1104
            // 指定模型类
1105
            $db = new $rule[0];
1106
        } else {
1107
            $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

1107
            /** @scrutinizer ignore-call */ 
1108
            $db = $this->db->name($rule[0]);
Loading history...
1108
        }
1109
1110
        $key = $rule[1] ?? $field;
1111
        $map = [];
1112
        
1113
        if (str_contains($key, '^')) {
1114
            // 支持多个字段验证
1115
            $fields = explode('^', $key);
1116
            $map_arr=[];
1117
            foreach ($fields as $k) {
1118
                if (isset($data[$k])) {
1119
                    $map[] = [$k, '=', $data[$k]];
1120
                    $map_arr[]=$k;
1121
                }
1122
            }
1123
            if(!in_array($field, $map_arr)){
1124
                $map[] = [$field, '=', $data[$field]];
1125
            }
1126
        } elseif (str_contains($key, '=')) {
1127
            // 支持复杂验证条件
1128
            $fields = explode('&', $key);
1129
            $map_arr=[];
1130
            foreach ($fields as $k) {
1131
                //判断验证条件是否传参,没有传参就使用$data中对应的值
1132
                if (str_contains($k, '=')) {
1133
                    $str_map = explode('=', $k);
1134
                    $map[] = [$str_map[0], '=', $str_map[1]];
1135
                    $map_arr[]=$str_map[0];
1136
                }else{
1137
                    $map[] = [$k, '=', $data[$k]];
1138
                    $map_arr[]=$k;
1139
                }
1140
            }
1141
            if(!in_array($field, $map_arr)){
1142
                $map[] = [$field, '=', $data[$field]];
1143
            }
1144
        } elseif (isset($data[$field])) {
1145
            $map[] = [$key, '=', $data[$field]];
1146
        } else {
1147
            $map = [];
1148
        }
1149
1150
        $pk = !empty($rule[3]) ? $rule[3] : $db->getPk();
1151
1152
        if (is_string($pk)) {
1153
            if (isset($rule[2])) {
1154
                $map[] = [$pk, '<>', $rule[2]];
1155
            } elseif (isset($data[$pk])) {
1156
                $map[] = [$pk, '<>', $data[$pk]];
1157
            }
1158
        }
1159
1160
        if ($db->where($map)->field($pk)->find()) {
1161
            return false;
1162
        }
1163
1164
        return true;
1165
    }
1166
1167
    /**
1168
     * 使用filter_var方式验证
1169
     * @access public
1170
     * @param mixed $value 字段值
1171
     * @param mixed $rule  验证规则
1172
     * @return bool
1173
     */
1174
    public function filter($value, $rule): bool
1175
    {
1176
        if (is_string($rule) && str_contains($rule, ',')) {
1177
            [$rule, $param] = explode(',', $rule);
1178
        } elseif (is_array($rule)) {
1179
            $param = $rule[1] ?? 0;
1180
            $rule  = $rule[0];
1181
        } else {
1182
            $param = 0;
1183
        }
1184
1185
        return false !== filter_var($value, is_int($rule) ? $rule : filter_id($rule), $param);
1186
    }
1187
1188
    /**
1189
     * 验证某个字段等于某个值的时候必须
1190
     * @access public
1191
     * @param mixed $value 字段值
1192
     * @param mixed $rule  验证规则
1193
     * @param array $data  数据
1194
     * @return bool
1195
     */
1196
    public function requireIf($value, $rule, array $data = []): bool
1197
    {
1198
        [$field, $val] = explode(',', $rule);
1199
1200
        if ($this->getDataValue($data, $field) == $val) {
1201
            return !empty($value) || '0' == $value;
1202
        }
1203
1204
        return true;
1205
    }
1206
1207
    /**
1208
     * 通过回调方法验证某个字段是否必须
1209
     * @access public
1210
     * @param mixed $value 字段值
1211
     * @param mixed $rule  验证规则
1212
     * @param array $data  数据
1213
     * @return bool
1214
     */
1215
    public function requireCallback($value, $rule, array $data = []): bool
1216
    {
1217
        $result = call_user_func_array([$this, $rule], [$value, $data]);
1218
1219
        if ($result) {
1220
            return !empty($value) || '0' == $value;
1221
        }
1222
1223
        return true;
1224
    }
1225
1226
    /**
1227
     * 验证某个字段有值的情况下必须
1228
     * @access public
1229
     * @param mixed $value 字段值
1230
     * @param mixed $rule  验证规则
1231
     * @param array $data  数据
1232
     * @return bool
1233
     */
1234
    public function requireWith($value, $rule, array $data = []): bool
1235
    {
1236
        $val = $this->getDataValue($data, $rule);
1237
1238
        if (!empty($val)) {
1239
            return !empty($value) || '0' == $value;
1240
        }
1241
1242
        return true;
1243
    }
1244
1245
    /**
1246
     * 验证某个字段没有值的情况下必须
1247
     * @access public
1248
     * @param mixed $value 字段值
1249
     * @param mixed $rule  验证规则
1250
     * @param array $data  数据
1251
     * @return bool
1252
     */
1253
    public function requireWithout($value, $rule, array $data = []): bool
1254
    {
1255
        $val = $this->getDataValue($data, $rule);
1256
1257
        if (empty($val)) {
1258
            return !empty($value) || '0' == $value;
1259
        }
1260
1261
        return true;
1262
    }
1263
1264
    /**
1265
     * 验证是否在范围内
1266
     * @access public
1267
     * @param mixed $value 字段值
1268
     * @param mixed $rule  验证规则
1269
     * @return bool
1270
     */
1271
    public function in($value, $rule): bool
1272
    {
1273
        return in_array($value, is_array($rule) ? $rule : explode(',', $rule));
1274
    }
1275
1276
    /**
1277
     * 验证是否不在某个范围
1278
     * @access public
1279
     * @param mixed $value 字段值
1280
     * @param mixed $rule  验证规则
1281
     * @return bool
1282
     */
1283
    public function notIn($value, $rule): bool
1284
    {
1285
        return !in_array($value, is_array($rule) ? $rule : explode(',', $rule));
1286
    }
1287
1288
    /**
1289
     * between验证数据
1290
     * @access public
1291
     * @param mixed $value 字段值
1292
     * @param mixed $rule  验证规则
1293
     * @return bool
1294
     */
1295
    public function between($value, $rule): bool
1296
    {
1297
        if (is_string($rule)) {
1298
            $rule = explode(',', $rule);
1299
        }
1300
        [$min, $max] = $rule;
1301
1302
        return $value >= $min && $value <= $max;
1303
    }
1304
1305
    /**
1306
     * 使用notbetween验证数据
1307
     * @access public
1308
     * @param mixed $value 字段值
1309
     * @param mixed $rule  验证规则
1310
     * @return bool
1311
     */
1312
    public function notBetween($value, $rule): bool
1313
    {
1314
        if (is_string($rule)) {
1315
            $rule = explode(',', $rule);
1316
        }
1317
        [$min, $max] = $rule;
1318
1319
        return $value < $min || $value > $max;
1320
    }
1321
1322
    /**
1323
     * 验证数据长度
1324
     * @access public
1325
     * @param mixed $value 字段值
1326
     * @param mixed $rule  验证规则
1327
     * @return bool
1328
     */
1329
    public function length($value, $rule): bool
1330
    {
1331
        if (is_array($value)) {
1332
            $length = count($value);
1333
        } elseif ($value instanceof File) {
1334
            $length = $value->getSize();
1335
        } else {
1336
            $length = mb_strlen((string) $value);
1337
        }
1338
1339
        if (is_string($rule) && str_contains($rule, ',')) {
1340
            // 长度区间
1341
            [$min, $max] = explode(',', $rule);
1342
            return $length >= $min && $length <= $max;
1343
        }
1344
1345
        // 指定长度
1346
        return $length == $rule;
1347
    }
1348
1349
    /**
1350
     * 验证数据最大长度
1351
     * @access public
1352
     * @param mixed $value 字段值
1353
     * @param mixed $rule  验证规则
1354
     * @return bool
1355
     */
1356
    public function max($value, $rule): bool
1357
    {
1358
        if (is_array($value)) {
1359
            $length = count($value);
1360
        } elseif ($value instanceof File) {
1361
            $length = $value->getSize();
1362
        } else {
1363
            $length = mb_strlen((string) $value);
1364
        }
1365
1366
        return $length <= $rule;
1367
    }
1368
1369
    /**
1370
     * 验证数据最小长度
1371
     * @access public
1372
     * @param mixed $value 字段值
1373
     * @param mixed $rule  验证规则
1374
     * @return bool
1375
     */
1376
    public function min($value, $rule): bool
1377
    {
1378
        if (is_array($value)) {
1379
            $length = count($value);
1380
        } elseif ($value instanceof File) {
1381
            $length = $value->getSize();
1382
        } else {
1383
            $length = mb_strlen((string) $value);
1384
        }
1385
1386
        return $length >= $rule;
1387
    }
1388
1389
    /**
1390
     * 验证日期
1391
     * @access public
1392
     * @param mixed $value 字段值
1393
     * @param mixed $rule  验证规则
1394
     * @param array $data  数据
1395
     * @return bool
1396
     */
1397
    public function after($value, $rule, array $data = []): bool
1398
    {
1399
        return strtotime($value) >= strtotime($rule);
1400
    }
1401
1402
    /**
1403
     * 验证日期
1404
     * @access public
1405
     * @param mixed $value 字段值
1406
     * @param mixed $rule  验证规则
1407
     * @param array $data  数据
1408
     * @return bool
1409
     */
1410
    public function before($value, $rule, array $data = []): bool
1411
    {
1412
        return strtotime($value) <= strtotime($rule);
1413
    }
1414
1415
    /**
1416
     * 验证日期
1417
     * @access public
1418
     * @param mixed $value 字段值
1419
     * @param mixed $rule  验证规则
1420
     * @param array $data  数据
1421
     * @return bool
1422
     */
1423
    public function afterWith($value, $rule, array $data = []): bool
1424
    {
1425
        $rule = $this->getDataValue($data, $rule);
1426
        return !is_null($rule) && strtotime($value) >= strtotime($rule);
1427
    }
1428
1429
    /**
1430
     * 验证日期
1431
     * @access public
1432
     * @param mixed $value 字段值
1433
     * @param mixed $rule  验证规则
1434
     * @param array $data  数据
1435
     * @return bool
1436
     */
1437
    public function beforeWith($value, $rule, array $data = []): bool
1438
    {
1439
        $rule = $this->getDataValue($data, $rule);
1440
        return !is_null($rule) && strtotime($value) <= strtotime($rule);
1441
    }
1442
1443
    /**
1444
     * 验证有效期
1445
     * @access public
1446
     * @param mixed $value 字段值
1447
     * @param mixed $rule  验证规则
1448
     * @return bool
1449
     */
1450
    public function expire($value, $rule): bool
1451
    {
1452
        if (is_string($rule)) {
1453
            $rule = explode(',', $rule);
1454
        }
1455
1456
        [$start, $end] = $rule;
1457
1458
        if (!is_numeric($start)) {
1459
            $start = strtotime($start);
1460
        }
1461
1462
        if (!is_numeric($end)) {
1463
            $end = strtotime($end);
1464
        }
1465
1466
        return time() >= $start && time() <= $end;
1467
    }
1468
1469
    /**
1470
     * 验证IP许可
1471
     * @access public
1472
     * @param mixed $value 字段值
1473
     * @param mixed $rule  验证规则
1474
     * @return bool
1475
     */
1476
    public function allowIp($value, $rule): bool
1477
    {
1478
        return in_array($value, is_array($rule) ? $rule : explode(',', $rule));
1479
    }
1480
1481
    /**
1482
     * 验证IP禁用
1483
     * @access public
1484
     * @param mixed $value 字段值
1485
     * @param mixed $rule  验证规则
1486
     * @return bool
1487
     */
1488
    public function denyIp($value, $rule): bool
1489
    {
1490
        return !in_array($value, is_array($rule) ? $rule : explode(',', $rule));
1491
    }
1492
1493
    /**
1494
     * 使用正则验证数据
1495
     * @access public
1496
     * @param mixed $value 字段值
1497
     * @param mixed $rule  验证规则 正则规则或者预定义正则名
1498
     * @return bool
1499
     */
1500
    public function regex($value, $rule): bool
1501
    {
1502
        if (isset($this->regex[$rule])) {
1503
            $rule = $this->regex[$rule];
1504
        } elseif (isset($this->defaultRegex[$rule])) {
1505
            $rule = $this->defaultRegex[$rule];
1506
        }
1507
1508
        if (is_string($rule) && !str_starts_with($rule, '/') && !preg_match('/\/[imsU]{0,4}$/', $rule)) {
1509
            // 不是正则表达式则两端补上/
1510
            $rule = '/^' . $rule . '$/';
1511
        }
1512
1513
        return is_scalar($value) && 1 === preg_match($rule, (string) $value);
1514
    }
1515
1516
    /**
1517
     * 获取错误信息
1518
     * @return array|string
1519
     */
1520
    public function getError()
1521
    {
1522
        return $this->error;
1523
    }
1524
1525
    /**
1526
     * 获取数据值
1527
     * @access protected
1528
     * @param array  $data 数据
1529
     * @param string $key  数据标识 支持二维
1530
     * @return mixed
1531
     */
1532
    protected function getDataValue(array $data, $key)
1533
    {
1534
        if (is_numeric($key)) {
1535
            $value = $key;
1536
        } elseif (is_string($key) && str_contains($key, '.')) {
1537
            // 支持多维数组验证
1538
            foreach (explode('.', $key) as $key) {
0 ignored issues
show
introduced by
$key is overwriting one of the parameters of this function.
Loading history...
1539
                if (!isset($data[$key])) {
1540
                    $value = null;
1541
                    break;
1542
                }
1543
                $value = $data = $data[$key];
1544
            }
1545
        } else {
1546
            $value = $data[$key] ?? null;
1547
        }
1548
1549
        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...
1550
    }
1551
1552
    /**
1553
     * 获取验证规则的错误提示信息
1554
     * @access protected
1555
     * @param string $attribute 字段英文名
1556
     * @param string $title     字段描述名
1557
     * @param string $type      验证规则名称
1558
     * @param mixed  $rule      验证规则数据
1559
     * @return string|array
1560
     */
1561
    protected function getRuleMsg(string $attribute, string $title, string $type, $rule)
1562
    {
1563
        if (isset($this->message[$attribute . '.' . $type])) {
1564
            $msg = $this->message[$attribute . '.' . $type];
1565
        } elseif (isset($this->message[$attribute][$type])) {
1566
            $msg = $this->message[$attribute][$type];
1567
        } elseif (isset($this->message[$attribute])) {
1568
            $msg = $this->message[$attribute];
1569
        } elseif (isset($this->typeMsg[$type])) {
1570
            $msg = $this->typeMsg[$type];
1571
        } elseif (str_starts_with($type, 'require')) {
1572
            $msg = $this->typeMsg['require'];
1573
        } else {
1574
            $msg = $title . $this->lang->get('not conform to the rules');
1575
        }
1576
1577
        if (is_array($msg)) {
1578
            return $this->errorMsgIsArray($msg, $rule, $title);
1579
        }
1580
1581
        return $this->parseErrorMsg($msg, $rule, $title);
1582
    }
1583
1584
    /**
1585
     * 获取验证规则的错误提示信息
1586
     * @access protected
1587
     * @param string $msg   错误信息
1588
     * @param mixed  $rule  验证规则数据
1589
     * @param string $title 字段描述名
1590
     * @return string|array
1591
     */
1592
    protected function parseErrorMsg(string $msg, $rule, string $title)
1593
    {
1594
        if (str_starts_with($msg, '{%')) {
1595
            $msg = $this->lang->get(substr($msg, 2, -1));
1596
        } elseif ($this->lang->has($msg)) {
1597
            $msg = $this->lang->get($msg);
1598
        }
1599
1600
        if (is_array($msg)) {
1601
            return $this->errorMsgIsArray($msg, $rule, $title);
1602
        }
1603
1604
        // rule若是数组则转为字符串
1605
        if (is_array($rule)) {
1606
            $rule = implode(',', $rule);
1607
        }
1608
1609
        if (is_scalar($rule) && str_contains($msg, ':')) {
1610
            // 变量替换
1611
            if (is_string($rule) && str_contains($rule, ',')) {
1612
                $array = array_pad(explode(',', $rule), 3, '');
1613
            } else {
1614
                $array = array_pad([], 3, '');
1615
            }
1616
1617
            $msg = str_replace(
1618
                [':attribute', ':1', ':2', ':3'],
1619
                [$title, $array[0], $array[1], $array[2]],
1620
                $msg
1621
            );
1622
1623
            if (str_contains($msg, ':rule')) {
1624
                $msg = str_replace(':rule', (string) $rule, $msg);
1625
            }
1626
        }
1627
1628
        return $msg;
1629
    }
1630
1631
    /**
1632
     * 错误信息数组处理
1633
     * @access protected
1634
     * @param array $msg   错误信息
1635
     * @param mixed  $rule  验证规则数据
1636
     * @param string $title 字段描述名
1637
     * @return array
1638
     */
1639
    protected function errorMsgIsArray(array $msg, $rule, string $title)
1640
    {
1641
        foreach ($msg as $key => $val) {
1642
            if (is_string($val)) {
1643
                $msg[$key] = $this->parseErrorMsg($val, $rule, $title);
1644
            }
1645
        }
1646
        return $msg;
1647
    }
1648
1649
    /**
1650
     * 获取数据验证的场景
1651
     * @access protected
1652
     * @param string $scene 验证场景
1653
     * @return void
1654
     */
1655
    protected function getScene(string $scene): void
1656
    {
1657
        $this->only = $this->append = $this->remove = [];
1658
1659
        if (method_exists($this, 'scene' . $scene)) {
1660
            call_user_func([$this, 'scene' . $scene]);
1661
        } elseif (isset($this->scene[$scene])) {
1662
            // 如果设置了验证适用场景
1663
            $this->only = $this->scene[$scene];
1664
        }
1665
    }
1666
1667
    /**
1668
     * 动态方法 直接调用is方法进行验证
1669
     * @access public
1670
     * @param string $method 方法名
1671
     * @param array  $args   调用参数
1672
     * @return bool
1673
     */
1674
    public function __call($method, $args)
1675
    {
1676
        if ('is' == strtolower(substr($method, 0, 2))) {
1677
            $method = substr($method, 2);
1678
        }
1679
1680
        array_push($args, lcfirst($method));
1681
1682
        return call_user_func_array([$this, 'is'], $args);
1683
    }
1684
}
1685