spareparts / enum
Simple ENUM class.
Installs: 28 758
Dependents: 3
Suggesters: 0
Security: 0
Stars: 3
Watchers: 1
Forks: 3
Open Issues: 3
Requires
- php: >=7.1
Requires (Dev)
- mockery/mockery: ^0.9.6
- phpunit/phpunit: ~5
This package is auto-updated.
Last update: 2024-11-07 15:28:57 UTC
README
PHP Enum done right
Easy way to use enumerated values in PHP.
Installation
Please, use composer.
composer require spareparts/enum
Basic usage
/** * @method static OPEN * @method static CLOSED */ class WindowStateEnum extends \SpareParts\Enum\Enum { } // obtain enum value $state = WindowStateEnum::OPEN(); // assign enum value $windows->state = WindowStateEnum::CLOSED(); // compare enum values if ($window->state === WindowStateEnum::OPEN()) { .... } // use enum to guard method parameters function changeWindowState(WindowStateEnum $newState) { ... }
How to prepare Enum
- extend Enum class
- Annotate enum class with @method annotations describing Enum values
How to use Enum
There are two possible ways to use enum values, with first one being preferred.
- using static methods with same name as your desired value.
This works with help from magic __callStatic method, meaning you do not have to add any methods manually.
$state = WindowStateEnum::OPEN();
This method is preferred, as it nicely shows its intended value without having to use weakly guarded strings.
Important tip: To have values correctly autocompleted, use @method annotations, like this:
/** * @method static OPEN * @method static CLOSED */ class WindowStateEnum extends \SpareParts\Enum\Enum { }
This way, your IDE should know WindowStateEnum
has 2 methods OPEN and CLOSE and correctly hint on their names. In case you are using IDE without support for @method annotations, you can always just add those methods "for real" :)
- using
instance()
method with desired value as instance parameter
$state = WindowStateEnum::instance('OPEN');
There is nothing wrong with this approach, but mistakes/typos can be easily made.
Asking enum for unsupported value
In case you ask for value that is not in the enum values, an InvalidEnumValueException exception is thrown.
try { $window->setState(WindowStateEnum::FLYING()); } catch (InvalidEnumValueException $e) { echo "This is not a correct state for window to be in!"; }
Testing for multiple values
You can check for enum belonging to any of an enum group / set like this:
if ($state->isAnyOf([Window::OPEN(), Window::CLOSED()]));