rocksheep / enum-helpers
A collection of helper functions for working with enums in PHP
Requires
- php: ^8.1
Requires (Dev)
- pestphp/pest: ^2.34
- phpstan/phpstan: ^1.11
README
This package provides a set of utilities to work with PHP enums, making it easier to convert enums to arrays and handle hidden enum cases. It leverages PHP 8.1's enum feature, adding functionality to enhance its usability within your projects.
Installation
You can install the package via composer:
composer require rocksheep/enum-helpers
Usage
Basic Usage
To use the EnumToArray
trait in your enum, simply use it within your enum definition:
use Rocksheep\EnumHelpers\EnumToArray; enum YourEnum: string { use EnumToArray; case Example = 'example'; }
This will allow you to convert your enum cases to an array easily.
Hiding Enum Cases
To hide specific enum cases from being listed, use the Hidden attribute:
use Rocksheep\EnumHelpers\Attributes\Hidden; use Rocksheep\EnumHelpers\EnumToArray; enum YourEnum: string { use EnumToArray; case Visible = 'visible'; #[Hidden] case Hidden = 'hidden'; }
Converting Enum to Array
To convert an enum to an array, simply call the toArray
method:
$array = YourEnum::toArray(); // ['visible' => 'Visible']
Testing
To run the tests, execute:
./vendor/bin/pest
Or you can use:
composer test
Contributing
Contributions are welcome! Please feel free to submit a pull request.
License
The package is open-sourced software licensed under the MIT license.