wscore/enum

枚举类。

1.0.0 2017-11-10 11:14 UTC

This package is not auto-updated.

Last update: 2024-09-15 05:44:32 UTC


README

枚举和列表实现

许可

MIT 许可证

安装

composer require "wscore/enum: ^1.0"

示例代码

创建一个 EnumList 类

创建枚举类的预期方式是,

  1. 定义常量,
  2. 定义静态 $choices 数组。

如下例所示。

use WScore\Enum\AbstractEnum;

class EnumList extends AbstractEnum
{
    const ENUM = 'enum';
    const VALUE = 'value';
    
    protected static $choices = [
        self::ENUM => 'enumerated',
        self::VALUE => 'value',
    ];
}

$choices 变量定义了可用的值以及标签(即人类可读的字符串)。

获取枚举对象

静态函数 enum 返回一个实例化的枚举对象,它是 EnumInterface

$enum = EnumList::enum(EnumList::ENUM);
(string) $enum; // enum
$enum->label(); // enumerated
$enum->is(EnumList::ENUM); // true

枚举列表和键

使用静态方法,如 choices()keys()flipped(),来获取可用的枚举值和键的列表,这些值和键可用于验证输入。

$list = EnumList::choices(); // returns list of keys and labels. 
$keys = EnumList::keys();    // returns keys of enumerated list. 
$flip = EnumList::flipped(); // returns array of key/value flipped.

选择子集

在某些用例中,您可能需要限制可选值。例如,下面的 ActiveList 类有 3 种状态,但可能只想将 2 个选项限制为最终用户,如 userChoice 中定义的。

class ActiveList extends AbstractEnum
{
    const ACTIVE = 'active';
    const CANCEL = 'cancel';
    const HOLD   = 'hold';
    
    protected static $choices = [
        self::ACTIVE => 'activated',
        self::CANCEL => 'canceled',
        self::HOLD   => 'hold-on',
    ];

    /**
     * @return array
     */
    public static function userChoice()
    {
        return [
            self::ACTIVE => 'activated',
            self::CANCEL => 'canceled',
        ];
    }
}

要获取可用的选择,

$list = ActiveList::userChoice(); 
$keys = ActiveList::keys('userChoice');
$flip = ActiveList::flipped('userChoice');

真正限制列表的使用

要真正将选择限制为原始 static::$choices 的子集...

use WScore\Enum\AbstractEnum;

class EnumList extends AbstractEnum
{
    const ENUM = 'enum';
    const VALUE = 'value';
    protected static $choices = [
        self::ENUM => 'enumerated',
        self::VALUE => 'value',
    ];

    /**
     * @param string $value
     * @return EnumList
     */
    public static function getUserEnum($value)
    {
        $choices = self::$choices;
        unset($choices[self::VALUE]);
        return new EnumList($value, $choices);
    }
}

然后,以下代码将抛出 \InvalidArgumentException。

$enum = EnumList::getUserEnum(EnumList::VALUE);