ldc-dam/app/Rules/EnumIsValidRule.php

66 lines
1.7 KiB
PHP
Raw Normal View History

<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
/**
* Custom Rule to validate an enum
*/
class EnumIsValidRule implements Rule
{
/**
* The enum class
*
* @var string
*/
protected string $enum;
/**
* Create a new rule instance
* which validate the fact that a value is within an Enum
*
* @param string $enumClass
* @return void
* @throws \RuntimeException If not a valid enum.
*/
public function __construct(string $enumClass)
{
if (!enum_exists($enumClass)) {
throw new \RuntimeException("'$enumClass' is not an enum");
}
$this->enumClass = $enumClass;
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return boolean
* @phpcs:disable Squiz.Commenting.FunctionComment.ScalarTypeHintMissing
* @phpcs:disable Squiz.Commenting.FunctionComment.TypeHintMissing
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceBeforeLastUsed
*/
public function passes($attribute, $value): bool
{
// phpcs:enable
try {
return $this->enumClass::tryFrom(\strval($value)) !== false;
} catch (\TypeError) {
return $this->enumClass::tryFrom(\intval($value)) !== false;
}
}
/**
* Get the validation error message.
*
* @return string
*/
public function message(): string
{
return trans('Le champ :attribute doit être une des valeurs suivantes: :values', [
'values' => collect($this->enumClass::cases())->implode(', ')
]);
}
}