2021-03-17 00:52:03 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace Kwaadpepper\Enum\Rules;
|
|
|
|
|
|
|
|
|
|
use BadMethodCallException;
|
|
|
|
|
use TypeError;
|
|
|
|
|
|
2021-09-12 00:05:38 +02:00
|
|
|
/**
|
|
|
|
|
* Custom Rule to validate an enum
|
|
|
|
|
*/
|
2021-03-17 00:52:03 +01:00
|
|
|
class EnumIsValidRule extends BaseEnumRule
|
|
|
|
|
{
|
2021-09-11 11:11:21 +02:00
|
|
|
|
2021-03-17 00:52:03 +01:00
|
|
|
/**
|
|
|
|
|
* Determine if the validation rule passes.
|
|
|
|
|
*
|
|
|
|
|
* @param string $attribute
|
|
|
|
|
* @param mixed $value
|
|
|
|
|
* @return bool
|
|
|
|
|
*/
|
2021-09-11 11:11:21 +02:00
|
|
|
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassBeforeLastUsed
|
2021-03-17 00:52:03 +01:00
|
|
|
public function passes($attribute, $value): bool
|
|
|
|
|
{
|
|
|
|
|
try {
|
|
|
|
|
// try cast to int if is int
|
2021-09-11 22:45:27 +02:00
|
|
|
$value = (is_numeric($value) and floatval(intval($value)) === floatval($value)) ?
|
|
|
|
|
(int)$value : $value;
|
2021-03-17 00:52:03 +01:00
|
|
|
forward_static_call([$this->enumClass, 'make'], $value);
|
2021-09-12 00:05:38 +02:00
|
|
|
} catch (TypeError | BadMethodCallException $e) {
|
2021-03-17 00:52:03 +01:00
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
/**
|
|
|
|
|
* Get the validation error message.
|
|
|
|
|
*
|
|
|
|
|
* @return string
|
|
|
|
|
*/
|
|
|
|
|
public function message(): string
|
|
|
|
|
{
|
2021-09-12 00:05:38 +02:00
|
|
|
return trans('enum::enum.notInList', [
|
|
|
|
|
'values' => implode(',', forward_static_call([$this->enumClass, 'toValues']))
|
|
|
|
|
]);
|
2021-03-17 00:52:03 +01:00
|
|
|
}
|
|
|
|
|
}
|