Skip to content

Commit

Permalink
Add EnumEnhancement
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewbaggett committed Apr 14, 2024
1 parent ffc259e commit db772fa
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 0 deletions.
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
93 changes: 93 additions & 0 deletions src/Enums/EnumEnhancement.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
<?php

declare(strict_types=1);

namespace Benzine\Enum;

use Othyn\PhpEnumEnhancements\Traits\EnumEnhancements as OthynEnumEnhancements;

trait EnumEnhancements
{
use OthynEnumEnhancements;

public static function fromName(\BackedEnum | string $seekName)
{
if ($seekName instanceof \BackedEnum) {
return $seekName;
}
foreach (self::cases() as $name => $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)];
}
}

0 comments on commit db772fa

Please sign in to comment.