1 | <?php |
||
13 | { |
||
14 | /** @var string|Enum */ |
||
15 | protected $enum; |
||
16 | |||
17 | protected string $attribute; |
||
|
|||
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 (Exception $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($this->asEnum($value)->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 |
||
91 |