vaened / php-enum
PHP enumeration support
Requires
- php: ^8.0
Requires (Dev)
- phpunit/phpunit: ^9.0
- symfony/var-dumper: ^6.0
This package is auto-updated.
Last update: 2024-10-29 05:47:46 UTC
README
Friendly enumeration implementation.
$status = Status::WARNING(); $status->key(); // WARNING $status->value(); // Advertencia // custom attribute $status->getColor(); // yellow
Installation
PHP Enum requires PHP 8.
To get the latest version, simply require the project using Composer:
$ composer require vaened/php-enum
Declaration
To create an enumeration it is necessary to extend from Vaened\Enum\Enum
, in addition to creating constants for each value of the enumeration. This library has the ability to add attributes for each enumeration, very similar to the enumerations in java.
<?php namespace App\Enums; use App\Color; use Vaened\Enum\Attributor; use Vaened\Enum\Enum; class Status extends Enum { // Enums public const WARNING = 'Advertencia'; public const SUCCESS = 'Exito'; }
Usage
Once the enumeration is implemented, you can use its values in the following way. The library uses __callStatic
to create instances of a specified enumeration, according to the requested value.
use App\Enums\Status; // returns an instance of Status, with the value of the constant WARNING Status::WARNING();
In case you want autocompletion ID, you can define the methods manually.
class Status extends Enum { public const WARNING = 'Advertencia'; public static function WARNING(): self { return self::create(self::WARNING); } }
or if you are using some ID that supports phpdocs, you can do something like this:
/** * Class Status * * @method static Status WARNING() */ class Status extends Enum { public const WARNING = 'Advertencia'; }
Advanced
There may be specific cases where you need to add some additional attribute to the enumeration. To do this, you will need to override the protected static method attributes available in all Enum
children, here you must define the attributes you will use for each enumeration.
Must use the
Vaened\Enum\Attributor
class.
Attributor::to('CONSTANT', [ 'name' => 'value' ]);
To get any attribute, you can use the protected method attribute which gets the name of the attribute as parameter
class Status extends Enum { public const SUCCESS = 'Éxito'; public function getColor(): Color { return $this->attribute('color'); } protected static function attributes(): array { return [ Attributor::to('SUCCESS', [ 'color' => new Color('blue'), ]), ]; } }
API
More documentation
You can find a lot of comments within the source code as well as the tests located in the tests
directory.