This library provides helpers for several enum operations:
- compare
- to array
It also provides an abstract EnumTestCase
.
composer require oskarstark/enum-helper
For example, you have the following Enum:
<?php
declare(strict_types=1);
namespace App\Enum;
enum Color: string
{
case RED = 'red';
case BLUE = 'blue';
}
You can use the following trait,
<?php
declare(strict_types=1);
namespace App\Enum;
+use OskarStark\Enum\Trait\Comparable;
+use OskarStark\Enum\Trait\ToArray;
enum Color: string
{
+ use Comparable;
+ use ToArray;
case RED = 'red';
case BLUE = 'blue';
}
This trait
gives you the possibility to compare you enum
with another one or a collection of enums like the
following:
App\Enum\Color::RED->equals(App\Enum\Color::BLUE); // returns false
App\Enum\Color::RED->notEquals(App\Enum\Color::RED); // returns false
App\Enum\Color::RED->equalsOneOf([
App\Enum\Color::BLUE,
App\Enum\Color::RED,
]); // returns true
For example, you want to check if a color is a nice color:
<?php
declare(strict_types=1);
namespace App\Enum;
use OskarStark\Enum\Trait\Comparable;
use OskarStark\Enum\Trait\ToArray;
enum Color: string
{
use Comparable;
use ToArray;
case RED = 'red';
case BLUE = 'blue';
case GREEN = 'green';
public function isNice(): bool
{
return self::equalsOneOf([
self::BLUE,
self::GREEN
]);
}
}
App\Enum\Color::RED->isNice(); // returns false
App\Enum\Color::BLUE->isNice(); // returns true
This trait
gives you the possibility to get an enum as array like the following:
App\Enum\Color::toArray(); // returns ['RED' => 'red', 'BLUE' => 'blue']
App\Enum\NonBackedEnum::toArray(); // returns ['RED' => 'RED', 'BLUE' => 'BLUE']