oskarstark/enum-helper

This library provides helpers for several enum operations

Maintainers

👁 OskarStark

Package info

github.com/OskarStark/enum-helper

pkg:composer/oskarstark/enum-helper

Statistics

Installs: 3 864 448

Dependents: 14

Suggesters: 0

Stars: 14

Open Issues: 1

1.8.4 2026-02-05 08:59 UTC

Requires

  • php: >=8.1

Suggests

None

Provides

None

Conflicts

Replaces

None

MIT 14e185f1cc259d7cd3f61eea17f9b174a886a6da

  • Oskar Stark <oskarstark.woop@googlemail.com>

enum

This package is auto-updated.

Last update: 2026-06-19 08:07:48 UTC


README

This library provides helpers for several enum operations:

  • compare
  • to array

It also provides an abstract EnumTestCase.

👁 CI

Installation

composer require oskarstark/enum-helper

Usage

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 traits:

<?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';
}

Comparable Trait

This trait gives you the possibility to compare your 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

ToArray Trait

This trait gives you the possibility to get an enum as array like the following:

For Backed Enum

App\Enum\Color::toArray(); // returns ['RED' => 'red', 'BLUE' => 'blue']

For Non-Backed Enum

App\Enum\NonBackedEnum::toArray(); // returns ['RED' => 'RED', 'BLUE' => 'BLUE']