|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Nuxtifyts\PhpDto\Validation\Rules; |
| 4 | + |
| 5 | +use BackedEnum; |
| 6 | +use Nuxtifyts\PhpDto\Exceptions\ValidationRuleException; |
| 7 | +use Nuxtifyts\PhpDto\Support\Arr; |
| 8 | + |
| 9 | +class BackedEnumRule implements ValidationRule |
| 10 | +{ |
| 11 | + /** @var class-string<BackedEnum> */ |
| 12 | + public protected(set) string $backedEnumClass; |
| 13 | + |
| 14 | + /** |
| 15 | + * @var ?array<array-key, BackedEnum> |
| 16 | + */ |
| 17 | + public protected(set) ?array $allowedValues = null; |
| 18 | + |
| 19 | + public string $name { |
| 20 | + get { |
| 21 | + return 'backed_enum'; |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + public function evaluate(mixed $value): bool |
| 26 | + { |
| 27 | + if ($value instanceof $this->backedEnumClass) { |
| 28 | + /** @var BackedEnum $value */ |
| 29 | + $resolvedValue = $value; |
| 30 | + } else if (is_string($value) || is_integer($value)) { |
| 31 | + $resolvedValue = $this->backedEnumClass::tryFrom($value); |
| 32 | + } else { |
| 33 | + return false; |
| 34 | + } |
| 35 | + |
| 36 | + return !!$resolvedValue |
| 37 | + && ( |
| 38 | + is_null($this->allowedValues) |
| 39 | + || in_array($resolvedValue->value, array_column($this->allowedValues, 'value')) |
| 40 | + ); |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * @param ?array<string, mixed> $parameters |
| 45 | + * |
| 46 | + * @throws ValidationRuleException |
| 47 | + */ |
| 48 | + public static function make(?array $parameters = null): self |
| 49 | + { |
| 50 | + $instance = new self(); |
| 51 | + |
| 52 | + $backedEnumClass = $parameters['backedEnumClass'] ?? null; |
| 53 | + |
| 54 | + if ( |
| 55 | + !is_string($backedEnumClass) |
| 56 | + || !enum_exists($backedEnumClass) |
| 57 | + || !is_subclass_of($backedEnumClass, BackedEnum::class) |
| 58 | + ) { |
| 59 | + throw ValidationRuleException::invalidParameters(); |
| 60 | + } |
| 61 | + |
| 62 | + $instance->backedEnumClass = $backedEnumClass; |
| 63 | + $instance->allowedValues = array_filter( |
| 64 | + array_map(static fn (mixed $value) => |
| 65 | + ($value instanceof $instance->backedEnumClass) |
| 66 | + ? $value |
| 67 | + : null, |
| 68 | + Arr::getArray($parameters ?? [], 'allowedValues') |
| 69 | + ) |
| 70 | + ) ?: null; |
| 71 | + |
| 72 | + return $instance; |
| 73 | + } |
| 74 | + |
| 75 | + public function validationMessage(): string |
| 76 | + { |
| 77 | + if ($this->allowedValues) { |
| 78 | + $allowedValues = implode( |
| 79 | + ', ', |
| 80 | + array_map(static fn (BackedEnum $value) => $value->value, $this->allowedValues) |
| 81 | + ); |
| 82 | + |
| 83 | + return "The :attribute field must be one of the following values: $allowedValues."; |
| 84 | + } else { |
| 85 | + return 'The :attribute field is invalid.'; |
| 86 | + } |
| 87 | + } |
| 88 | +} |
0 commit comments