Files
tez-utils-enum/src/TranslatableTrait.php
T
rhalberstadt 5fd843f8c4
PHP Composer / build (push) Failing after 40s
Updated Namespace
2026-08-23 20:06:44 +02:00

55 lines
1.2 KiB
PHP

<?php
declare(strict_types=1);
namespace Tezmanian\Utils\Enum;
/**
* Provides human-readable labels for enum cases without any framework dependency.
*
* Override {@see labels()} in the enum to provide custom label mappings.
* Falls back to the case name when no label is defined.
*
* @phpstan-require-implements \UnitEnum
*
* @method static list<static> cases()
*/
trait TranslatableTrait
{
/**
* Override this method in the enum to provide custom label mappings.
* Keys must be case names (e.g. self::Active->name).
*
* @return array<string, string>
*/
protected static function labels(): array
{
return [];
}
/**
* Returns the human-readable label for this case.
* Falls back to the case name if no label is configured.
*/
public function label(): string
{
return static::labels()[$this->name] ?? $this->name;
}
/**
* Returns all cases mapped to their labels.
*
* @return array<string, string> [caseName => label]
*/
public static function labelsArray(): array
{
$labels = [];
foreach (static::cases() as $case) {
$labels[$case->name] = $case->label();
}
return $labels;
}
}