intrfce / enum-attribute-descriptors
使用属性为您的PHP枚举提供标题和描述。
v0.3.0
2024-08-28 21:01 UTC
Requires
- php: ^8.1.0
Requires (Dev)
- orchestra/testbench: ^9.1
- pestphp/pest: ^2.23
- phpunit/phpunit: ^10.0
- tightenco/duster: ^2.5
README
您是否曾经为某些东西编写过枚举,并且想要有一个“漂亮”的枚举名称,所以您会写一些像这样
<?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), }; } }
但问题是,对于每个新的case
,您都必须在match
语句中添加一些内容,或者希望使用default
回退打印出可读的内容?
使用这个包,您可以将标题甚至描述与枚举案例一起定位,如下所示
<?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'; }
酷吧!
安装
您可以通过composer安装此包
composer require intrfce/enum-attribute-descriptors
使用方法
只需将Intrfce\EnumAttributeDescriptors\Concerns\HasAttributeDescriptors
特质添加到您的枚举中,您就可以开始了!
定义回退。
如果您有一种情况,您不想(或不能)为每个案例定义描述或标题,您可以在枚举类上覆盖titleFallback()
和descriptionFallback()
方法。
public function titleFallback(): ?string { return ucfirst($this->value); } public function descriptionFallback(): ?string { return 'This option has no description yet'; }
简单!
鸣谢
许可证
MIT许可证(MIT)。请参阅许可证文件以获取更多信息。