1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\Enum\Laravel\Rules; |
4
|
|
|
|
5
|
|
|
use Illuminate\Contracts\Validation\Rule; |
6
|
|
|
use Illuminate\Support\Arr; |
7
|
|
|
use Illuminate\Support\Facades\Lang; |
8
|
|
|
use Illuminate\Support\Str; |
9
|
|
|
use Spatie\Enum\Enum; |
10
|
|
|
use Throwable; |
11
|
|
|
|
12
|
|
|
class EnumRule implements Rule |
13
|
|
|
{ |
14
|
|
|
/** @var string|Enum */ |
15
|
|
|
protected $enum; |
16
|
|
|
|
17
|
|
|
protected ?string $attribute = null; |
18
|
|
|
|
19
|
|
|
/** @var mixed */ |
20
|
|
|
protected $value; |
21
|
|
|
|
22
|
|
|
public function __construct(string $enum) |
23
|
|
|
{ |
24
|
|
|
$this->enum = $enum; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public function passes($attribute, $value): bool |
28
|
|
|
{ |
29
|
|
|
$this->attribute = $attribute; |
30
|
|
|
$this->value = $value; |
31
|
|
|
|
32
|
|
|
try { |
33
|
|
|
$this->asEnum($value); |
34
|
|
|
|
35
|
|
|
return true; |
36
|
|
|
} catch (Throwable $ex) { |
37
|
|
|
return false; |
38
|
|
|
} |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public function message(): string |
42
|
|
|
{ |
43
|
|
|
return Lang::get('enum::validation.enum', [ |
44
|
|
|
'attribute' => $this->attribute, |
45
|
|
|
'value' => $this->value, |
46
|
|
|
'enum' => $this->enum, |
47
|
|
|
'other' => implode(', ', $this->getDisplayableOtherValues()), |
48
|
|
|
]); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
protected function getDisplayableOtherValues(): array |
52
|
|
|
{ |
53
|
|
|
return array_map(function ($value): string { |
54
|
|
|
return $this->getValueTranslation($value) ?? $value; |
55
|
|
|
}, $this->getOtherValues()); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @param string|int $value |
60
|
|
|
* |
61
|
|
|
* @return string|null |
62
|
|
|
*/ |
63
|
|
|
protected function getValueTranslation($value): ?string |
64
|
|
|
{ |
65
|
|
|
return Arr::get( |
66
|
|
|
Lang::get('enum::validation.enums'), |
67
|
|
|
$this->enum.'.'.Str::slug((string) $this->asEnum($value), '_') |
68
|
|
|
); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
protected function getOtherValues(): array |
72
|
|
|
{ |
73
|
|
|
return array_keys(forward_static_call([$this->enum, 'toArray'])); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* @param int|string|\Spatie\Enum\Enum $value |
78
|
|
|
* |
79
|
|
|
* @return Enum |
80
|
|
|
* |
81
|
|
|
* @throws \BadMethodCallException |
82
|
|
|
*/ |
83
|
|
|
protected function asEnum($value): Enum |
84
|
|
|
{ |
85
|
|
|
return forward_static_call( |
86
|
|
|
[$this->enum, 'make'], |
87
|
|
|
$value |
88
|
|
|
); |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|