The package implement ideas from RFC Enumerations and provide abstract class Enum
that intended to create
enumerated objects with support extra data and auxiliary static functions values()
, cases()
and isValid()
.
- PHP 8.0 or higher.
The package could be installed with composer:
composer require vjik/php-enum --prefer-dist
use Vjik\Enum\Enum;
/**
* @method static self NEW()
* @method static self PROCESS()
* @method static self DONE()
*/
final class Status extends Enum
{
private const NEW = 'new';
private const PROCESS = 'process';
private const DONE = 'done';
}
$process = Status::from('process');
On create object with invalid value throws ValueError
.
$process = Status::tryFrom('process'); // Status object with value "process"
$process = Status::tryFrom('not-exists'); // null
On create object with invalid value returns null
.
Static methods are automatically implemented to provide quick access to an enum value.
$process = Status::PROCESS();
Status::DONE()->getName(); // DONE
Status::DONE()->getValue(); // done
Set data in the protected static function data()
and create getters using the protected method getPropertyValue()
.
Also you can create getter using protected method match()
.
use Vjik\Enum\Enum;
/**
* @method static self CREATE()
* @method static self UPDATE()
*/
final class Action extends Enum
{
private const CREATE = 1;
private const UPDATE = 2;
protected static function data(): array
{
return [
self::CREATE => [
'tip' => 'Create document',
],
self::UPDATE => [
'tip' => 'Update document',
],
];
}
public function getTip(): string
{
/** @var string */
return $this->getPropertyValue('tip');
}
public function getColor(): string
{
return $this->match([
self::CREATE => 'red',
self::UPDATE => 'blue',
]);
}
public function getCode(): int
{
return $this->match([
self::CREATE => 1,
], 99);
}
}
Usage:
echo Action::CREATE()->getTip();
echo Action::CREATE()->getColor();
echo Action::CREATE()->getCode();
Returns list of values.
// [1, 2]
Action::values();
Returns list of objects:
// [$createObject, $updateObject]
Action::cases();
Check if value is valid on the enum set.
Action::isValid(1); // true
Action::isValid(99); // false
Enum
support casting to string (using magic method __toString
). The value is returned as a string.
echo Status::DONE(); // done
The package is tested with PHPUnit. To run tests:
./vendor/bin/phpunit
The package tests are checked with Infection mutation framework. To run it:
./vendor/bin/infection
The code is statically analyzed with Psalm. To run static analysis:
./vendor/bin/psalm
The PHP Enum implementation is free software. It is released under the terms of the BSD License. Please see LICENSE
for more information.
Version 3 of this package is inspired by myclabs/php-enum
.