Passed
Push — 8.0 ( ae3f71...2a8087 )
by liu
10:33 queued 15s
created

Validate::requireWith()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

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

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