-
-
Notifications
You must be signed in to change notification settings - Fork 37
/
Enum.php
80 lines (65 loc) · 1.93 KB
/
Enum.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php
namespace Spatie\Enum\Laravel\Rules;
use Exception;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Spatie\Enum\Enumerable;
use InvalidArgumentException;
use Illuminate\Support\Facades\Lang;
use Illuminate\Contracts\Validation\Rule;
class Enum implements Rule
{
protected $rule = 'enum';
/** @var Enumerable */
protected $enum;
/** @var string */
protected $attribute;
/** @var mixed */
protected $value;
public function __construct(string $enum)
{
if (! class_exists($enum) || ! isset(class_implements($enum)[Enumerable::class])) {
throw new InvalidArgumentException("The given class {$enum} does not implement the Enumerable interface.");
}
$this->enum = $enum;
}
public function passes($attribute, $value): bool
{
$this->attribute = $attribute;
$this->value = $value;
try {
$this->enum::make($value);
return true;
} catch (Exception $ex) {
return false;
}
}
public function message(): string
{
return Lang::trans('enum::validation.'.$this->rule, [
'attribute' => $this->attribute,
'value' => $this->value,
'enum' => $this->enum,
'other' => implode(', ', $this->getDisplayableOtherValues()),
]);
}
protected function getDisplayableOtherValues(): array
{
return array_map(function ($value): string {
return $this->getTranslation($value) ?? $value;
}, $this->getOtherValues());
}
/**
* @param string|int $value
*
* @return string|null
*/
protected function getTranslation($value): ?string
{
return Arr::get(Lang::trans('enum::validation.enums'), $this->enum.'.'.Str::slug($this->enum::make($value)->getName(), '_'));
}
protected function getOtherValues(): array
{
return $this->enum::getValues();
}
}