anteris-dev/enum-descriptions

为枚举添加描述属性。

v0.1.0 2022-01-31 16:54 UTC

This package is auto-updated.

Last update: 2024-08-29 05:31:49 UTC


README

此包通过利用 Description 属性为 PHP 枚举添加描述。

安装方法

使用 composer 安装此包,运行以下命令

composer require anteris-dev/enum-descriptions

入门指南

您可以使用 Description 属性指定一个 case 的描述,如下所示。如果 case 上没有设置描述,其名称将通过大写字母分割,用空格连接,然后首字母大写(例如,someValue 变为 Some value)。

use AnterisDev\EnumDescriptions\Description;

enum Animal
{
    #[Description('A cute dog.')]
    case Dog;
    
    #[Description('A fuzzy cat.')]
    case Cat;
}

获取描述

有几个助手函数可以帮助您检索描述。首先是全局函数。

全局函数

// Accepts an enum class name and returns an array. Enum values are represented in the array keys
// and enum descriptions are represented as those key values.
enum_descriptions(Animal::class);

// Returns the string description for the specific enum passed.
enum_description(Animal::Dog);

特质

您还可以将 HasDescriptions 特质添加到枚举中,以在该处暴露一些有用的函数。

use AnterisDev\EnumDescriptions\HasDescriptions;

enum Animal
{
    use HasDescriptions;
}

// Returns an array. Enum values are represented in the array keys and enum
// descriptions are represented as those key values.
Animal::descriptions();

// Returns the description for the specific value specified.
Animal::Dog->description();