PHPackages                             markbaker/enumhelper - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. markbaker/enumhelper

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

markbaker/enumhelper
====================

A small library that provides Helper Traits for PHP 8.1 Enums

1.0.2(4y ago)2819.4k↓33.3%11MITPHPPHP ^8.1

Since Dec 7Pushed 4y ago1 watchersCompare

[ Source](https://github.com/MarkBaker/EnumHelper)[ Packagist](https://packagist.org/packages/markbaker/enumhelper)[ Docs](https://github.com/MarkBaker/EnumHelper)[ RSS](/packages/markbaker-enumhelper/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (3)Dependencies (4)Versions (5)Used By (1)

A library of helper traits for working with PHP 8.1 enums
=========================================================

[](#a-library-of-helper-traits-for-working-with-php-81-enums)

[![Build Status](https://github.com/MarkBaker/EnumHelper/workflows/main/badge.svg)](https://github.com/MarkBaker/EnumHelper/actions)[![Total Downloads](https://camo.githubusercontent.com/c0b3cbdee2f318e82d7e194b358f0f53780bf85fdcca3f3d519bd1c4eb53d706/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d61726b62616b65722f656e756d68656c706572)](https://packagist.org/packages/markbaker/enumhelper)[![Latest Stable Version](https://camo.githubusercontent.com/decb44cb13f70e846cc433d95b3bc074994fb0b8994f6f2666ff803bbaa37cb5/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f762f72656c656173652f4d61726b42616b65722f456e756d48656c706572)](https://packagist.org/packages/markbaker/enumhelper)[![License](https://camo.githubusercontent.com/845d57415d0d73bd3e60c3d89fa2eac0b936c6fa76a61fea1660bcd4d29d19ca/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f4d61726b42616b65722f456e756d48656c706572)](https://packagist.org/packages/markbaker/enumhelper)

This package provides a series of traits that allows you to:

- RestorableFromName Trait

    Create/restore a PHP 8.1 enum from a name string.
- EnumValidatableCase

    Validate an enum name from a name string.
- CasesIndexedByName

    Similar to the standard static `cases()` method, but returns an associative array, indexed by the case names.

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require markbaker/enumhelper
```

Usage
-----

[](#usage)

### RestorableFromName Trait

[](#restorablefromname-trait)

In PHP 8.1, it is possible to create a backed enum from a value using the enum's `from()` or `tryFrom()` methods.

```
enum Suit: string {
    case Hearts = 'H';
    case Diamonds = 'D';
    case Clubs = 'C';
    case Spades = 'S';
}

$suit = Suit::Diamonds;

$value = $suit->value;      // Returns 'D'

$newSuit = Suit::from($value);
```

The `EnumHelper\EnumRestorableFromName` trait provided in this library adds a `fromName()` method to any enum where you want to create an enum from its name, rather than from its value.

```
enum Suit: string {
    use EnumHelper\EnumRestorableFromName;

    case Hearts = 'H';
    case Diamonds = 'D';
    case Clubs = 'C';
    case Spades = 'S';
}

$suit = Suit::Diamonds;

$suitName = $suit->name;      // Returns 'Diamonds'

$newSuit = Suit::fromName($suitName);
```

An invalid name will throw an exception. Note that names are case-sensitive.

This could be useful if you wanted to store the name in a database for readability (particularly appropriate for unbacked enums); then recreate the enum in the model when you load the database record.

This works with both backed and unbacked enums.

### EnumValidatableCase Trait

[](#enumvalidatablecase-trait)

Useful to validate if a name has been defined in the case set for an enum:

```
enum Suit: string {
    use EnumHelper\EnumValidatableCase;

    case Hearts = 'H';
    case Diamonds = 'D';
    case Clubs = 'C';
    case Spades = 'S';
}

$suit = Suit::Diamonds;

$validCaseName = Suit::Hearts;
$isCaseNameValid = Suit::isValidCase($validCaseName);      // Returns boolean true

$invalidCaseName = 'HeArTs';
$isCaseNameValid = Suit::isValidCase($invalidCaseName);    // Returns boolean false
```

Note that names are case-sensitive.

This works with both backed and unbacked enums.

### CasesIndexedByName Trait

[](#casesindexedbyname-trait)

While PHP 8.1+ Enums already provide a standard static `cases()` method to return a list of all cases defined for that enum:

```
enum Suit: string {
    use EnumHelper\EnumValidatableCase;

    case Hearts = 'H';
    case Diamonds = 'D';
    case Clubs = 'C';
    case Spades = 'S';
}

var_dump(Suit::cases());
```

which returns an enumerated array of the defined cases.

```
array(4) {
  [0]=>
  enum(Suit::Hearts)
  [1]=>
  enum(Suit::Diamonds)
  [2]=>
  enum(Suit::Clubs)
  [3]=>
  enum(Suit::Spades)
}

```

Using the `CasesIndexedByName` Trait and the related `casesIndexedByName()` method

```
enum Suit: string {
    use EnumHelper\CasesIndexedByName;

    case Hearts = 'H';
    case Diamonds = 'D';
    case Clubs = 'C';
    case Spades = 'S';
}

var_dump(Suit::casesIndexedByName());
```

which will return an associative array of the defined cases, where the array index is the case name.

```
array(4) {
  ["Hearts"]=>
  enum(Suit::Hearts)
  ["Diamonds"]=>
  enum(Suit::Diamonds)
  ["Clubs"]=>
  enum(Suit::Clubs)
  ["Spades"]=>
  enum(Suit::Spades)
}

```

This can be particularly useful if you filter the `cases()` list to return a subset of cases, and don't like the gaps in numeric sequence in the enumerated array.

```
enum Suit: string {
    use EnumHelper\CasesIndexedByName;

    public const RED = 'Red';
    public const BLACK = 'Black';

    case Hearts = 'H';
    case Diamonds = 'D';
    case Clubs = 'C';
    case Spades = 'S';

    public function color(): string {
        return match($this) {
            self::Hearts, self::Diamonds => self::RED,
            self::Clubs, self::Spades => self::BLACK,
        };
    }

    public static function red(): array {
        return array_filter(
            self::casesIndexedByName(),
            fn(self $suit) => $suit->color() === self::RED
        );
    }

    public static function black(): array {
        return array_filter(
            self::casesIndexedByName(),
            fn(self $suit) => $suit->color() === self::BLACK
        );
    }
}

var_dump(Suit::black());
```

will return

```
array(2) {
  ["Clubs"]=>
  enum(Suit::Clubs)
  ["Spades"]=>
  enum(Suit::Spades)
}

```

Changelog
---------

[](#changelog)

Please see the [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

License
-------

[](#license)

This library is released under the MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity37

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~22 days

Total

3

Last Release

1579d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/2b8457fa3227a7e8e38f0121f1fe254ec965133df93ae5ea8352c757adb98283?d=identicon)[PHPOffice](/maintainers/PHPOffice)

---

Top Contributors

[![MarkBaker](https://avatars.githubusercontent.com/u/770298?v=4)](https://github.com/MarkBaker "MarkBaker (2 commits)")

---

Tags

helperenumtrait

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/markbaker-enumhelper/health.svg)

```
[![Health](https://phpackages.com/badges/markbaker-enumhelper/health.svg)](https://phpackages.com/packages/markbaker-enumhelper)
```

###  Alternatives

[iteks/laravel-enum

A comprehensive Laravel package providing enhanced enum functionalities, including attribute handling, select array conversions, and fluent facade interactions for robust enum management in Laravel applications.

2516.7k](/packages/iteks-laravel-enum)[lazerg/laravel-enum-pro

A powerful PHP enum extension with collection support, random selection, and magic static calls

4319.0k](/packages/lazerg-laravel-enum-pro)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
