This library provides a collection of native enum utilities (traits) which you almost always need in every PHP project.
You can install the package via composer:
composer require dive-be/php-enum-utils
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';
}
Allows you to retrieve a key-value pair of names and values:
Role::toArray(); // ['Administrator' => 'admin', 'Auditor' => 'audit', 'Moderator' => 'mod']
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
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
Allows you to retrieve a list of the enum names:
Role::toNames(); // ['Administrator', 'Auditor', 'Moderator']
Allows you to retrieve a list of the enum values:
Role::toValues(); // ['admin', 'audit', 'mod']
Aggregator trait for all of the aforementioned utilities.
composer test
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
If you discover any security related issues, please email oss@dive.be instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.