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

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

suleymanozev/enum-helper
========================

Simple opinionated framework agnostic PHP 8.1 enum helper

1.0.0(2y ago)02731MITPHPPHP ^8.1

Since Jan 23Pushed 2y ago1 watchersCompare

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

READMEChangelog (1)Dependencies (3)Versions (2)Used By (1)

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

[](#enum-helper)

[![Latest Version on Packagist](https://camo.githubusercontent.com/70cd8e8ce6290197f9ad258f325a3d976cb07d4f78f0321485fa8c5e6931836a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f73756c65796d616e6f7a65762f656e756d2d68656c7065722e7376673f7374796c653d666f722d7468652d6261646765)](https://packagist.org/packages/suleymanozev/enum-helper)[![Pest Tests number](https://camo.githubusercontent.com/affb72dc21fd2d681a23a72a41d30a713987ff8a0103f6e9e395b43dbc153349/68747470733a2f2f696d672e736869656c64732e696f2f7374617469632f76313f6c6162656c3d2532337465737473266d6573736167653d33303326636f6c6f723d464638384641267374796c653d666f722d7468652d6261646765266c6f676f3d646174613a696d6167652f706e673b6261736536342c6956424f5277304b47676f414141414e5355684555674141414277414141416343414d414141424630792b6d414141426956424d564555414141442f69507639795033586d2b6a2f6d502f2f7766566a36374a653662502f682f70567836703631373564353757517963662b69506e2f695072736e657a417264332b742f7170764e4a64364c502f6a5070753672762f6c50722f6b5070633537542f7276746335374e7036726a336f506c3337634c2f74666e2f77763964366272582f2f4c2f672f72596e2b6e2f677672576d2b6469364c582b6a5072736b6647577a4d707436626c6e3462646435374a6b364c575379636a2b76507175774e566f36726465366250376e7676596e75703931622f2b7666762f6c76746335374f71764e544673392f2f742f746435374c39742f722f69507064364c506170656a2f6f76703236627879363776396c666c64364c4a72344c6a777376622f7876332f6a7633397a76317436627547356354447265483569766c6335724a7936373656346378623537442f792f6835304d4f79344f4355786356613737582f69507065364c502f6a502b7075394c38742f2f2f7476755179636641724e7870364c7a41726431353172372f692f396e3462622f6a2f39653672542f69667237696672736b764c596e7568693837746738626c673762662f76762f2f6c502b77784e746a3962332f71762f2f6f502f2b69767a2f6c2f7238696672796e2f66766c505466705044656f66444b74756a48744f5758314e462f3473654333635238327346753763426f354c694d77504d724141414157485253546c4d412f577638464149432f644d452f576a2b337445472f507637393847316f48526a53306b314c4273574467734a2f7633362b66547938657a6e342b4c683239584e7a4d7a4c79734c41774c53777236366f704a71616b592b4e69344a37656e643062476c7059313158553034384b69636d49523866697a6c2b767741414156644a524546554b4d39747a325658416c4551674f4642425552706b453637753775374531594659516c31536276726c7a7444694c7673732b66632f6643656d584d76414568684b71553735395031724c6f7855445579456839665048307a37414c69567245592b53534e74784e533275706f75597637684f4c313931614b56735a48555467626e51505167446b7134637448646f516d54576d573457467a6c56554456704e4b58663266577057625a497755712f68636d6a5747596e536131705a5a6a456f6f6d72456456416973443743583647456234307271544f4478436a32314f6a444f766a5256386c326a68756442446368672f46556244495a4349547a775179483661392b32414d44626d3947666c74466e786741647451575567514a6c345651713337755063536e7366595a7a61763645773138665134665559504d37516e34755369496479783573614a36542b2f332b354b536c7473686963774932557066414b452f616f415254766e6e374b4d594d646c41557957525379484e324a65553432486c43693454737a5448636d756a33694d566450354a7a6f7941574e7a693654335a47724d46436c694b334241715253432f42322b3649787659594e634f2b324e7066762b79466931304c66425541414141415355564f524b35435949493d)](https://github.com/suleymanozev/enum-helper/tree/main/tests)[![GitHub Tests Action Status](https://camo.githubusercontent.com/b5713524743560d6af4188fd6ed128b1adbca5d429fb351eb61396423599c684/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f73756c65796d616e6f7a65762f656e756d2d68656c7065722f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d746573747326636f6c6f723d354645384233267374796c653d666f722d7468652d6261646765266c6f676f3d646174613a696d6167652f706e673b6261736536342c6956424f5277304b47676f414141414e5355684555674141414277414141416343414d414141424630792b6d414141426956424d564555414141442f69507639795033586d2b6a2f6d502f2f7766566a36374a653662502f682f70567836703631373564353757517963662b69506e2f695072736e657a417264332b742f7170764e4a64364c502f6a5070753672762f6c50722f6b5070633537542f7276746335374e7036726a336f506c3337634c2f74666e2f77763964366272582f2f4c2f672f72596e2b6e2f677672576d2b6469364c582b6a5072736b6647577a4d707436626c6e3462646435374a6b364c575379636a2b76507175774e566f36726465366250376e7676596e75703931622f2b7666762f6c76746335374f71764e544673392f2f742f746435374c39742f722f69507064364c506170656a2f6f76703236627879363776396c666c64364c4a72344c6a777376622f7876332f6a7633397a76317436627547356354447265483569766c6335724a7936373656346378623537442f792f6835304d4f79344f4355786356613737582f69507065364c502f6a502b7075394c38742f2f2f7476755179636641724e7870364c7a41726431353172372f692f396e3462622f6a2f39653672542f69667237696672736b764c596e7568693837746738626c673762662f76762f2f6c502b77784e746a3962332f71762f2f6f502f2b69767a2f6c2f7238696672796e2f66766c505466705044656f66444b74756a48744f5758314e462f3473654333635238327346753763426f354c694d77504d724141414157485253546c4d412f577638464149432f644d452f576a2b337445472f507637393847316f48526a53306b314c4273574467734a2f7633362b66547938657a6e342b4c683239584e7a4d7a4c79734c41774c53777236366f704a71616b592b4e69344a37656e643062476c7059313158553034384b69636d49523866697a6c2b767741414156644a524546554b4d39747a325658416c4551674f4642425552706b453637753775374531594659516c31536276726c7a7444694c7673732b66632f6643656d584d76414568684b71553735395031724c6f7855445579456839665048307a37414c69567245592b53534e74784e533275706f75597637684f4c313931614b56735a48555467626e51505167446b7134637448646f516d54576d573457467a6c56554456704e4b58663266577057625a497755712f68636d6a5747596e536131705a5a6a456f6f6d72456456416973443743583647456234307271544f4478436a32314f6a444f766a5256386c326a68756442446368672f46556244495a4349547a775179483661392b32414d44626d3947666c74466e786741647451575567514a6c345651713337755063536e7366595a7a61763645773138665134665559504d37516e34755369496479783573614a36542b2f332b354b536c7473686963774932557066414b452f616f415254766e6e374b4d594d646c41557957525379484e324a65553432486c43693454737a5448636d756a33694d566450354a7a6f7941574e7a693654335a47724d46436c694b334241715253432f42322b3649787659594e634f2b324e7066762b79466931304c66425541414141415355564f524b35435949493d)](https://github.com/suleymanozev/enum-helper/actions/workflows/run-tests.yml)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/755012acac025da428bbce34fbf1a8c12e2f3c230c0c50f62038ab2e0a4ebc9d/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f73756c65796d616e6f7a65762f656e756d2d68656c7065722f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6c6162656c3d636f64652532307374796c6526636f6c6f723d354645384233267374796c653d666f722d7468652d6261646765)](https://github.com/suleymanozev/enum-helper/actions/workflows/php-cs-fixer.yml)[![Total Downloads](https://camo.githubusercontent.com/6fc98ab1903a3983aafc35ac9061d63b0b9c64daa069ab8ebeef486038599baf/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f73756c65796d616e6f7a65762f656e756d2d68656c7065722e7376673f7374796c653d666f722d7468652d6261646765)](https://packagist.org/packages/suleymanozev/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 [suleymanozev/laravel-enum-helper](https://github.com/suleymanozev/laravel-enum-helper).

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

[](#functionalities-summary)

- **Invokable cases**: get the value of enum "invoking" it statically
- **Construct enum by name or value**: `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()`)
- **Unique ID**: get an unique identifier from instance or instance from identifier (`uniqueId()`, `fromUniqueId()`)
- **Descriptions &amp; Translations**: add description to enum with optional translation (`description()`,`descriptions()`,`descriptionsByName()`,`descriptionsByValue()`,`nullableDescriptionsByValue()`)

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

[](#installation)

PHP 8.1+ is required.

```
composer require suleymanozev/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 `EnumUniqueId` 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 Suleymanozev\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)
- [Froms](#from-fromName)
- [Enums Inspection](#inspection)
- [Enums Equality](#equality)
- [Names](#names)
- [Values](#values)
- [Unique ID](#uniqueid)
- [Descriptions &amp; Translations](#descriptions-and-translations)

### 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
```

### 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()` and `isBacked()`

[](#ispure-and-isbacked)

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

```
PureEnum::PENDING->isPure() // true
PureEnum::PENDING->isBacked() // false
IntBackedEnum::PENDING->isPure() // false
StringBackedEnum::PENDING->isBacked() // 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 an `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 a 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]
```

### UniqueId

[](#uniqueid)

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 `EnumUniqueId`.

```
use Suleymanozev\EnumHelper\Traits\EnumUniqueId;

enum PureEnum
{
    use EnumUniqueId;

    ...
```

#### uniqueId()

[](#uniqueid-1)

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->uniqueId(); // Namespace\PureEnum.PENDING
$enum = StringBackedEnum::NO_RESPONSE;
$enum->uniqueId(); // Namespace\StringBackedEnum.NO_RESPONSE
```

#### fromUniqueId()

[](#fromuniqueid)

This method returns an enum instance from unique identifier.

```
PureEnum::fromUniqueId('Namespace\PureEnum.PENDING'); // PureEnum::PENDING
IntBackedEnum::fromUniqueId('Namespace\IntBackedEnum.PENDING'); // IntBackedEnum::PENDING
IntBackedEnum::fromUniqueId('NOT.valid.uniqueId'); // throw InvalidUniqueId Exception
IntBackedEnum::fromUniqueId('Wrong\Namespace\IntBackedEnum.PENDING'); // throw InvalidUniqueId Exception
IntBackedEnum::fromUniqueId('Namespace\IntBackedEnum.MISSING'); // throw InvalidUniqueId Exception
```

#### Global getEnumFromUniqueId() helper

[](#global-getenumfromuniqueid-helper)

The method `fromUniqueId()` 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 uniqueId like this:

```
use Suleymanozev\EnumHelper\Exceptions\InvalidUniqueId;

public function getEnumFromUniqueId(string $uniqueId): object
{
    if (
        !strpos($uniqueId, '.')
        || substr_count($uniqueId, '.') !== 1
    ) {
        throw InvalidUniqueId::uniqueIdFormatIsInvalid($uniqueId);
    }

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

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

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

### 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 Suleymanozev\EnumHelper\EnumHelper;
use Suleymanozev\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 EnumUniqueId trait
        return translate($this->uniqueId(), $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',...
// 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']
```

#### 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',...
```

### Special Thanks

[](#special-thanks)

- Datomatic Team

###  Health Score

25

—

LowBetter than 37% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity11

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 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

Unknown

Total

1

Last Release

842d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/46e3a500894af089bd0454a7091114e0959fb7f300353aa30e1e3a6548be9d6b?d=identicon)[suleymanozev](/maintainers/suleymanozev)

---

Top Contributors

[![suleymanozev](https://avatars.githubusercontent.com/u/20399264?v=4)](https://github.com/suleymanozev "suleymanozev (1 commits)")

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[gallib/laravel-short-url

A Laravel package to shorten urls

16516.4k](/packages/gallib-laravel-short-url)[funstaff/tika

libs for tika wrapper

1124.4k](/packages/funstaff-tika)

PHPackages © 2026

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