Enum Metadata
A native PHP enum holds a value and a name, but nothing for display. A select box needs a label, a status badge needs a color, and an admin page may need an icon or a set of extra settings. Keeping these in a match or a parallel array means every new case has to be updated in several places. Attributes on the enum cases keep this data next to the case it describes.
Minimal Setup
Use EnumRichTrait in an enum that implements EnumRichInterface, then put attributes on the cases:
use Windwalker\Utilities\Attributes\Enum\Title;
use Windwalker\Utilities\Enum\EnumRichInterface;
use Windwalker\Utilities\Enum\EnumRichTrait;
enum Status: string implements EnumRichInterface
{
use EnumRichTrait;
#[Title('Draft')]
case Draft = 'draft';
}
Status::Draft->getTitle(); // DraftEnumMetaTrait provides the metadata getters without the translation helpers of EnumRichTrait.
Showcase: A Status Selector
The following enum provides the labels, colors, and icons for an editor's status field. Each case carries its own metadata:
use Windwalker\Utilities\Attributes\Enum\Color;
use Windwalker\Utilities\Attributes\Enum\Hidden;
use Windwalker\Utilities\Attributes\Enum\Icon;
use Windwalker\Utilities\Attributes\Enum\Meta;
use Windwalker\Utilities\Attributes\Enum\Title;
use Windwalker\Utilities\Enum\EnumRichInterface;
use Windwalker\Utilities\Enum\EnumRichTrait;
enum Status: string implements EnumRichInterface
{
use EnumRichTrait;
#[Title('Draft'), Icon('fa-pencil'), Color('gray')]
#[Meta(['weight' => 1])]
case Draft = 'draft';
#[Title('Published'), Icon('fa-check'), Color('green')]
case Published = 'published';
#[Hidden, Title('Archived'), Color('red')]
case Archived = 'archived';
// Optional translation key for getTitle($lang) and getTransItems($lang)
protected function translateKey(string $name) : string
{
return 'app.enum.status.' . $name;
}
}
Status::getTitles();
// [
// 'draft' => 'Draft',
// 'published' => 'Published',
// 'archived' => 'Archived',
// ]
Status::getColors();
// ['draft' => 'gray', 'published' => 'green', 'archived' => 'red']
Status::Draft->getIcon(); // fa-pencil
Status::Draft->getMeta(); // ['weight' => 1]getTitles() and getColors() return arrays keyed by the case value, which is what a select box or a badge map needs. A case without an attribute returns an empty string or an empty array, so the methods never fail for a missing attribute.
Titles and Translations
Title takes a plain string, a translation key, or both:
#[Title('Published')]
case Published = 'published';
#[Title(string: 'Published', lang: 'status.published')]
case Published = 'published';The rule for getTitle() depends on whether you pass a language object:
- Without a language object, or when the attribute has no
langkey, the method returns thestringof theTitle. - With a language object, the method first looks for the translation of the case, using the key
app.enum.<enum-name>.<CASE>built byEnumRichTrait. If that translation exists, it is returned. Otherwise, thelangkey of theTitleattribute is translated.
Status::Published->getTitle(); // Published
Status::Published->getTitle($lang); // translated, or the Title keyINFO
Title must have a string or a lang. An empty Title throws an InvalidArgumentException when the attribute is read.
getTransItems() builds the same kind of array as getTitles(), using the language object for each case.
Hidden Cases
Hidden marks a case for the interface, so you can ask isHidden():
Status::Archived->isHidden(); // true
Status::Draft->isHidden(); // falseHidden does not remove the case from cases(), getTitles(), or fromTitle(). Code that builds a list for users must check isHidden() itself.
Default Values with preprocessValue
wrap() and tryWrap() call preprocessValue() before they look up the case. Override it to map an empty input to a default case:
enum Status: string implements EnumRichInterface
{
use EnumRichTrait;
#[Title('Draft')]
case Draft = 'draft';
#[Title('Published')]
case Published = 'published';
public static function preprocessValue(mixed $value): mixed
{
return $value ?: self::Draft;
}
}
Status::wrap(null); // Status::Draft
Status::wrap(''); // Status::Draft
Status::wrap('published'); // Status::PublishedWARNING
?: also replaces 0, '0', and false. If one of your case values is falsy, check for null or '' explicitly instead:
public static function preprocessValue(mixed $value): mixed
{
return $value === null || $value === ''
? self::DEFAULT_VALUE
: $value;
}INFO
tryWrap() also runs preprocessValue() before its null check, so tryWrap(null) returns the default case, not null. sameAs() uses tryWrap() internally, so it follows the same rule.
Metadata Methods
The trait provides a getter and a collection method for each attribute:
getTitle()andgetTitles()forTitle.getIcon()andgetIcons()forIcon.getColor()andgetColors()forColor.getMeta()andgetMetas()forMeta.
fromTitle() returns the case whose title matches a string, and tryFromTitle() returns null when no title matches:
Status::fromTitle('Draft'); // Status::Draft
Status::tryFromTitle('Unknown'); // nullMethod Summary
| Method | Parameters | Description |
|---|---|---|
preprocessValue() | mixed $value | Hook run by wrap() and tryWrap(); override to set a default. |
wrap() | mixed $value | The case for a value, after preprocessValue(). Throws on no match. |
tryWrap() | mixed $value | Like wrap(), but returns null when no case matches. |
getTitle() | ?LanguageInterface $lang = null, ...$args | Title of the case, translated when a language is given. |
getTitles() | None | Titles keyed by case value. |
getTransItems() | LanguageInterface $lang, ...$args | Translated titles keyed by case value. |
fromTitle() | string $title | The case with a matching title. |
tryFromTitle() | string $title | The case with a matching title, or null. |
getIcon() / getIcons() | None | Icon of the case, or all icons. |
getColor() / getColors() | None | Color of the case, or all colors. |
getMeta() / getMetas() | None | Meta array of the case, or all meta arrays. |
isHidden() | None | Whether the case has Hidden. |
Title attribute | string $string = '', string $lang = '' | Title text and optional translation key. |
Icon attribute | string $icon | Icon name. |
Color attribute | string $color | Color name. |
Meta attribute | array $meta | Arbitrary data for the case. |
Hidden attribute | None | Marks the case as hidden. |
Related
- Attributes: the generic attribute reader that these attributes build on.