PHPackages                             archtechx/enums - 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. archtechx/enums

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

archtechx/enums
===============

Helpers for making PHP enums more lovable.

v1.1.2(11mo ago)56910.3M—0.6%23[2 issues](https://github.com/archtechx/enums/issues)[1 PRs](https://github.com/archtechx/enums/pulls)20MITPHPPHP ^8.1CI passing

Since Feb 20Pushed 11mo ago4 watchersCompare

[ Source](https://github.com/archtechx/enums)[ Packagist](https://packagist.org/packages/archtechx/enums)[ RSS](/packages/archtechx-enums/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (11)Used By (20)

Enums
=====

[](#enums)

A collection of enum helpers for PHP.

- [`InvokableCases`](#invokablecases)
- [`Names`](#names)
- [`Values`](#values)
- [`Options`](#options)
- [`From`](#from)
- [`Metadata`](#metadata)
- [`Comparable`](#comparable)

You can read more about the original idea on [Twitter](https://twitter.com/archtechx/status/1495158228757270528).

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

[](#installation)

PHP 8.1+ is required.

```
composer require archtechx/enums
```

Usage
-----

[](#usage)

### InvokableCases

[](#invokablecases)

This helper lets you get the value of a backed enum, or the name of a pure enum, by "invoking" it — either statically (`MyEnum::FOO()` instead of `MyEnum::FOO`), or as an instance (`$enum()`).

That way, you can use enums as array keys:

```
'statuses' => [
    TaskStatus::INCOMPLETE() => ['some configuration'],
    TaskStatus::COMPLETED() => ['some configuration'],
],
```

Or access the underlying primitives for any other use cases:

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

$task->updateStatus(TaskStatus::COMPLETED());
```

The main point: this is all without [having to append](https://twitter.com/archtechx/status/1495158237137494019) `->value` to everything.

This approach also has *decent* IDE support. You get autosuggestions while typing, and then you just append `()`:

```
MyEnum::FOO; // => MyEnum instance
MyEnum::FOO(); // => 1
```

#### Apply the trait on your enum

[](#apply-the-trait-on-your-enum)

```
use ArchTech\Enums\InvokableCases;

enum TaskStatus: int
{
    use InvokableCases;

    case INCOMPLETE = 0;
    case COMPLETED = 1;
    case CANCELED = 2;
}

enum Role
{
    use InvokableCases;

    case ADMINISTRATOR;
    case SUBSCRIBER;
    case GUEST;
}
```

#### Use static calls to get the primitive value

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

```
TaskStatus::INCOMPLETE(); // 0
TaskStatus::COMPLETED(); // 1
TaskStatus::CANCELED(); // 2
Role::ADMINISTRATOR(); // 'ADMINISTRATOR'
Role::SUBSCRIBER(); // 'SUBSCRIBER'
Role::GUEST(); // 'GUEST'
```

#### Invoke instances to get the primitive value

[](#invoke-instances-to-get-the-primitive-value)

```
public function updateStatus(TaskStatus $status, Role $role)
{
    $this->record->setStatus($status(), $role());
}
```

### Names

[](#names)

This helper returns a list of case *names* in the enum.

#### Apply the trait on your enum

[](#apply-the-trait-on-your-enum-1)

```
use ArchTech\Enums\Names;

enum TaskStatus: int
{
    use Names;

    case INCOMPLETE = 0;
    case COMPLETED = 1;
    case CANCELED = 2;
}

enum Role
{
    use Names;

    case ADMINISTRATOR;
    case SUBSCRIBER;
    case GUEST;
}
```

#### Use the `names()` method

[](#use-the-names-method)

```
TaskStatus::names(); // ['INCOMPLETE', 'COMPLETED', 'CANCELED']
Role::names(); // ['ADMINISTRATOR', 'SUBSCRIBER', 'GUEST']
```

### Values

[](#values)

This helper returns a list of case *values* for backed enums, or a list of case *names* for pure enums (making this functionally equivalent to [`::names()`](#names) for pure Enums)

#### Apply the trait on your enum

[](#apply-the-trait-on-your-enum-2)

```
use ArchTech\Enums\Values;

enum TaskStatus: int
{
    use Values;

    case INCOMPLETE = 0;
    case COMPLETED = 1;
    case CANCELED = 2;
}

enum Role
{
    use Values;

    case ADMINISTRATOR;
    case SUBSCRIBER;
    case GUEST;
}
```

#### Use the `values()` method

[](#use-the-values-method)

```
TaskStatus::values(); // [0, 1, 2]
Role::values(); // ['ADMINISTRATOR', 'SUBSCRIBER', 'GUEST']
```

### Options

[](#options)

This helper returns an associative array of case names and values for backed enums, or a list of names for pure enums (making this functionally equivalent to [`::names()`](#names) for pure Enums).

#### Apply the trait on your enum

[](#apply-the-trait-on-your-enum-3)

```
use ArchTech\Enums\Options;

enum TaskStatus: int
{
    use Options;

    case INCOMPLETE = 0;
    case COMPLETED = 1;
    case CANCELED = 2;
}

enum Role
{
    use Options;

    case ADMINISTRATOR;
    case SUBSCRIBER;
    case GUEST;
}
```

#### Use the `options()` method

[](#use-the-options-method)

```
TaskStatus::options(); // ['INCOMPLETE' => 0, 'COMPLETED' => 1, 'CANCELED' => 2]
Role::options(); // ['ADMINISTRATOR', 'SUBSCRIBER', 'GUEST']
```

#### stringOptions()

[](#stringoptions)

The trait also adds the `stringOptions()` method that can be used for generating convenient string representations of your enum options:

```
// First argument is the callback, second argument is glue
// returns "INCOMPLETE => 0, COMPLETED => 1, CANCELED => 2"
TaskStatus::stringOptions(fn ($name, $value) => "$name => $value", ', ');
```

For pure enums (non-backed), the name is used in place of `$value` (meaning that both `$name` and `$value` are the same).

Both arguments for this method are optional, the glue defaults to `\n` and the callback defaults to generating HTML `` tags:

```
// Incomplete
// Completed
// Canceled
TaskStatus::stringOptions(); // backed enum

// Administrator
// Subscriber
// Guest
Role::stringOptions(); // pure enum
```

### From

[](#from)

This helper adds `from()` and `tryFrom()` to pure enums, and adds `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. Attempting to override those methods in a `BackedEnum` causes a fatal error.
- Pure enums only have named cases and not values, so the `from()` and `tryFrom()` methods are functionally equivalent to `fromName()` and `tryFromName()`

#### Apply the trait on your enum

[](#apply-the-trait-on-your-enum-4)

```
use ArchTech\Enums\From;

enum TaskStatus: int
{
    use From;

    case INCOMPLETE = 0;
    case COMPLETED = 1;
    case CANCELED = 2;
}

enum Role
{
    use From;

    case ADMINISTRATOR;
    case SUBSCRIBER;
    case GUEST;
}
```

#### Use the `from()` method

[](#use-the-from-method)

```
Role::from('ADMINISTRATOR'); // Role::ADMINISTRATOR
Role::from('NOBODY'); // Error: ValueError
```

#### Use the `tryFrom()` method

[](#use-the-tryfrom-method)

```
Role::tryFrom('GUEST'); // Role::GUEST
Role::tryFrom('NEVER'); // null
```

#### Use the `fromName()` method

[](#use-the-fromname-method)

```
TaskStatus::fromName('INCOMPLETE'); // TaskStatus::INCOMPLETE
TaskStatus::fromName('MISSING'); // Error: ValueError
Role::fromName('SUBSCRIBER'); // Role::SUBSCRIBER
Role::fromName('HACKER'); // Error: ValueError
```

#### Use the `tryFromName()` method

[](#use-the-tryfromname-method)

```
TaskStatus::tryFromName('COMPLETED'); // TaskStatus::COMPLETED
TaskStatus::tryFromName('NOTHING'); // null
Role::tryFromName('GUEST'); // Role::GUEST
Role::tryFromName('TESTER'); // null
```

### Metadata

[](#metadata)

This trait lets you add metadata to enum cases.

#### Apply the trait on your enum

[](#apply-the-trait-on-your-enum-5)

```
use ArchTech\Enums\Metadata;
use ArchTech\Enums\Meta\Meta;
use App\Enums\MetaProperties\{Description, Color};

#[Meta(Description::class, Color::class)]
enum TaskStatus: int
{
    use Metadata;

    #[Description('Incomplete Task')] #[Color('red')]
    case INCOMPLETE = 0;

    #[Description('Completed Task')] #[Color('green')]
    case COMPLETED = 1;

    #[Description('Canceled Task')] #[Color('gray')]
    case CANCELED = 2;
}
```

Explanation:

- `Description` and `Color` are userland class attributes — meta properties
- The `#[Meta]` call enables those two meta properties on the enum
- Each case must have a defined description &amp; color (in this example)

#### Access the metadata

[](#access-the-metadata)

```
TaskStatus::INCOMPLETE->description(); // 'Incomplete Task'
TaskStatus::COMPLETED->color(); // 'green'
```

#### Creating meta properties

[](#creating-meta-properties)

Each meta property (= attribute used on a case) needs to exist as a class.

```
#[Attribute]
class Color extends MetaProperty {}

#[Attribute]
class Description extends MetaProperty {}
```

Inside the class, you can customize a few things. For instance, you may want to use a different method name than the one derived from the class name (`Description` becomes `description()` by default). To do that, override the `method()` method on the meta property:

```
#[Attribute]
class Description extends MetaProperty
{
    public static function method(): string
    {
        return 'note';
    }
}
```

With the code above, the description of a case will be accessible as `TaskStatus::INCOMPLETE->note()`.

Another thing you can customize is the passed value. For instance, to wrap a color name like `text-{$color}-500`, you'd add the following `transform()` method:

```
#[Attribute]
class Color extends MetaProperty
{
    protected function transform(mixed $value): mixed
    {
        return "text-{$value}-500";
    }
}
```

And now the returned color will be correctly transformed:

```
TaskStatus::COMPLETED->color(); // 'text-green-500'
```

You can also add a `defaultValue()` method to specify the value a case should have if it doesn't use the meta property. That way you can apply the attribute only on some cases and still get a configurable default value on all other cases.

#### Use the `fromMeta()` method

[](#use-the-frommeta-method)

```
TaskStatus::fromMeta(Color::make('green')); // TaskStatus::COMPLETED
TaskStatus::fromMeta(Color::make('blue')); // Error: ValueError
```

#### Use the `tryFromMeta()` method

[](#use-the-tryfrommeta-method)

```
TaskStatus::tryFromMeta(Color::make('green')); // TaskStatus::COMPLETED
TaskStatus::tryFromMeta(Color::make('blue')); // null
```

#### Recommendation: use annotations and traits

[](#recommendation-use-annotations-and-traits)

If you'd like to add better IDE support for the metadata getter methods, you can use `@method` annotations:

```
/**
 * @method string description()
 * @method string color()
 */
#[Meta(Description::class, Color::class)]
enum TaskStatus: int
{
    use Metadata;

    #[Description('Incomplete Task')] #[Color('red')]
    case INCOMPLETE = 0;

    #[Description('Completed Task')] #[Color('green')]
    case COMPLETED = 1;

    #[Description('Canceled Task')] #[Color('gray')]
    case CANCELED = 2;
}
```

And if you're using the same meta property in multiple enums, you can create a dedicated trait that includes this `@method` annotation.

### Comparable

[](#comparable)

This trait lets you compare enums using `is()`, `isNot()`, `in()` and `notIn()`.

#### Apply the trait on your enum

[](#apply-the-trait-on-your-enum-6)

```
use ArchTech\Enums\Comparable;

enum TaskStatus: int
{
    use Comparable;

    case INCOMPLETE = 0;
    case COMPLETED = 1;
    case CANCELED = 2;
}

enum Role
{
    use Comparable;

    case ADMINISTRATOR;
    case SUBSCRIBER;
    case GUEST;
}
```

#### Use the `is()` method

[](#use-the-is-method)

```
TaskStatus::INCOMPLETE->is(TaskStatus::INCOMPLETE); // true
TaskStatus::INCOMPLETE->is(TaskStatus::COMPLETED); // false
Role::ADMINISTRATOR->is(Role::ADMINISTRATOR); // true
Role::ADMINISTRATOR->is(Role::NOBODY); // false
```

#### Use the `isNot()` method

[](#use-the-isnot-method)

```
TaskStatus::INCOMPLETE->isNot(TaskStatus::INCOMPLETE); // false
TaskStatus::INCOMPLETE->isNot(TaskStatus::COMPLETED); // true
Role::ADMINISTRATOR->isNot(Role::ADMINISTRATOR); // false
Role::ADMINISTRATOR->isNot(Role::NOBODY); // true
```

#### Use the `in()` method

[](#use-the-in-method)

```
TaskStatus::INCOMPLETE->in([TaskStatus::INCOMPLETE, TaskStatus::COMPLETED]); // true
TaskStatus::INCOMPLETE->in([TaskStatus::COMPLETED, TaskStatus::CANCELED]); // false
Role::ADMINISTRATOR->in([Role::ADMINISTRATOR, Role::GUEST]); // true
Role::ADMINISTRATOR->in([Role::SUBSCRIBER, Role::GUEST]); // false
```

#### Use the `notIn()` method

[](#use-the-notin-method)

```
TaskStatus::INCOMPLETE->notIn([TaskStatus::INCOMPLETE, TaskStatus::COMPLETED]); // false
TaskStatus::INCOMPLETE->notIn([TaskStatus::COMPLETED, TaskStatus::CANCELED]); // true
Role::ADMINISTRATOR->notIn([Role::ADMINISTRATOR, Role::GUEST]); // false
Role::ADMINISTRATOR->notIn([Role::SUBSCRIBER, Role::GUEST]); // true
```

PHPStan
-------

[](#phpstan)

To assist PHPStan when using invokable cases, you can include the PHPStan extensions into your own `phpstan.neon` file:

```
includes:
  - ./vendor/archtechx/enums/extension.neon
```

*Note: If you have installed [`phpstan/extension-installer`](https://github.com/phpstan/extension-installer#usage), the extension is automatically included.*

Development
-----------

[](#development)

Run all checks locally:

```
./check
```

Code style will be automatically fixed by php-cs-fixer.

###  Health Score

58

—

FairBetter than 98% of packages

Maintenance51

Moderate activity, may be stable

Popularity67

Solid adoption and visibility

Community37

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 65.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 ~133 days

Recently: every ~127 days

Total

10

Last Release

346d ago

Major Versions

v0.3.2 → v1.0.02024-01-12

### Community

Maintainers

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

---

Top Contributors

[![stancl](https://avatars.githubusercontent.com/u/33033094?v=4)](https://github.com/stancl "stancl (27 commits)")[![samlev](https://avatars.githubusercontent.com/u/462466?v=4)](https://github.com/samlev "samlev (3 commits)")[![ejunker](https://avatars.githubusercontent.com/u/4758?v=4)](https://github.com/ejunker "ejunker (2 commits)")[![lukinovec](https://avatars.githubusercontent.com/u/34375937?v=4)](https://github.com/lukinovec "lukinovec (2 commits)")[![parth391](https://avatars.githubusercontent.com/u/4966579?v=4)](https://github.com/parth391 "parth391 (1 commits)")[![szepeviktor](https://avatars.githubusercontent.com/u/952007?v=4)](https://github.com/szepeviktor "szepeviktor (1 commits)")[![colinmackinlay](https://avatars.githubusercontent.com/u/7833362?v=4)](https://github.com/colinmackinlay "colinmackinlay (1 commits)")[![xHeaven](https://avatars.githubusercontent.com/u/14284867?v=4)](https://github.com/xHeaven "xHeaven (1 commits)")[![hosmelq](https://avatars.githubusercontent.com/u/1166143?v=4)](https://github.com/hosmelq "hosmelq (1 commits)")[![hungthai1401](https://avatars.githubusercontent.com/u/22017922?v=4)](https://github.com/hungthai1401 "hungthai1401 (1 commits)")[![owenconti](https://avatars.githubusercontent.com/u/791222?v=4)](https://github.com/owenconti "owenconti (1 commits)")

###  Code Quality

TestsPest

Static AnalysisPHPStan

### Embed Badge

![Health badge](/badges/archtechx-enums/health.svg)

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

PHPackages © 2026

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