Skip to content

Commit

Permalink
add enum label string type check
Browse files Browse the repository at this point in the history
  • Loading branch information
pfilsx committed Feb 27, 2023
1 parent 860fdea commit 9c81ccc
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
2 changes: 1 addition & 1 deletion src/DBAL/Contract/EnumInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
interface EnumInterface
{
/**
* @return array<int|string>
* @return string[]
*/
public static function cases(): array;
}
25 changes: 21 additions & 4 deletions src/Tools/EnumTool.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ final class EnumTool
*/
public static function getEnumTypeNameFromClassName(string $className): string
{
self::checkEnumExists($className);
self::checkEnumExistsAndValid($className);

$classNameParts = \explode('\\', $className);

Expand All @@ -33,7 +33,7 @@ public static function getEnumTypeNameFromClassName(string $className): string
*/
public static function getEnumLabelsByClassName(string $className): array
{
self::checkEnumExists($className);
self::checkEnumExistsAndValid($className);

return \array_map(
static function (mixed $case) {
Expand All @@ -50,18 +50,35 @@ static function (mixed $case) {
);
}

private static function checkEnumExists(string $className): void
private static function checkEnumExistsAndValid(string $className): void
{
if (self::$checkMap[$className] ?? false) {
return;
}

if (!\enum_exists($className) && (!\class_exists($className) || is_subclass_of($className, EnumInterface::class))) {
if (!\enum_exists($className) && (!\class_exists($className) || !is_subclass_of($className, EnumInterface::class))) {
throw new InvalidArgumentException(
sprintf('Invalid enum className specified: %s. Enum class has to be a php8 enum or implements %s', $className, EnumInterface::class)
);
}

if (enum_exists($className) && self::isIntBackedEnum($className)) {
throw new InvalidArgumentException(
sprintf('Invalid enum className specified: %s. PostgreSQL supports only string values for enums', $className)
);
}

self::$checkMap[$className] = true;
}

/**
* @param class-string<\UnitEnum> $className
* @return bool
*/
private static function isIntBackedEnum(string $className): bool
{
$fistCase = ($className::cases()[0] ?? null);

return $fistCase instanceof \BackedEnum && is_int($fistCase->value);
}
}

0 comments on commit 9c81ccc

Please sign in to comment.