cruxinator/php-bitmask

PHP 位掩码实现

0.2.0 2023-09-16 06:46 UTC

This package is auto-updated.

Last update: 2024-09-19 11:43:48 UTC


README

Build Status Scrutinizer Code Quality Coverage Status Latest Stable Version Latest Unstable Version Total Downloads Monthly Downloads Daily Downloads

为什么?

首先,最主要的是,myclabs/php-enum受限制且不能组合(Enum::FOO() | Enum::BAR() 也不太好用)。

使用位掩码而不是整数有以下优点

  • 你可以进行类型提示:function setAction(Bitmask $action) {;
  • 你可以为位掩码添加方法(例如 formatparse 等);
  • 你可以扩展位掩码以添加新值(使你的枚举 final 以防止它);
  • 你可以获取所有可能值的列表(见下文);
  • 位掩码可以在单个值中包含许多枚举。

这个位掩码类不是为了取代枚举,而是当有实际意义时才使用。

安装

composer require cruxinator/php-bitmask

声明

use Cruxinator\BitMask\BitMask ;

class UserStatus extends BitMask
{

const Registered = 1; // BIT #1 of $flags has the value 1

const Active = 2; // BIT #2 of $flags has the value 2

const Member = 4; // BIT #3 of $flags has the value 4

const Admin = 8; // BIT #4 of $flags has the value 8

}

用法

$status = UserStatus::Registered();

// or with a dynamic key:
$status = UserStatus::$key();
// or with a dynamic value:
$status = new UserStatus($value);

// values can then be checked
if ($status->isActive()){
// ...
}

// individuals flags can later toggled ON
$status->setActive(true);
// or off
$status->setActive(false);

如您所见,方法已自动实现,以提供对位掩码值的快速访问。

与使用类常量相比的一个优点是可以对位图值进行类型提示

function setStatus(UserStatus $action) {
    // ...
}

文档

  • __construct() 构造函数检查值是否可以由枚举组合;
  • __toString() 你可以 echo $myValue,它将显示位掩码值(以布尔数组格式显示);
  • getValue() 返回位掩码的当前值
  • getKey() 返回位掩码当前组合部分的键数组
  • equals() 测试位掩码实例是否相等(如果枚举值相等则返回 true,否则返回 false);

静态方法

  • toArray() 返回所有可能值的数组(键为常量名称,值为常量值);
  • keys() 返回枚举类中所有常量的名称(键);
  • values() 返回所有枚举常量的枚举类实例(键为常量名称,值为枚举实例);
  • isValid() 检查测试值是否在枚举集中有效;
  • isValidKey() 检查测试键是否在枚举集中有效;
  • search() 返回搜索值的键;

动态方法

class UserStatus extends BitMask
{
    private const Registered = 1;
    private const Active = 2;
}

// Static method:
$status = UserStatus::Registered();
$status = UserStatus::Active();

// instance methods
$status->isRegistered();
$status->isActive();
$status->setRegistered($bool);
$status->setActive($bool);

使用 __callStatic()__call() 实现了静态方法辅助器。

如果你关心 IDE 自动完成,你可以自己实现静态方法

class UserStatus extends BitMask
{
    private const Registered = 1;

    /**
     * @return UserStatus
     */
    public static function Registered() {
        return new UserStatus(self::Registered);
    }
    /**
     * @return bool
     */
    public function isRegistered(){
        return $this->isFlagSet(self::Registered);
    }
    /**
     * @param bool $flag
     * @return self
     */
    public function setRegistered(bool $flag){
        return $this->setFlag(self::Registered, $flag);
    }
}

或者你可以使用 phpdoc(例如,这得到了 PhpStorm 的支持)

/**
 * @method static UserStatus Registered()
 * @method bool isRegistered()
 * @method UserStatus setRegistered(bool)
 */
class UserStatus extends Bitmask
{
    private const Registered = 1;
}

相关项目