55 lines
1.2 KiB
PHP
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;
|
|
}
|
|
}
|