legecha / enumpty
在枚举中创建如 label()、description() 或 icon() 等方法的吗?这个非常简单的包为您省去了这项繁琐的工作,并提供了相同的功能,无需实现这些方法。
v1.1.0
2024-02-09 15:42 UTC
Requires
- php: >=8.1
Requires (Dev)
- friendsofphp/php-cs-fixer: dev-master
- pestphp/pest: 2.x-dev
README
描述您的枚举!
您发现自己正在枚举中创建如 label()
、description()
或 icon()
等方法?这个非常简单的包为您省去了这项繁琐的工作,并提供了相同的功能,无需实现这些方法。
相反,只需使用属性来描述您的案例!
示例
只需使用 Describable
特性,并使用命名参数通过 DescribeEnum
属性来描述您的案例。
枚举值上的方法现在可用,以及枚举类型上的静态 *Cases
方法。
use Legecha\Enumpty\Attributes\DescribeEnum; use Legecha\Enumpty\Describable; enum MyEnum { use Describable; #[DescribeEnum(label: 'My First Case', description: "My first description")] case First; #[DescribeEnum(description: "My second description", label: 'My 2nd Case']) case Second; case Third; #[DescribeEnum(label: 'My Fourth Case')] case Fourth; } $enum = MyEnum::First; $enum->label(); // string(13) "My First Case" $enum->description(); // string(20) "My first description" $enum = MyEnum::Third; $enum->description(); // NULL MyEnum::labelCases(); /* array(4) { ["MyEnum::First"]=> string(13) "My First Case" ["MyEnum::Second"]=> string(11) "My 2nd Case" ["MyEnum::Third"]=> NULL ["MyEnum::Fourth"]=> string(14) "My Fourth Case" } */ MyEnum::descriptionCases(); /* array(4) { ["MyEnum::First"]=> string(20) "My first description" ["MyEnum::Second"]=> string(21) "My second description" ["MyEnum::Third"]=> NULL ["MyEnum::Fourth"]=> NULL } */
但是,还有更多!
还有 Names
特性,它提供了一个 name()
方法来获取枚举案例名称的“美观”版本,以及一个 names()
静态方法来检索特定枚举的所有名称。无需属性。
use Legecha\Enumpty\Names; enum MyEnum { use Names; case MyFirstCase; case Second; case HereIsTheThird; case DontForgetTheFourth; } $enum = MyEnum::MyFirstCase; $enum->name(); // string(13) "My First Case" MyEnum::HereIsTheThird->name(); // string (15) "Here Is The Third" MyEnum::names(); /* array(4) { ["MyEnum::MyFirstCase"]=> string(13) "My First Case" ["MyEnum::Second"]=> string(6) "Second" ["MyEnum::HereIsTheThird"]=> string(15) "Here Is The Third" ["MyEnum::DontForGetTheFourth"]=> string(23) "Dont Forget The Fourth" } */
安装
composer require legecha/enumpty
问题和贡献
这是一个非常简单的包,但非常欢迎拉取请求。请在这样做之前包括一个测试并清理代码。
composer test
composer fix