diff --git a/composer.json b/composer.json index 86fcbd9..5094985 100644 --- a/composer.json +++ b/composer.json @@ -53,6 +53,7 @@ "middlewares/trailing-slash": "^2.0", "middlewares/whoops": "^2.0", "monolog/monolog": "^3.6", + "othyn/php-enum-enhancements": "^1.0", "php-di/slim-bridge": "^3.0", "psr/cache": "^1.0", "psr/container": "^1.0", diff --git a/src/Enums/EnumEnhancement.php b/src/Enums/EnumEnhancement.php new file mode 100644 index 0000000..4e3e4f3 --- /dev/null +++ b/src/Enums/EnumEnhancement.php @@ -0,0 +1,93 @@ + $status) { + $name = is_string($status) ? $name : $status->name; + $value = is_string($status) ? $status : $status->value; + if ($name === $seekName) { + return $status; + } + } + + // If there is a default, return it instead of throwing an error + $hasDefault = false; + foreach (self::cases() as $enum) { + if ($enum->name === 'DEFAULT') { + $hasDefault = true; + } + } + if ($hasDefault) { + return self::DEFAULT; + } + + \Kint::dump(sprintf("'%s' is not a valid backing key for enum %s", $seekName, self::class)); + + throw new \ValueError(sprintf("'%s' is not a valid backing key for enum %s", $seekName, self::class)); + } + + public static function fromValue(\BackedEnum | int | string $seekValue) + { + if ($seekValue instanceof \BackedEnum) { + return $seekValue; + } + foreach (self::cases() as $name => $status) { + $name = is_string($status) ? $name : $status->name; + $value = is_string($status) ? $status : $status->value; + if ($value === $seekValue) { + return $status; + } + } + + \Kint::dump(sprintf("'%s' is not a valid backing value for enum %s.", $seekValue, self::class)); + + throw new \ValueError(sprintf("'%s' is not a valid backing value for enum %s", $seekValue, self::class)); + } + + public static function isValidName(string $name): bool + { + try { + self::fromName($name); + } catch (\ValueError) { + return false; + } + + return true; + } + + public static function isValidValue(string $name): bool + { + try { + self::fromValue($name); + } catch (\ValueError) { + return false; + } + + return true; + } + + public static function values(): array + { + return self::cases(); + } + + public static function random(): self + { + $values = self::values(); + + return $values[array_rand($values)]; + } +}