Completed
Push — master ( 6f49b0...9bb6c5 )
by
unknown
09:20
created

CountryCode::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Spatie\ValidationRules\Rules;
4
5
use Illuminate\Contracts\Validation\Rule;
6
use League\ISO3166\ISO3166;
7
8
class CountryCode implements Rule
9
{
10
    /** @var bool */
11
    protected $required;
12
13
    /** @var string */
14
    protected $attribute;
15
16
    public function __construct(bool $required = true)
17
    {
18
        $this->required = $required;
19
    }
20
21
    public function nullable(): self
22
    {
23
        $this->required = false;
24
25
        return $this;
26
    }
27
28
    public function passes($attribute, $value): bool
29
    {
30
        $this->attribute = $attribute;
31
32
        if (! $this->required && ($value === '0' || $value === 0 || $value === null)) {
33
            return true;
34
        }
35
36
        $countries = array_pluck((new ISO3166())->all(), ISO3166::KEY_ALPHA2);
37
38
        return in_array($value, $countries, true);
39
    }
40
41
    public function message(): string
42
    {
43
        return __('validation.country_code', [
44
            'attribute' => $this->attribute,
45
        ]);
46
    }
47
}
48