fuwasegu / php-enum-util
PHP原生日志库的扩展库。
3.0.0
2023-02-28 09:05 UTC
Requires
- php: ^8.1
Requires (Dev)
- phpstan/phpstan: ^1.9
- phpunit/phpunit: ^9.5
- yumemi-inc/php-cs-fixer-config: ^8.1
This package is auto-updated.
Last update: 2024-09-28 12:54:23 UTC
README
PHP原生日志库的扩展库。
📦 安装
composer require fuwasegu/php-enum-util
✏️ 使用
此库提供了特质,使PHP 8.1以来实现的Enum更易于使用。
HasDescription特质
此特质提供了一个访问description()
方法的接口,以及descriptions()
方法的实现。
enum Status: string { use HasDescription; case ACTIVE = 'active'; case INACTIVE = 'inactive'; case RETIED = 'retired'; public function description(): string { return match ($this) { self::ACTIVE => 'State in which the employee is enrolled.', self::INACTIVE => 'State in which the employee is on administrative leave.', self::RETIED => 'State in which employee is retiring.', }; } }
// Getter for Enum description Status::ACTIVE->description(); // Getter for Enum value and description maps Status::descriptions();
HasLabel特质
此特质提供了一个访问label()
方法的接口,以及labels()
方法的实现。
enum Capital: int { use HasLabel; case TOKYO = 1; case BEIJING = 2; case WASHINGTON = 3; case LONDON = 4; public function label(): string { return match ($this) { self::TOKYO => 'Tokyo', self::BEIJING => 'Beijing', self::WASHINGTON => 'Washington', self::LONDON => 'London', }; } }
// Getter for Enum label Status::ACTIVE->label(); // Getter for Enum value and label maps Status::labels();
📌 注意
HasLabel和HasDescription特质之间没有实现上的差异。差异在于方法名称。
如果你想为枚举提供一个简短的标签,请选择前者;如果你想提供一个长描述,请选择后者。
HasValues特质
此特质是Enum中最初实现的cases()
方法的值版本,并提供辅助方法。
enum Status: string { use HasValues; case ACTIVE = 'active'; case INACTIVE = 'inactive'; case RETIED = 'retired'; }
// Getter for Enum values Status::values(); // Join Enum values with a string Status::implodeValues();
HasNames特质
此特质是Enum中最初实现的cases()
方法的名版本,并提供辅助方法。
enum Status: string { use HasNames; case ACTIVE = 'active'; case INACTIVE = 'inactive'; case RETIED = 'retired'; }
// Getter for Enum names Status::names(); // Join Enum names with a string Status::implodeNames();
Comparable特质
此特质提供了一个用于轻松比较Backed Enums的方法
enum Status: string { use Comparable; case ACTIVE = 'active'; case INACTIVE = 'inactive'; case RETIED = 'retired'; }
// Compare Enum peer to peer $maybeActive = Status::ACTIVE; Status::ACTIVE->is($maybeActive); // true Status::INACTIVE->isNot($maybeActive); // false // Attempts to convert the compared int or string to an Enum with Enum::tryFrom before comparing // If tryFrom is null, `isFrom()` returns false and `isNotFrom()` returns true. $value = 'active'; Status::ACTIVE->isFrom($value); // true Status::INACTIVE->isNotFrom($value); // false Status::ACTIVE->isFrom('foo'); // false Status::ACTIVE->isNotFrom('foo') // true