PHPackages                             datomatic/enum-helper - 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. datomatic/enum-helper

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

datomatic/enum-helper
=====================

Simple opinionated framework agnostic PHP 8.1 enum helper

v2.1.1(4mo ago)59260.3k↓10.8%22MITPHPPHP ^8.1CI passing

Since May 27Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/datomatic/enum-helper)[ Packagist](https://packagist.org/packages/datomatic/enum-helper)[ RSS](/packages/datomatic-enum-helper/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (19)Used By (2)

[![Enum Helper-Dark](branding/dark.png#gh-dark-mode-only)](branding/dark.png#gh-dark-mode-only)[![Enum Helper-Light](branding/light.png#gh-light-mode-only)](branding/light.png#gh-light-mode-only)

Enum Helper
===========

[](#enum-helper)

[![Latest Version on Packagist](https://camo.githubusercontent.com/bc729c38e65bb5448c2d848cd053da2d4b27aa5178486dc49d66c59cfe925c5f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6461746f6d617469632f656e756d2d68656c7065722e7376673f7374796c653d666f722d7468652d6261646765)](https://packagist.org/packages/datomatic/enum-helper)[![Pest Tests number](https://camo.githubusercontent.com/6dafafc39d0fb3d302c84b2ab83904102fe14ad7c6ecc42576425331ec01acce/68747470733a2f2f696d672e736869656c64732e696f2f7374617469632f76313f6c6162656c3d2532337465737473266d6573736167653d33333926636f6c6f723d443135323946267374796c653d666f722d7468652d6261646765266c6f676f3d646174613a696d6167652f706e673b6261736536342c6956424f5277304b47676f414141414e5355684555674141414277414141415a43414d41414141564872345641414143796c424d5645554141414247762b5a47774f5a48762b5a51774f6848774f6466727432576973744776755a6f714e7073707470356e6453436d4e4c6b563639796f7465656863685674754a346e645647762b6470714e6d416d64436a674d526a713978757064684e7575536c674d56766f39644c764f527070396c396d394e6373642b446c39474e6b4d3547762b5a47774f65356337356b713978356e6457496c4d2b656863693064384648762b6447762b644776655246762b65536a637132637344466137724a616270567475453874504658744f4657744f42627364364c6b633775556179436c394856594c526a713975476c64434e6b4d36556a4d796268386d696773617166634f78654d4734644c362f62377a476172724f5a72663353716c69724e7a30544b6e62584c4a4e752b527470646c7a6f64615969637166684d616d674d537465384b3064722b386362334462627447762b566c7174756c6773584b614c6855742b4656744f426c71397848774f65416d644839523664366e4e5373664d4a6772743563734e3547762b5a47774f665958374f496b38372f526156477675626857724661732b4276704e69546a4d796f66384e53754f4a4b764f566b71397455742b4a786f64644c757553516a73785a732b473963723148762b5a547465425874654646762b5a747039684876755470557131497665535768386c51742b4e63734f4479543674306f646449764f4f68674d68766f7456477565583152364e366d394f7164377447762b5a47762b644d7a766c497665564e30763149786532496c4e43506a38314b79664a5075755259732b42697264314e3066784877757055742b4e52754f4a71734f4a6373643971703970306f6464336e3956396d394f416d644b4c6b732b76684d32546a6379596963713863623344624c7653597262585837546557724a537a767470785064497875394e784f3959774f3147774f686a742b6874732b687a724f4e3670392b416f39316c724e794b6e6470786f3969536d4e695a6b3957686a744f466c744364694d7168683871696738616e674d5772664d4f7565734b3064734334644c2f496162724c5a376a515a4c662f544c4c6f564b3777554b315a797668677850566c764f353374653165752b704f762b6c51764f645675755a39724f565974654664732b474c6f64397a716436576e6436456f743179706471646c646a51673968386e7464386e645739684e4b706964436e69632b326638723261636d3965736530664d62466463584d634d4b79654d48556138444162377a565a4c6a7657376a3156625461586250704f50304b41414141696e5253546c4d412f6661434266372b2f766e2b2f76372b2f7633392b5066304d7a49792f7637392f6672323976547a38752f4d76702b566c5a57566c496832527a55794d6a497349516a392f6672362b766e352b506a342b506a342b506a342b506a342b50623038764476372b2f76372b2f76372b2f75377572713564766131645454794d6a4875626579723632716d7065576c5a57566b354750686f574367585a306347746e5a474a655856565651446f364f5334754868305a467738312b374d6f41414143416b6c455156516f7a3249416762546a62696450384c3564666e545a30734d48392b3962736e6968664678684b774d4c57444c3275506d4a6c537441636f634f377564664d6e45437a35314c5a364d6177484c7448696435563634346467516f643043536e3333696841586366444a5771794d4e515a4b4e623842794c77382f50374276443068753376593555303046566d6d434a47746565317136756a67374f54725932396e61574d734b536e464f6e544a44756b63524a4a6e78364e574c5a30386650317a30594e664f48647532624e34306932334b7a4e367539557767795a546c34514146427755472b5076354b696a49792f703468386f5a542b37745975775041556b61364f767236596d4b69757271696f69494341734c47355a66594758735a75705259734147616e7334574c733465744a42477055314e484c553162505631465256733152554d6e507a464e6377646a4579547449435370626566724c6f507367704e7a5a7632726a68334c71316b2f6f5a75376f342b6a6d30675a4c4b39795433416b4f4d352b35637271327a4c302f75376537755975774357516b4b767668466f4644683465626a45674f4d7a5553696c7845497574594c395865444e48614737515748474442555a732b59334130476a454c54653041324d72547357627877392f7835556a4c7563674c53516b78677744717476347742464374317438794163754b7a5670382b74616f50424b5a4e36356d6570414f575979692b626a462f72766973684a4b43496d596f714779472b546a31716944516d52737173415a487a42612b4f574a585a7451446a634541485949334f61664f76756a56686b327936526f6e4d494c57526d4d3174576f6a4b50496d4a575054794a422f52674159655a4d3047597977534361756b2b6a71366c35546a565579346a77776571617a366d417a4667436a6c386261784e3362536741414141424a52553545726b4a6767673d3d)](https://github.com/datomatic/enum-helper/tree/main/tests)[![GitHub Tests Action Status](https://camo.githubusercontent.com/1b9acad69838de67e29ec3577c0e8e285250fc7ce0f34663fbb893c72cf8937b/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6461746f6d617469632f656e756d2d68656c7065722f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d746573747326636f6c6f723d354645384233267374796c653d666f722d7468652d6261646765266c6f676f3d646174613a696d6167652f706e673b6261736536342c6956424f5277304b47676f414141414e5355684555674141414277414141415a43414d41414141564872345641414143796c424d5645554141414247762b5a47774f5a48762b5a51774f6848774f6466727432576973744776755a6f714e7073707470356e6453436d4e4c6b563639796f7465656863685674754a346e645647762b6470714e6d416d64436a674d526a713978757064684e7575536c674d56766f39644c764f527070396c396d394e6373642b446c39474e6b4d3547762b5a47774f65356337356b713978356e6457496c4d2b656863693064384648762b6447762b644776655246762b65536a637132637344466137724a616270567475453874504658744f4657744f42627364364c6b633775556179436c394856594c526a713975476c64434e6b4d36556a4d796268386d696773617166634f78654d4734644c362f62377a476172724f5a72663353716c69724e7a30544b6e62584c4a4e752b527470646c7a6f64615969637166684d616d674d537465384b3064722b386362334462627447762b566c7174756c6773584b614c6855742b4656744f426c71397848774f65416d644839523664366e4e5373664d4a6772743563734e3547762b5a47774f665958374f496b38372f526156477675626857724661732b4276704e69546a4d796f66384e53754f4a4b764f566b71397455742b4a786f64644c757553516a73785a732b473963723148762b5a547465425874654646762b5a747039684876755470557131497665535768386c51742b4e63734f4479543674306f646449764f4f68674d68766f7456477565583152364e366d394f7164377447762b5a47762b644d7a766c497665564e30763149786532496c4e43506a38314b79664a5075755259732b42697264314e3066784877757055742b4e52754f4a71734f4a6373643971703970306f6464336e3956396d394f416d644b4c6b732b76684d32546a6379596963713863623344624c7653597262585837546557724a537a767470785064497875394e784f3959774f3147774f686a742b6874732b687a724f4e3670392b416f39316c724e794b6e6470786f3969536d4e695a6b3957686a744f466c744364694d7168683871696738616e674d5772664d4f7565734b3064734334644c2f496162724c5a376a515a4c662f544c4c6f564b3777554b315a797668677850566c764f353374653165752b704f762b6c51764f645675755a39724f565974654664732b474c6f64397a716436576e6436456f743179706471646c646a51673968386e7464386e645739684e4b706964436e69632b326638723261636d3965736530664d62466463584d634d4b79654d48556138444162377a565a4c6a7657376a3156625461586250704f50304b41414141696e5253546c4d412f6661434266372b2f766e2b2f76372b2f7633392b5066304d7a49792f7637392f6672323976547a38752f4d76702b566c5a57566c496832527a55794d6a497349516a392f6672362b766e352b506a342b506a342b506a342b506a342b50623038764476372b2f76372b2f76372b2f75377572713564766131645454794d6a4875626579723632716d7065576c5a57566b354750686f574367585a306347746e5a474a655856565651446f364f5334754868305a467738312b374d6f41414143416b6c455156516f7a3249416762546a62696450384c3564666e545a30734d48392b3962736e6968664678684b774d4c57444c3275506d4a6c537441636f634f377564664d6e45437a35314c5a364d6177484c7448696435563634346467516f643043536e3333696841586366444a5771794d4e515a4b4e623842794c77382f50374276443068753376593555303046566d6d434a47746565317136756a67374f54725932396e61574d734b536e464f6e544a44756b63524a4a6e78364e574c5a30386650317a30594e664f48647532624e34306932334b7a4e367539557767795a546c34514146427755472b5076354b696a49792f703468386f5a542b37745975775041556b61364f767236596d4b69757271696f69494341734c47355a66594758735a75705259734147616e7334574c733465744a42477055314e484c553162505631465256733152554d6e507a464e6377646a4579547449435370626566724c6f507367704e7a5a7632726a68334c71316b2f6f5a75376f342b6a6d30675a4c4b39795433416b4f4d352b35637271327a4c302f75376537755975774357516b4b767668466f4644683465626a45674f4d7a5553696c7845497574594c395865444e48614737515748474442555a732b59334130476a454c54653041324d72547357627877392f7835556a4c7563674c53516b78677744717476347742464374317438794163754b7a5670382b74616f50424b5a4e36356d6570414f575979692b626a462f72766973684a4b43496d596f714779472b546a31716944516d52737173415a487a42612b4f574a585a7451446a634541485949334f61664f76756a56686b327936526f6e4d494c57526d4d3174576f6a4b50496d4a575054794a422f52674159655a4d3047597977534361756b2b6a71366c35546a565579346a77776571617a366d417a4667436a6c386261784e3362536741414141424a52553545726b4a6767673d3d)](https://github.com/datomatic/enum-helper/actions/workflows/run-tests.yml)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/742a4d12c0d0b6e289f26afc285f318cf0238b4fb5ac88de642877f0653547fd/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6461746f6d617469632f656e756d2d68656c7065722f70696e742e796d6c3f6c6162656c3d636f64652532307374796c6526636f6c6f723d354645384233267374796c653d666f722d7468652d6261646765)](https://github.com/datomatic/enum-helper/actions/workflows/php-cs-fixer.yml)[![Total Downloads](https://camo.githubusercontent.com/695d26a8864fe6235ba86f4d8981c55bd40daced8fe18e01b1858ab774138fdd/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6461746f6d617469632f656e756d2d68656c7065722e7376673f7374796c653d666f722d7468652d6261646765)](https://packagist.org/packages/datomatic/enum-helper)

A simple and opinionated collections of PHP 8.1 enum helpers inspired by [archtechx/enums](https://github.com/archtechx/enums) and [BenSampo/laravel-enum](https://github.com/BenSampo/laravel-enum).
This package is framework agnostic, but if you use Laravel consider to use this linked package [datomatic/laravel-enum-helper](https://github.com/datomatic/laravel-enum-helper) and [datomatic/laravel-enum-collections](https://github.com/datomatic/laravel-enum-collections).

Upgrade from v1.x
-----------------

[](#upgrade-from-v1x)

Please see the [upgrade.md](upgrade.md) file.

Functionalities summary
-----------------------

[](#functionalities-summary)

- **Invokable cases**: get the value of enum "invoking" it statically
- **Construct enum by name or value**: `wrap()`, `from()`, `tryFrom()`, `fromName()`, `tryFromName()`, `fromValue()`, `tryFromValue()` methods
- **Enums Inspection**: `isPure()`, `isBacked()`, `has()`, `hasName()`, `hasValue()` methods
- **Enums Equality**: `is()`, `isNot()`, `in()`, `notIn()` methods
- **Names**: methods to have a list of case names (`names()`, `namesByValue()`)
- **Values**: methods to have a list of case values (`values()`, `valuesByName()`)
- **Serialization**: get an unique identifier from instance or instance from identifier (`serialize()`, `unserialize()`)
- **Descriptions &amp; Translations**: add description to enum with optional translation (`description()`,`descriptions()`,`descriptionsByName()`,`descriptionsByValue()`,`nullableDescriptionsByValue()`)
- **Labels**: add label to enum (`label()`,`labels()`,`labelsByName()`,`labelsByValue()`,`nullableLabelsByValue()`)
- **Properties**: methods to have a list of properties (`dynamicList()`,`dynamicByKey()`)

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

[](#installation)

PHP 8.1+ is required.

```
composer require datomatic/enum-helper
```

Usage
-----

[](#usage)

You can use the traits you need, but for convenience, you can use only the `EnumHelper` trait that includes (`EnumInvokable`, `EnumFroms`, `EnumNames`, `EnumValues`, `EnumInspection`, `EnumEquality`).
`EnumDescription` and `EnumSerialization` are separated from `EnumHelper` because they cover edge cases.

The helper support both pure enum (e.g. `PureEnum`, `PascalCasePureEnum`) and `BackedEnum` (e.g. `IntBackedEnum`, `StringBackedEnum`).

In all examples we'll use the classes described below:

```
use Datomatic\EnumHelper\EnumHelper;

// Pure enum
enum PureEnum
{
    use EnumHelper;

    case PENDING;
    case ACCEPTED;
    case DISCARDED;
    case NO_RESPONSE;
}
enum PascalCasePureEnum
{
    use EnumHelper;

    case Pending;
    case Accepted;
    case Discarded;
    case NoResponse;
}

// BackedEnum
enum StringBackedEnum: string
{
    use EnumHelper;

    case PENDING = 'P';
    case ACCEPTED = 'A';
    case DISCARDED = 'D';
    case NO_RESPONSE = 'N';
}
enum IntBackedEnum: int
{
    use EnumHelper;

    case PENDING = 0;
    case ACCEPTED = 1;
    case DISCARDED = 2;
    case NO_RESPONSE = 3;
}
```

The package works with cases written in UPPER\_CASE, snake\_case and PascalCase.

### Jump To

[](#jump-to)

- [Invokable Cases](#invokable-cases)
- [From](#from-fromName)
- [Enums Inspection](#inspection)
- [Enums Equality](#equality)
- [Names](#names)
- [Values](#values)
- [Serialization](#serialization)
- [Descriptions &amp; Translations](#descriptions-and-translations)
- [Properties](#properties)

### Invokable Cases

[](#invokable-cases)

This helper lets you get the value of a `BackedEnum`, or the name of a pure enum, by "invoking" it both statically (`PureEnum::pending()`), and as an instance (`$status()`).
A good approach is to call methods in camelCase mode, but you can invoke the enum in all cases `::STATICALLY()`, `::statically()` or `::Statically()`.

```
IntBackedEnum::PENDING // PureEnum enum instance
IntBackedEnum::pending(); // 0
```

That way permits you to use enum invoke into an array keys definition:

```
'statuses' => [
    PureEnum::pending() => 'some configuration',
...
```

or in database interactions ` $db_field_definition->default(PureEnum::pending())`or invoke instances to get the primitive value

```
public function updateStatus(int $status): void;

$task->updateStatus(IntBackedEnum::pending());
```

#### Examples use static calls to get the primitive value

[](#examples-use-static-calls-to-get-the-primitive-value)

```
// Pure Enum
PureEnum::noResponse(); // 'NO_RESPONSE'
PureEnum::NO_RESPONSE(); // 'NO_RESPONSE'
PureEnum::NoResponse(); // 'NO_RESPONSE'

// Pure Enum with PascalCase
PascalCasePureEnum::noResponse(); // 'NoResponse'
PascalCasePureEnum::NO_RESPONSE(); // 'NoResponse'
PascalCasePureEnum::NoResponse(); // 'NoResponse'

// IntBackedEnum
IntBackedEnum::pending(); // 0

// StringBackedEnum
StringBackedEnum::pending(); // 'P'
```

#### IDE code completion

[](#ide-code-completion)

To have a code completion you can get autosuggestions while typing the enum case and then add () or you can add phpDoc @method tags to the enum class to define all invokable cases like this:

```
/**
 * @method static string pending()
 * @method static string accepted()
 * @method static string discarded()
 * @method static string noResponse()
 */
enum PureEnum
...
```

### From FromName

[](#from-fromname)

This helper adds `from()` and `tryFrom()` to pure enums, `fromValue()` and `tryFromValue()` (alias of `from()` and `tryFrom()`), `fromName()` and `tryFromName()` to all enums

#### Important Notes:

[](#important-notes)

- `BackedEnum` instances already implement their own `from()` and `tryFrom()` methods, which will not be overridden by this trait.

#### `from()`

[](#from)

```
// Pure Enum
PureEnum::from('PENDING'); // PureEnum::PENDING
PascalCasePureEnum::from('Pending'); // PascalCasePureEnum::Pending
PureEnum::from('MISSING'); // ValueError Exception
// BackedEnum
StringBackedEnum::from('P'); // StringBackedEnum::PENDING
StringBackedEnum::from('M'); // ValueError Exception
```

#### `tryFrom()`

[](#tryfrom)

```
// Pure Enum
PureEnum::tryFrom('PENDING'); // PureEnum::PENDING
PureEnum::tryFrom('MISSING'); // null
// BackedEnum
StringBackedEnum::tryFrom('P'); // StringBackedEnum::PENDING
StringBackedEnum::tryFrom('M'); // null
```

#### `fromName()`

[](#fromname)

```
// Pure Enum
PureEnum::fromName('PENDING'); // PureEnum::PENDING
PureEnum::fromName('MISSING'); // ValueError Exception
// BackedEnum
StringBackedEnum::fromName('PENDING'); // StringBackedEnum::PENDING
StringBackedEnum::fromName('MISSING'); // ValueError Exception
```

#### `tryFromName()`

[](#tryfromname)

```
// Pure Enum
PureEnum::tryFromName('PENDING'); // PureEnum::PENDING
PureEnum::tryFromName('MISSING'); // null
// BackedEnum
StringBackedEnum::tryFromName('PENDING'); // StringBackedEnum::PENDING
StringBackedEnum::tryFromName('MISSING'); // null
```

#### `wrap()`

[](#wrap)

This method is a convenience helper to "wrap" a value (or an enum instance) into the corresponding enum instance. It is especially useful when you accept mixed input (an enum instance, a case name, a backing value, or null) and want to normalize it into the enum instance.

Signature:

```
public static function wrap(self|string|int|null $value, bool $strict = false): ?self
```

Behavior notes:

- If an actual enum instance (same enum) is passed, it is returned unchanged.
- If null is passed, the method throws an error if `$strict = true`, otherwise it returns null.
- If a backing value is passed (int or string), the method attempts to resolve it using `tryFrom()` (for BackedEnum) or `tryFromName()` (for pure enums).
- For int-backed enums, numeric strings (e.g. `'1'`) are accepted: they are converted to integer and processed as numeric backing values.
- When a string is passed and no backing match is found, `wrap()` will try to resolve it as a case name via `tryFromName()`.
- By default (`$strict = false`) the method returns null if no enum case matches. When `$strict = true`, the method throws a `ValueError` if the value cannot be converted to a valid enum instance.

Examples:

```
// Passing an enum instance returns it unchanged
$enum = IntBackedEnum::PENDING;
IntBackedEnum::wrap($enum); // IntBackedEnum::PENDING

// Null remains null
IntBackedEnum::wrap(null); // null
IntBackedEnum::wrap(null, true); // throws ValueError

// Backed enum by native backing value
IntBackedEnum::wrap(1); // IntBackedEnum::ACCEPTED
StringBackedEnum::wrap('P'); // StringBackedEnum::PENDING

// Numeric string for int-backed enum
IntBackedEnum::wrap('1'); // IntBackedEnum::ACCEPTED

// Case name (pure enum)
PureEnum::wrap('PENDING'); // PureEnum::PENDING

// Case name (backed enum)
StringBackedEnum::wrap('PENDING'); // StringBackedEnum::PENDING

// Non matching values
PureEnum::wrap('MISSING'); // null
PureEnum::wrap('MISSING', true); // throws ValueError: '"MISSING" is not a valid backing value for enum "Namespace\PureEnum"'
```

Notes on error message:

- When `$strict` is true and no match is found, `wrap()` throws a `ValueError` with a message similar to: '"" is not a valid backing value for enum ""'

This helper is useful in input normalization flows (e.g. DTOs, HTTP handlers, form processors) where you want to accept several forms of enum input and consistently obtain an enum instance or a null.

### Inspection

[](#inspection)

This helper permits check the type of enum (`isPure()`,`isBacked()`) and if enum contains a case name or value (`has()`, `doesntHave()`, `hasName()`, `doesntHaveName()`, `hasValue()`, `doesntHaveValue()`).

#### `isPure()`, `isBacked()`, `isIntBacked()`and `isStringBacked()`

[](#ispure-isbacked-isintbackedand-isstringbacked)

With these methods you can check the type of the enum instance.

```
PureEnum::PENDING->isPure() // true
PureEnum::PENDING->isBacked() // false
IntBackedEnum::PENDING->isPure() // false
IntBackedEnum::PENDING->isIntBacked() // true
StringBackedEnum::PENDING->isBacked() // true
StringBackedEnum::PENDING->isStringBacked() // true
```

#### `has()` and `doesntHave()`

[](#has-and-doesnthave)

`has()` method permit checking if an enum has a case (name or value) by passing int, string or enum instance. For convenience, there is also an `doesntHave()` method which is the exact reverse of the `has()` method.

```
PureEnum::has('PENDING') // true
IntBackedEnum::has(10) // false
IntBackedEnum::has(1) // true
IntBackedEnum::has('1') // true
StringBackedEnum::has('ACCEPTED') // true
StringBackedEnum::has('A') // true
StringBackedEnum::doesntHave('A') // false
```

#### `hasName()` and `doesntHaveName()`

[](#hasname-and-doesnthavename)

`hasName()` method permit checking if an enum has a case name. For convenience, there is also an `doesntHaveName()` method which is the exact reverse of the `hasName()` method.

```
PureEnum::hasName('PENDING') // true
PureEnum::hasName('P') // false
IntBackedEnum::hasName('ACCEPTED') // true
IntBackedEnum::hasName(1) // false
StringBackedEnum::doesntHaveName('ACDSIED') // true
StringBackedEnum::hasName('A') // false
```

#### `hasValue()` and `doesntHaveValue()`

[](#hasvalue-and-doesnthavevalue)

`hasValue()` method permit checking if an enum has a case by passing int, string or enum instance. For convenience, there is also a `doesntHaveValue()` method which is the exact reverse of the `hasValue()` method.

```
PureEnum::hasValue('PENDING') // true
PureEnum::hasValue('P') // false
IntBackedEnum::hasValue('ACCEPTED') // false
IntBackedEnum::hasValue(1) // true
StringBackedEnum::doesntHaveValue('Z') // true
StringBackedEnum::hasValue('A') // true
```

### Equality

[](#equality)

This helper permits to compare an enum instance (`is()`,`isNot()`) and search if it is present inside an array (`in()`,`notIn()`).

#### `is()` and `isNot()`

[](#is-and-isnot)

`is()` method permit checking the equality of an instance against an enum instance, a case name, or a case value.
For convenience, there is also an `isNot()` method which is the exact reverse of the `is()` method.

```
$enum = PureEnum::PENDING;
$enum->is(PureEnum::PENDING); // true
PureEnum::PENDING->is(PureEnum::ACCEPTED); // false
PureEnum::PENDING->is('PENDING'); // true
PureEnum::PENDING->is('ACCEPTED'); // false
PureEnum::PENDING->isNot('ACCEPTED'); // true

$backedEnum = IntBackedEnum::PENDING;
$backedEnum->is(IntBackedEnum::PENDING); // true
IntBackedEnum::PENDING->is(IntBackedEnum::ACCEPTED); // false
IntBackedEnum::PENDING->is(0); // true
IntBackedEnum::PENDING->is('PENDING'); // true
StringBackedEnum::PENDING->is('P'); // true
StringBackedEnum::PENDING->isNot('P'); // false
```

#### `in()` and `notIn()`

[](#in-and-notin)

`in()` method permit to see if an instance matches on an array of instances, names or values. For convenience, there is also a `notIn()` method which is the exact reverse of the `i()` method.

```
$enum = PureEnum::PENDING;
$enum->in([PureEnum::PENDING,PureEnum::ACCEPTED]); // true
PureEnum::PENDING->in([PureEnum::DISCARDED, PureEnum::ACCEPTED]); // false
PureEnum::PENDING->in(['PENDING', 'ACCEPTED']); // true
PureEnum::PENDING->in(['ACCEPTED', 'DISCARDED']); // false
PureEnum::PENDING->notIn(['ACCEPTED']); // true

$backedEnum = IntBackedEnum::PENDING;
$backedEnum->in([IntBackedEnum::PENDING, IntBackedEnum::ACCEPTED]); // true
IntBackedEnum::PENDING->in([IntBackedEnum::ACCEPTED])// false
IntBackedEnum::PENDING->in([0, 1, 2]); // true
IntBackedEnum::PENDING->in([2, 3]); // false
IntBackedEnum::PENDING->in(['PENDING', 'ACCEPTED']); // true
IntBackedEnum::PENDING->in(['DISCARDED', 'ACCEPTED']); // false
StringBackedEnum::PENDING->in(['P', 'D']); // true
StringBackedEnum::PENDING->notIn(['A','D']); // true
```

### Names

[](#names)

This helper offer `names()` and `namesByValue()` methods.

#### `names()`

[](#names-1)

This method returns a list of case names in the enum.

```
PureEnum::names(); // ['PENDING', 'ACCEPTED', 'DISCARDED', 'NO_RESPONSE']
PascalCasePureEnum::names(); // ['Pending', 'Accepted', 'Discarded', 'NoResponse']
StringBackedEnum::names(); // ['PENDING', 'ACCEPTED', 'DISCARDED', 'NO_RESPONSE']
// Subset
PureEnum::names([PureEnum::NO_RESPONSE, PureEnum::DISCARDED]); // ['NO_RESPONSE', 'DISCARDED']
PascalCasePureEnum::names([PascalCasePureEnum::Accepted, PascalCasePureEnum::Discarded]); // ['Accepted', 'Discarded']
```

#### `namesByValue()`

[](#namesbyvalue)

This method returns an associative array of \[value =&gt; name\] on `BackedEnum`, \[name =&gt; name\] on pure enum.

```
PureEnum::namesByValue(); // [ 'PENDING' => 'PENDING', 'ACCEPTED' => 'ACCEPTED', 'DISCARDED' => 'DISCARDED'...
StringBackedEnum::namesByValue(); // [ 'P' => 'PENDING', 'A' => 'ACCEPTED', 'D' => 'DISCARDED'...
IntBackedEnum::namesByValue(); // [ 0=>'PENDING', 1=>'ACCEPTED', 2=>'DISCARDED'...
// Subset
IntBackedEnum::namesByValue([IntBackedEnum::NO_RESPONSE, IntBackedEnum::DISCARDED]); // [ 3=>'NO_RESPONSE', 2=>'DISCARDED']
```

### Values

[](#values)

This helper offer `values()` and `valuesByName()` methods.

#### `values()`

[](#values-1)

This method returns a list of case values for `BackedEnum` or a list of case names for pure enums.

```
PureEnum::values(); // ['PENDING', 'ACCEPTED', 'DISCARDED', 'NO_RESPONSE']
StringBackedEnum::values(); // ['P', 'A', 'D', 'N']
IntBackedEnum::values(); // [0, 1, 2, 3]
// Subset
PureEnum::values([PureEnum::NO_RESPONSE, PureEnum::DISCARDED]); // ['NO_RESPONSE', 'DISCARDED']
StringBackedEnum::values([StringBackedEnum::NO_RESPONSE, StringBackedEnum::DISCARDED]); // ['N', 'D']
IntBackedEnum::values([IntBackedEnum::NO_RESPONSE, IntBackedEnum::DISCARDED]); // [3, 2]
```

#### `valuesByName()`

[](#valuesbyname)

This method returns an associative array of \[name =&gt; value\] on `BackedEnum`, \[name =&gt; name\] on pure enum.

```
PureEnum::valuesByName(); // ['PENDING' => 'PENDING','ACCEPTED' => 'ACCEPTED','DISCARDED' => 'DISCARDED',...]
StringBackedEnum::valuesByName(); // ['PENDING' => 'P','ACCEPTED' => 'A','DISCARDED' => 'D','NO_RESPONSE' => 'N']
IntBackedEnum::valuesByName(); // ['PENDING' => 0,'ACCEPTED' => 1,'DISCARDED' => 2,'NO_RESPONSE' => 3]
// Subset
PureEnum::valuesByName([PureEnum::NO_RESPONSE, PureEnum::DISCARDED]); // ['NO_RESPONSE' => 'NO_RESPONSE', 'DISCARDED' => 'DISCARDED']
StringBackedEnum::valuesByName([StringBackedEnum::NO_RESPONSE, StringBackedEnum::DISCARDED]); // ['NO_RESPONSE' => 'N', 'DISCARDED' => 'D']
IntBackedEnum::valuesByName([IntBackedEnum::NO_RESPONSE, IntBackedEnum::DISCARDED]); // ['NO_RESPONSE' => 3, 'DISCARDED' => 2]
```

### Serialization

[](#serialization)

This helper permits to get an unique identifier from enum or an enum instance from identifier.

The helper is not included on the base `EnumHelper` trait and does not depend on it, so if you need it you must use `EnumSerialization`.

```
use Datomatic\EnumHelper\Traits\EnumSerialization;

enum PureEnum
{
    use EnumSerialization;

    ...
```

#### serialize()

[](#serialize)

This method returns the enum unique identifier based on Namespace\\ClassName::CASE\_NAME. You can use this identifier to save multiple types of enums in a database on a polymorphic column.

```
PureEnum::PENDING->serialize(); // Namespace\PureEnum.PENDING
$enum = StringBackedEnum::NO_RESPONSE;
$enum->serialize(); // Namespace\StringBackedEnum.NO_RESPONSE
```

#### unserialize()

[](#unserialize)

This method returns an enum instance from unique identifier.

```
PureEnum::unserialize('Namespace\PureEnum::PENDING'); // PureEnum::PENDING
IntBackedEnum::unserialize('Namespace\IntBackedEnum::PENDING'); // IntBackedEnum::PENDING
IntBackedEnum::unserialize('NOT::valid::uniqueId'); // throw InvalidSerializedValue Exception
IntBackedEnum::unserialize('Wrong\Namespace\IntBackedEnum::PENDING'); // throw InvalidSerializedValue Exception
IntBackedEnum::unserialize('Namespace\IntBackedEnum::MISSING'); // throw InvalidSerializedValue Exception
```

#### Global unserializeEnum() helper

[](#global-unserializeenum-helper)

The method `unserialize()` has little possibility of use because it's related to only an enum class. A better approach is to create a global helper to instantiate any enum from serialization like this:

```
use Datomatic\EnumHelper\Exceptions\InvalidSerializedValue;

public function unserializeEnum(string $value): object
{
    if (
        !strpos($value, '.')
        || substr_count($value, '.') !== 1
    ) {
        throw InvalidSerializedValue::serializedFormatIsInvalid($value);
    }

    list($enumClass, $enumName) = explode('.', $value);

    foreach ($enumClass::cases() as $case){
        if( $case->name === $enumName){
                return $case;
            }
        }
    }

    throw InvalidSerializedValue::caseNotPresent($case);
}
```

#### json\_encode on PureEnum

[](#json_encode-on-pureenum)

By default, you can't use `json_encode()` on `PureEnum` because it hasn't a value. Using this trait and implementing `JsonSerializable` interface you can use `json_encode()`.

```
enum Status implements \JsonSerializable
{
    use EnumSerialization;

    case PENDING;
    case ACCEPTED;
}

json_encode(Status::PENDING); // '"PENDING"'
```

### Descriptions and Translations

[](#descriptions-and-translations)

This helper permits to have a description of each case of an enum. Work with both singular language and multilingual application. This is useful when you need descriptions to characterize the cases better or in a multilingual context.

The helper is not included on the base `EnumHelper` trait and does not depend on it, so if you need it you must use `EnumDescription` and implement the abstract `description()` method to define the descriptions. You can use it on both pure enums and `BackedEnum`.

```
use Datomatic\EnumHelper\EnumHelper;
use Datomatic\EnumHelper\Traits\EnumDescription;

enum StringBackedEnum: string
{
    use EnumHelper;
    use EnumDescription;

    case PENDING = 'P';
    case ACCEPTED = 'A';
    case DISCARDED = 'D';
    case NO_RESPONSE = 'N';

    public function description(?string $lang = null): string
    {
        return match ($this) {
            self::PENDING => 'Await decision',
            self::ACCEPTED => 'Recognized valid',
            self::DISCARDED => 'No longer useful',
            self::NO_RESPONSE => 'No response',
        };
    }
```

After the implementation of `description()` method you can use it

```
PureEnum::PENDING->description(); // 'Await decision'
```

#### Localization

[](#localization)

You can change the `description()` method with your translation method/helper to translate the descriptions.

```
public function description(?string $lang = null): string
    {
        // this is only an example of implementation... translate method not exist
        // if $lang is null you have to use the current locale
        return return translate('status.'$this->name, $lang);

        // or translate each case
        return match ($this) {
            self::PENDING => translate('Await decision'),
            self::ACCEPTED => translate('Recognized valid'),
            self::DISCARDED => translate('No longer useful'),
            self::NO_RESPONSE => translate('No response'),
        };

        //or use EnumSerialization trait
        return translate($this->serialize(), $lang);
    }
```

After the implementation of `description` method you can use it

```
$enum = PureEnum::PENDING;
$enum->description(); // 'Await decision'
$enum->description('it'); // 🇮🇹 'In attesa'
```

#### descriptions()

[](#descriptions)

This method returns a list of case descriptions of enum.

```
StringBackedEnum::descriptions(); // ['Await decision','Recognized valid','No longer useful','No response']
// Subset
StringBackedEnum::descriptions([StringBackedEnum::ACCEPTED, StringBackedEnum::NO_RESPONSE]); // ['Recognized valid','No response']
```

#### descriptionsByValue()

[](#descriptionsbyvalue)

This method returns an associative array of \[value =&gt; description\] on `BackedEnum`, \[name =&gt; description\] on pure enum.

```
StringBackedEnum::descriptionsByValue(); // ['P' => 'Await decision', 'A' => 'Recognized valid',...
PureEnum::descriptionsByValue(); // ['PENDING' => 'Await decision', 'ACCEPTED' => 'Recognized valid',...
PureEnum::descriptionsByValue(lang: 'it'); // ['PENDING' => 'In attesa', 'ACCEPTED' => 'Valido',...
// Subset
StringBackedEnum::descriptionsByValue([StringBackedEnum::DISCARDED, StringBackedEnum::ACCEPTED]); // ['D' => 'No longer useful', 'A' => 'Recognized valid']
PureEnum::descriptionsByValue([[PureEnum::PENDING, PureEnum::DISCARDED]); // ['PENDING' => 'Await decision', 'DISCARDED' => 'No longer useful']
PureEnum::descriptionsByValue([[PureEnum::PENDING, PureEnum::DISCARDED],'it'); // ['PENDING' => 'In attesa', 'DISCARDED' => 'Scartato']
```

#### nullableDescriptionsByValue()

[](#nullabledescriptionsbyvalue)

This method prepend to `descriptionsByValue()` returns a default value usefull when do you need nullable select on a form.

```
StringBackedEnum::nullableDescriptionsByValue('Select value'); // [null => 'Select value', 'P' => 'Await decision', 'A' => 'Recognized valid',...
```

#### descriptionsByName()

[](#descriptionsbyname)

This method returns an associative array of \[name =&gt; description\].

```
StringBackedEnum::descriptionsByName(); // ['PENDING' => 'Await decision', 'ACCEPTED' => 'Recognized valid',...
PureEnum::descriptionsByName(lang: 'it'); // ['PENDING' => 'In attesa', 'ACCEPTED' => 'Valido',...
// Subset
StringBackedEnum::descriptionsByName([StringBackedEnum::DISCARDED, StringBackedEnum::ACCEPTED]); // ['DISCARDED' => 'No longer useful', 'ACCEPTED' => 'Recognized valid']
PureEnum::descriptionsByName([[PureEnum::PENDING, PureEnum::DISCARDED],'it'); // ['PENDING' => 'In attesa', 'DISCARDED' => 'Scartato']
```

### Labels

[](#labels)

The `EnumLabel` trait it's the same of `EnumDescription` but you can use if prefer call `label` method instead `description`.

### Properties

[](#properties)

The `EnumProperties` trait it's used to get properties list dynamically. If your enum has a method to define a property like `color()` you can use this trait in this mode:

```
StringBackedEnum::dynamicList(method: 'color');
StringBackedEnum::dynamicByKey(key: 'value', method: 'color');

//Subset and Locale
StringBackedEnum::dynamicList(method: 'color',[StringBackedEnum::DISCARDED, StringBackedEnum::ACCEPTED], 'it');
StringBackedEnum::dynamicByKey(key: 'value', method: 'color', [StringBackedEnum::DISCARDED, StringBackedEnum::ACCEPTED], 'it');
```

###  Health Score

55

—

FairBetter than 98% of packages

Maintenance74

Regular maintenance activity

Popularity47

Moderate usage in the ecosystem

Community17

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor1

Top contributor holds 93.9% 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 ~77 days

Recently: every ~105 days

Total

18

Last Release

141d ago

Major Versions

v0.7.2 → v1.0.02022-09-09

v1.1.0 → v2.0.02024-10-31

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/497169?v=4)[Alberto Peripolli](/maintainers/trippo)[@trippo](https://github.com/trippo)

---

Top Contributors

[![trippo](https://avatars.githubusercontent.com/u/497169?v=4)](https://github.com/trippo "trippo (184 commits)")[![fabio-ivona](https://avatars.githubusercontent.com/u/8792274?v=4)](https://github.com/fabio-ivona "fabio-ivona (7 commits)")[![Carnicero90](https://avatars.githubusercontent.com/u/78483736?v=4)](https://github.com/Carnicero90 "Carnicero90 (5 commits)")

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/datomatic-enum-helper/health.svg)

```
[![Health](https://phpackages.com/badges/datomatic-enum-helper/health.svg)](https://phpackages.com/packages/datomatic-enum-helper)
```

PHPackages © 2026

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