Reduce duplicated code between enumValues and enumNames

This commit is contained in:
Alejandro Celaya
2025-07-04 09:52:35 +02:00
parent 314a99862d
commit f4aaf02d55

View File

@@ -256,14 +256,7 @@ function toProblemDetailsType(string $errorCode): string
*/
function enumValues(string $enum): array
{
static $cache;
if ($cache === null) {
$cache = [];
}
return $cache[$enum] ?? (
$cache[$enum] = array_map(static fn (BackedEnum $type) => (string) $type->value, $enum::cases())
);
return enumSide($enum, 'value');
}
/**
@@ -271,14 +264,27 @@ function enumValues(string $enum): array
* @return string[]
*/
function enumNames(string $enum): array
{
return enumSide($enum, 'name');
}
/**
* @param class-string<BackedEnum> $enum
* @param 'name'|'value' $type
* @return string[]
*/
function enumSide(string $enum, string $type): array
{
static $cache;
if ($cache === null) {
$cache = [];
}
return $cache[$enum] ?? (
$cache[$enum] = array_map(static fn (BackedEnum $type) => (string) $type->name, $enum::cases())
return $cache[$type][$enum] ?? (
$cache[$type][$enum] = array_map(
static fn (BackedEnum $entry) => (string) ($type === 'name' ? $entry->name : $entry->value),
$enum::cases(),
)
);
}