2021-03-17 00:52:03 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace Kwaadpepper\Enum\Rules;
|
|
|
|
|
|
|
|
|
|
use BadMethodCallException;
|
|
|
|
|
use TypeError;
|
|
|
|
|
|
|
|
|
|
class EnumIsValidRule extends BaseEnumRule
|
|
|
|
|
{
|
2021-09-11 11:11:21 +02:00
|
|
|
|
2021-03-17 00:52:03 +01:00
|
|
|
private $messageType = 0;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 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
|
|
|
|
|
$value = is_numeric($value) && floatval(intval($value)) === floatval($value) ? (int)$value : $value;
|
|
|
|
|
forward_static_call([$this->enumClass, 'make'], $value);
|
|
|
|
|
} catch (TypeError $e) {
|
|
|
|
|
$this->messageType = 1;
|
|
|
|
|
return false;
|
|
|
|
|
} catch (BadMethodCallException $e) {
|
|
|
|
|
$this->messageType = 2;
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
/**
|
|
|
|
|
* Get the validation error message.
|
|
|
|
|
*
|
|
|
|
|
* @return string
|
|
|
|
|
*/
|
|
|
|
|
public function message(): string
|
|
|
|
|
{
|
2021-09-11 13:35:17 +02:00
|
|
|
$message = null;
|
2021-03-17 00:52:03 +01:00
|
|
|
switch ($this->messageType) {
|
|
|
|
|
case 1:
|
2021-09-11 13:35:17 +02:00
|
|
|
$message = trans('enum::enum.isNotValid');
|
|
|
|
|
break;
|
2021-03-17 00:52:03 +01:00
|
|
|
case 2:
|
2021-09-11 13:35:17 +02:00
|
|
|
$message = trans('enum::enum.notInList', [
|
2021-03-17 00:52:03 +01:00
|
|
|
'values' => implode(',', forward_static_call([$this->enumClass, 'toValues']))
|
|
|
|
|
]);
|
|
|
|
|
}
|
2021-09-11 13:35:17 +02:00
|
|
|
return \is_string($message) ? $message : 'Invalid Enum';
|
2021-03-17 00:52:03 +01:00
|
|
|
}
|
|
|
|
|
}
|