1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\Enum\Laravel\Rules; |
4
|
|
|
|
5
|
|
|
use Exception; |
6
|
|
|
use Illuminate\Contracts\Validation\Rule; |
7
|
|
|
use Illuminate\Support\Arr; |
8
|
|
|
use Illuminate\Support\Facades\Lang; |
9
|
|
|
use Illuminate\Support\Str; |
10
|
|
|
use InvalidArgumentException; |
11
|
|
|
use Spatie\Enum\Enumerable; |
12
|
|
|
|
13
|
|
|
class EnumRule implements Rule |
14
|
|
|
{ |
15
|
|
|
protected $rule = 'enum'; |
16
|
|
|
|
17
|
|
|
/** @var Enumerable */ |
18
|
|
|
protected $enum; |
19
|
|
|
|
20
|
|
|
/** @var string */ |
21
|
|
|
protected $attribute; |
22
|
|
|
|
23
|
|
|
/** @var mixed */ |
24
|
|
|
protected $value; |
25
|
|
|
|
26
|
|
|
public function __construct(string $enum) |
27
|
|
|
{ |
28
|
|
|
if (! class_exists($enum) || ! isset(class_implements($enum)[Enumerable::class])) { |
29
|
|
|
throw new InvalidArgumentException("The given class {$enum} does not implement the Enumerable interface."); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
$this->enum = $enum; |
|
|
|
|
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public function passes($attribute, $value): bool |
36
|
|
|
{ |
37
|
|
|
$this->attribute = $attribute; |
38
|
|
|
$this->value = $value; |
39
|
|
|
|
40
|
|
|
try { |
41
|
|
|
$this->enum::make($value); |
42
|
|
|
|
43
|
|
|
return true; |
44
|
|
|
} catch (Exception $ex) { |
45
|
|
|
return false; |
46
|
|
|
} |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
public function message(): string |
50
|
|
|
{ |
51
|
|
|
return Lang::get('enum::validation.'.$this->rule, [ |
52
|
|
|
'attribute' => $this->attribute, |
53
|
|
|
'value' => $this->value, |
54
|
|
|
'enum' => $this->enum, |
55
|
|
|
'other' => implode(', ', $this->getDisplayableOtherValues()), |
56
|
|
|
]); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
protected function getDisplayableOtherValues(): array |
60
|
|
|
{ |
61
|
|
|
return array_map(function ($value): string { |
62
|
|
|
return $this->getValueTranslation($value) ?? $value; |
63
|
|
|
}, $this->getOtherValues()); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @param string|int $value |
68
|
|
|
* |
69
|
|
|
* @return string|null |
70
|
|
|
*/ |
71
|
|
|
protected function getValueTranslation($value): ?string |
72
|
|
|
{ |
73
|
|
|
return Arr::get(Lang::get('enum::validation.enums'), $this->enum.'.'.Str::slug($this->enum::make($value)->getName(), '_')); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
protected function getOtherValues(): array |
77
|
|
|
{ |
78
|
|
|
return $this->enum::getValues(); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|
Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.
Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..