PHPackages                             philiprehberger/php-enum-utils - 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. philiprehberger/php-enum-utils

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

philiprehberger/php-enum-utils
==============================

Utility trait and helpers for PHP 8.1+ native enums

v1.2.0(4mo ago)169MITPHPPHP ^8.2CI passing

Since Mar 15Pushed 1mo agoCompare

[ Source](https://github.com/philiprehberger/php-enum-utils)[ Packagist](https://packagist.org/packages/philiprehberger/php-enum-utils)[ Docs](https://github.com/philiprehberger/php-enum-utils)[ GitHub Sponsors](https://github.com/philiprehberger)[ RSS](/packages/philiprehberger-php-enum-utils/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (6)Versions (9)Used By (0)

PHP Enum Utils
==============

[](#php-enum-utils)

[![Tests](https://github.com/philiprehberger/php-enum-utils/actions/workflows/tests.yml/badge.svg)](https://github.com/philiprehberger/php-enum-utils/actions/workflows/tests.yml)[![Latest Version on Packagist](https://camo.githubusercontent.com/6d21851ffc86454b47225caaef3de473aef1ef7dd70435930f2093411a6e662c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7068696c69707265686265726765722f7068702d656e756d2d7574696c732e737667)](https://packagist.org/packages/philiprehberger/php-enum-utils)[![Last updated](https://camo.githubusercontent.com/7a05af03d81c63d8360f81b6953da4ed535e0c97a2f0d9c4e556ea43c5668578/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6173742d636f6d6d69742f7068696c69707265686265726765722f7068702d656e756d2d7574696c73)](https://github.com/philiprehberger/php-enum-utils/commits/main)

Utility trait and helpers for PHP 8.1+ native enums.

Requirements
------------

[](#requirements)

- PHP 8.2+

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

[](#installation)

```
composer require philiprehberger/php-enum-utils
```

Usage
-----

[](#usage)

### Adding the trait to your enum

[](#adding-the-trait-to-your-enum)

```
use PhilipRehberger\EnumUtils\EnumUtils;
use PhilipRehberger\EnumUtils\Attributes\Label;
use PhilipRehberger\EnumUtils\Attributes\Description;

enum Status: string
{
    use EnumUtils;

    #[Label('Pending Review')]
    #[Description('The item is waiting for review')]
    case Pending = 'pending';

    #[Label('In Progress')]
    case InProgress = 'in_progress';

    case Completed = 'completed';
}
```

### Lookup by name

[](#lookup-by-name)

```
$case = Status::fromName('pending');      // Status::Pending (case-insensitive)
$case = Status::tryFromName('unknown');   // null
```

### Listing cases

[](#listing-cases)

```
Status::names();   // ['Pending', 'InProgress', 'Completed']
Status::values();  // ['pending', 'in_progress', 'completed']
Status::count();   // 3
```

### Arrays for forms and selects

[](#arrays-for-forms-and-selects)

```
Status::toSelectArray();
// ['pending' => 'Pending Review', 'in_progress' => 'In Progress', 'completed' => 'Completed']

Status::toArray();
// ['Pending' => 'pending', 'InProgress' => 'in_progress', 'Completed' => 'completed']
```

### Filtering cases

[](#filtering-cases)

```
// Filter by a custom predicate
$active = Status::casesWhere(fn (Status $s) => $s !== Status::Completed);
// [Status::Pending, Status::InProgress]

// Check if a case is among a given set
Status::Pending->in(Status::Pending, Status::InProgress);   // true
Status::Completed->in(Status::Pending, Status::InProgress); // false
```

### Random case and comparison

[](#random-case-and-comparison)

```
$case = Status::random();                        // A random Status case
Status::Pending->equals(Status::Pending);        // true
Status::Pending->equals(Status::Completed);      // false
```

### Collections

[](#collections)

```
use PhilipRehberger\EnumUtils\EnumCollection;

// Wrap all cases in a fluent collection
$active = Status::collect()
    ->filter(fn (Status $s) => $s !== Status::Completed)
    ->sortBy(fn (Status $s) => $s->value)
    ->toArray();

// Get the first matching case
$first = Status::collect()->first(fn (Status $s) => str_starts_with($s->value, 'p'));

// Group cases
$grouped = Status::collect()->groupBy(fn (Status $s) => $s === Status::Completed ? 'done' : 'active');

// Partition into two arrays: [matching, non-matching]
[$pending, $rest] = Status::collect()->partition(fn (Status $s) => $s === Status::Pending);
```

### Serialization

[](#serialization)

```
// Serialize all cases to JSON
$json = Status::toJson();
// [{"name":"Pending","value":"pending","label":"Pending Review","description":"..."},...]

// Deserialize back to enum cases
$cases = Status::fromJson($json);  // [Status::Pending, Status::InProgress, ...]

// Get value => label map
$map = Status::toMap();
// ['pending' => 'Pending Review', 'in_progress' => 'In Progress', 'completed' => 'Completed']
```

### State Transitions

[](#state-transitions)

```
use PhilipRehberger\EnumUtils\Attributes\AllowedTransitions;

enum OrderStatus: string
{
    use EnumUtils;

    #[AllowedTransitions(self::Processing, self::Cancelled)]
    case Pending = 'pending';

    #[AllowedTransitions(self::Shipped, self::Cancelled)]
    case Processing = 'processing';

    #[AllowedTransitions(self::Delivered)]
    case Shipped = 'shipped';

    case Delivered = 'delivered';
    case Cancelled = 'cancelled';
}

OrderStatus::Pending->canTransitionTo(OrderStatus::Processing);  // true
OrderStatus::Pending->canTransitionTo(OrderStatus::Shipped);     // false
OrderStatus::Pending->allowedTransitions();  // [OrderStatus::Processing, OrderStatus::Cancelled]
OrderStatus::Delivered->allowedTransitions(); // [] (no transitions defined)
```

### Reading attributes with EnumMeta

[](#reading-attributes-with-enummeta)

```
use PhilipRehberger\EnumUtils\EnumMeta;

EnumMeta::label(Status::Pending);         // 'Pending Review'
EnumMeta::label(Status::Completed);       // 'Completed' (fallback: humanized name)
EnumMeta::description(Status::Pending);   // 'The item is waiting for review'
EnumMeta::description(Status::Completed); // null
EnumMeta::labels(Status::class);          // ['pending' => 'Pending Review', ...]
```

API
---

[](#api)

### EnumUtils Trait

[](#enumutils-trait)

MethodDescription`::fromName(string $name): static`Case-insensitive lookup by name; throws `ValueError` on miss`::tryFromName(string $name): ?static`Case-insensitive lookup by name; returns `null` on miss`::names(): array`All case names as a flat array`::values(): array`All case values as a flat array`::random(): static`A random case`::casesWhere(callable $filter): array`Filter cases by a custom predicate`::toSelectArray(): array``[value => label]` for form selects`::toArray(): array``[name => value]` for serialization`::count(): int`Total number of cases`->equals(self $other): bool`Strict identity comparison`->in(self ...$cases): bool`Check if case is among the given set`::collect(): EnumCollection`Wrap all cases in a fluent collection`::toJson(): string`Serialize all cases to JSON`::fromJson(string $json): array`Deserialize JSON back to enum cases`::toMap(): array``[value => label]` map for all cases`->canTransitionTo(self $target): bool`Check if transition is allowed`->allowedTransitions(): array`Get all allowed target states### EnumMeta Helper

[](#enummeta-helper)

MethodDescription`EnumMeta::label(BackedEnum $case): string`Label from attribute or humanized name`EnumMeta::description(BackedEnum $case): ?string`Description from attribute or `null``EnumMeta::labels(string $enumClass): array``[value => label]` for all cases### Attributes

[](#attributes)

AttributeTargetPurpose`#[Label('...')]`Enum caseHuman-readable label`#[Description('...')]`Enum caseLonger description text`#[AllowedTransitions(...)]`Enum caseDefine valid state transitionsDevelopment
-----------

[](#development)

```
composer install
vendor/bin/phpunit
vendor/bin/pint --test
vendor/bin/phpstan analyse
```

Support
-------

[](#support)

If you find this project useful:

⭐ [Star the repo](https://github.com/philiprehberger/php-enum-utils)

🐛 [Report issues](https://github.com/philiprehberger/php-enum-utils/issues?q=is%3Aissue+is%3Aopen+label%3Abug)

💡 [Suggest features](https://github.com/philiprehberger/php-enum-utils/issues?q=is%3Aissue+is%3Aopen+label%3Aenhancement)

❤️ [Sponsor development](https://github.com/sponsors/philiprehberger)

🌐 [All Open Source Projects](https://philiprehberger.com/open-source-packages)

💻 [GitHub Profile](https://github.com/philiprehberger)

🔗 [LinkedIn Profile](https://www.linkedin.com/in/philiprehberger)

License
-------

[](#license)

[MIT](LICENSE)

###  Health Score

41

—

FairBetter than 87% of packages

Maintenance84

Actively maintained with recent releases

Popularity10

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 87.5% 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 ~2 days

Total

8

Last Release

129d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/cfd7d24cbbf32400fa13ce0bbe7a31edd2d66a6d4488eafdb3d64c5337bf0435?d=identicon)[philiprehberger](/maintainers/philiprehberger)

---

Top Contributors

[![philiprehberger](https://avatars.githubusercontent.com/u/8218077?v=4)](https://github.com/philiprehberger "philiprehberger (14 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")

---

Tags

enumhelpersattributesutilitiesphp-enum

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/philiprehberger-php-enum-utils/health.svg)

```
[![Health](https://phpackages.com/badges/philiprehberger-php-enum-utils/health.svg)](https://phpackages.com/packages/philiprehberger-php-enum-utils)
```

###  Alternatives

[andreas-glaser/php-helpers

A comprehensive collection of PHP utility functions for array manipulation, string operations, date handling, HTML generation, form building, validation, and more. Modern PHP 8.2+ library with full type safety.

1388.9k2](/packages/andreas-glaser-php-helpers)[zlikavac32/php-enum

Better PHP enum support

225.8k5](/packages/zlikavac32-php-enum)

PHPackages © 2026

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