-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
CountryCode.php
47 lines (35 loc) · 995 Bytes
/
CountryCode.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
namespace Spatie\ValidationRules\Rules;
use League\ISO3166\ISO3166;
use Illuminate\Contracts\Validation\Rule;
class CountryCode implements Rule
{
/** @var bool */
protected $required;
/** @var string */
protected $attribute;
public function __construct(bool $required = true)
{
$this->required = $required;
}
public function nullable(): self
{
$this->required = false;
return $this;
}
public function passes($attribute, $value): bool
{
$this->attribute = $attribute;
if (! $this->required && ($value === '0' || $value === 0 || $value === null)) {
return true;
}
$countries = array_pluck((new ISO3166())->all(), ISO3166::KEY_ALPHA2);
return in_array($value, $countries, true);
}
public function message(): string
{
return __('validationRules::messages.country_code', [
'attribute' => $this->attribute,
]);
}
}