dive-be / php-enum-utils
Those utilities you always need when dealing with native enumerations.
Installs: 257 753
Dependents: 1
Suggesters: 0
Security: 0
Stars: 31
Watchers: 0
Forks: 0
Open Issues: 0
Requires
- php: ~8.3
Requires (Dev)
- phpunit/phpunit: ^11.0
README
This library provides a collection of native enum utilities (traits) which you almost always need in every PHP project.
Installation
You can install the package via composer:
composer require dive-be/php-enum-utils
Usage
Assume the following string
backed enum:
enum Role: string { use \Dive\Enum\Arrayable; use \Dive\Enum\Assertable; use \Dive\Enum\Comparable; use \Dive\Enum\NameListable; use \Dive\Enum\ValueListable; case Administrator = 'admin'; case Auditor = 'audit'; case Moderator = 'mod'; }
Arrayable (backed enums only)
Allows you to retrieve a key-value pair of names and values:
Role::toArray(); // ['Administrator' => 'admin', 'Auditor' => 'audit', 'Moderator' => 'mod']
Assertable
This relies on the enum names being in PascalCase, which follows Larry Garfield's RFC.
Allows you to make assertions on enum instances using predicate functions:
$role = Role::Moderator; $role->isAuditor(); // false $role->isModerator(); // true
Comparable
Allows you to compare enums. Mostly useful when providing backed values:
$role = Role::Administrator; $role->equals('admin'); // true $role->equals(Role::Administrator); // true $role->equals('mod'); // false $role->equals(Role::Moderator); // false $role->equalsAny(['admin', 'mod', 'audit']); // true $role->equalsAny([Role::Administrator, Role::Auditor]); // true $role->equalsAny([Role::Moderator, 'audit']); // false
NameListable
Allows you to retrieve a list of the enum names:
Role::toNames(); // ['Administrator', 'Auditor', 'Moderator']
ValueListable (backed enums only)
Allows you to retrieve a list of the enum values:
Role::toValues(); // ['admin', 'audit', 'mod']
WithUtilities (backed enums only)
Aggregator trait for all of the aforementioned utilities.
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security
If you discover any security related issues, please email oss@dive.be instead of using the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.