RegionRule::getRule()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
nc 1
nop 1
1
<?php
2
namespace SimpleCMS\Region\Validation;
3
4
use Illuminate\Contracts\Validation\ValidationRule;
5
6
/**
7
 * 自定义验证规则
8
 */
9
class RegionRule implements ValidationRule
10
{
11
12
    /**
13
     * 校验参数类
14
     *
15
     * @var string|null
16
     * @author Dennis Lui <[email protected]>
17
     */
18
    public ?string $ruleClass = null;
19
20
    /**
21
     * Run the validation rule.
22
     *
23
     * @param  string  $attribute
24
     * @param  mixed  $value
25
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
26
     * @return void
27
     */
28
    public function validate(string $attribute, mixed $value, \Closure $fail): void
29
    {
30
        if (!$this->passes($value)) {
31
            $fail($this->message($attribute));
32
        }
33
    }
34
35
    /**
36
     * 获取模型方法类
37
     *
38
     * @author Dennis Lui <[email protected]>
39
     * @param  mixed          $value
40
     * @return RegionInterface
41
     */
42
    protected function getRule($value): RegionInterface
43
    {
44
        $className = $this->ruleClass;
45
        return new $className($value);
46
    }
47
48
    /**
49
     * Determine if the validation rule passes.
50
     *
51
     * @param  mixed  $value
52
     * @return bool
53
     */
54
    public function passes($value)
55
    {
56
        if (!$this->ruleClass)
57
            return false;
58
        return $this->getRule($value)->isValid();
59
    }
60
61
    /**
62
     * Summary of message
63
     * @param string $attribute
64
     * @return string
65
     */
66
    public function message(string $attribute)
67
    {
68
        return "The {$attribute} is incorrect.";
69
    }
70
}