intrfce / enum-attribute-descriptors
Use attributes to give your PHP enums titles and descriptions.
Installs: 48
Dependents: 0
Suggesters: 0
Security: 0
Stars: 7
Watchers: 1
Forks: 0
Open Issues: 0
pkg:composer/intrfce/enum-attribute-descriptors
Requires
- php: ^8.1.0
Requires (Dev)
- orchestra/testbench: ^9.1
- pestphp/pest: ^2.23
- phpunit/phpunit: ^10.0
- tightenco/duster: ^2.5
README
Have you ever written an enum for something and wanted to have a "nice" version of the enum name, so you write something like this:
<?php enum Colour: string { case RED = 'red'; case BLUE = 'blue'; case GREEN = 'green'; public function getTitle() { return match($this->value) { 'blue' => "Dark Blue", 'red' => "Blood Red" default => ucfirst($this->value), }; } }
But the problem is, for each new case, you have to add something to the match statement, or HOPE that it'll print something out that's legible using the default fallback?
With this package, you can co-locate titles, and even descriptions, with your enum cases like so:
<?php enum Colour: string { use HasAttributeDescriptors; #[Title('Blood Red')] #[Description('Our primary highlight colour')] case RED = 'red'; #[Title('Dark Blue')] #[Description('Our primary logo colour')] case BLUE = 'blue'; #[Title('Army Green')] #[Description('Only use this for background colours.')] case GREEN = 'green'; }
Neat huh!
Installation
You can install the package via composer:
composer require intrfce/enum-attribute-descriptors
Usage
Just add the Intrfce\EnumAttributeDescriptors\Concerns\HasAttributeDescriptors trait to your enum, and you're good to go!
Defining fallbacks.
If you have a situation where you don't want to (or can't) define a description or title for each case, you can override
the titleFallback() and descriptionFallback() methods on your enum class.
public function titleFallback(): ?string { return ucfirst($this->value); } public function descriptionFallback(): ?string { return 'This option has no description yet'; }
Simple!
Credits
License
The MIT License (MIT). Please see License File for more information.