Skip to content

About

Native enum extensions, reusable enum traits, and class-based enums for PHP >= 8.4.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Repository files navigation

PHP EnumEx

Latest Stable Version
v3.0.0 released on December 3, 2026 (123).

Same enum, different behavior.

EnumEx stands for Enum Extension, bringing extra flexibility and expressiveness to PHP enums.
pronounced: [ "enum-E-X" | "enum-ex" | "enumex" | whatever ]

Native enum extensions, collections, composites, reusable enum traits, and class-based enums for PHP >= 8.4.

Playing with bits

use Notonza\PhpEnumEx\Extension\Case\EnumCase;
use Notonza\PhpEnumEx\Extension\Collection\EnumCollection;

enum ByteUnit: int {
    case BYTE     = 1;
    case KIBIBYTE = 1 << 10;
    case MEBIBYTE = 1 << 20;
    case GIBIBYTE = 1 << 30;
}

/** @extends EnumCase<ByteUnit> */
final readonly class ByteUnitDecimal extends EnumCase {

    public static function from(ByteUnit $unit): self {
        return new self($unit);
    }

    public function format(): string {
        return number_format($this->unwrap()->value);
    }
}

/** @extends EnumCase<ByteUnit> */
final readonly class ByteUnitHex extends EnumCase {

    public static function from(ByteUnit $unit): self {
        return new self($unit);
    }

    public function format(): string {
        return '0x' . strtoupper(dechex($this->unwrap()->value));
    }
}

$units = EnumCollection::of(ByteUnit::class);

$decimal = $units->wrapCasesAs(ByteUnitDecimal::from(...));
$hex     = $units->wrapCasesAs(ByteUnitHex::from(...));

$name = ByteUnit::MEBIBYTE->name;
// Same case, different behavior
$decimal->fromName($name)->format(); // '1,048,576'
$hex->fromName($name)->format();     // '0x100000'
$units->fromName($name)->value();    // 1048576
use Notonza\PhpEnumEx\Extension\Case\EnumCase;
use Notonza\PhpEnumEx\Extension\Collection\EnumCollection;

enum FilePermission: int {
    case READ    = 1 << 0;
    case WRITE   = 1 << 1;
    case EXECUTE = 1 << 2;
}

/** @extends EnumCase<FilePermission> */
final readonly class PermissionCheck extends EnumCase {

    public function __construct(
        FilePermission $permission,
        private int    $mask,
    ) {
        parent::__construct($permission);
    }

    public function isGranted(): bool {
        $flag = $this->unwrap()->value;

        return ($this->mask & $flag) === $flag;
    }
}

$mask = FilePermission::READ->value
      | FilePermission::WRITE->value;

$checks = EnumCollection::of(FilePermission::class)
    ->wrapCasesAs(
        fn (FilePermission $case)
            => new PermissionCheck($case, $mask),
    );

// Context-specific selection
$granted = $checks->filter(fn (PermissionCheck $case): bool => $case->isGranted());
$denied  = $checks->reject(fn (PermissionCheck $case): bool => $case->isGranted());

array_keys($granted); // ['READ', 'WRITE']
array_keys($denied);  // ['EXECUTE']

Core native enum abstractions

EnumEx currently provides three complementary abstractions for working with native enums without changing their definitions. All three abstractions support inheritance in addition to composition. This combination enables powerful and expressive domain modeling.


Case — EnumCase

Extend a single native enum case with context-specific behavior or additional state while preserving its identity.

---
config:
  flowchart:
    rankSpacing: 110
    nodeSpacing: 20
    padding: 7
    diagramPadding: 5
  themeVariables:
    fontSize: 12px
---
flowchart LR
    subgraph CaseBox[" "]
        direction LR
        A("A")
    end

    subgraph Relationship[" "]
        direction TB
        EC["EnumCase"] -->|wraps| Paid("OrderStatus::Paid")
    end

    CaseBox ~~~~~~~~~~~ Relationship

    style CaseBox fill:transparent,stroke:#64748b,stroke-width:2px,rx:12,ry:12
    style Relationship fill:transparent,stroke:transparent
    classDef native fill:#0d948820,stroke:#0d9488,stroke-width:1.5px
    class A,Paid native
    classDef compact font-size:12px
    class A,Paid,EC compact
Loading

Wraps one native case.

$case = EnumCase::of(OrderStatus::Paid);
$case->is(OrderStatus::Paid); // true

Collection — EnumCollection

Work with all declared cases of one native enum, optionally applying a shared wrapper factory for context-specific behavior.

flowchart LR
    subgraph CollectionBox[" "]
        direction LR
        A("A") ~~~ B("B") ~~~ C("C")
    end

    subgraph Relationship[" "]
        direction TB
        subgraph Cases[" "]
            direction LR
            Paid("OrderStatus::Paid") ~~~ Pending("OrderStatus::Pending") ~~~ Cancelled("OrderStatus::Cancelled")
        end
        COL["EnumCollection"] -->|represents all declared cases of one enum| Cases
    end

    CollectionBox ~~~ Relationship

    style CollectionBox fill:transparent,stroke:#64748b,stroke-width:2px,stroke-dasharray:5 4,rx:12,ry:12
    style Relationship fill:transparent,stroke:transparent
    style Cases fill:transparent,stroke:#64748b,stroke-dasharray:5 4
    classDef native fill:#0d948820,stroke:#0d9488,stroke-width:1.5px
    class A,B,C,Paid,Pending,Cancelled native
Loading

Represents all declared cases of one enum.

$collection = EnumCollection::of(OrderStatus::class);
array_keys($collection->except([OrderStatus::Cancelled])); // ['Paid', 'Pending']

Composite — EnumComposite

Compose multiple native enum cases, potentially from different enum types, into one structured value with explicit order and duplicate policies.

flowchart LR
    subgraph CompositeBox[" "]
        direction LR
        A1("A") ~~~ X("X") ~~~ A2("A")
    end

    subgraph Relationship[" "]
        direction TB
        subgraph Cases[" "]
            direction LR
            Paid1("OrderStatus::Paid") ~~~ Admin("UserRole::Admin") ~~~ Paid2("OrderStatus::Paid")
        end
        COMP["EnumComposite"] -->|retains| Cases
    end

    CompositeBox ~~~ Relationship

    style CompositeBox fill:transparent,stroke:#64748b,stroke-width:2px,rx:12,ry:12
    style Relationship fill:transparent,stroke:transparent
    style Cases fill:transparent,stroke:#64748b
    classDef native fill:#0d948820,stroke:#0d9488,stroke-width:1.5px
    classDef other fill:#6366f120,stroke:#6366f1,stroke-width:1.5px
    class A1,A2,Paid1,Paid2 native
    class X,Admin other
Loading

Retains a sequence of native cases.

$composite = EnumComposite::as(
    CompositeOrder::Insensitive,
    CompositeDuplicates::Preserve,
)->of(
    OrderStatus::Paid,
    UserRole::Admin,
    OrderStatus::Paid,
);
$composite->hasAll(OrderStatus::Paid, OrderStatus::Paid); // true

The left diagrams show abstract structure; the right diagrams give concrete examples. The diagrams and short snippets assume an OrderStatus enum declaring Paid, Pending and Cancelled in that order, and a UserRole enum with Admin. A, B and C represent those three OrderStatus cases; X represents UserRole::Admin. These illustrative definitions are independent of the examples below. The repeated A represents two occurrences of the same native case, not two different cases.

Table of contents

Requirements and installation

The Composer package is notonza/php-enumex (formerly gachakra/php-enum). Its PSR-4 root namespace is Notonza\PhpEnumEx.

The library requires PHP ^8.4. Development and testing require PHP 8.4.1 or later within that range because of the PHPUnit version in composer.lock.

This README documents the v3 API. The native extension namespaces and mapping and qualified-formatting APIs include breaking changes from v2. To install the v3 release:

composer require notonza/php-enumex:^3.0

Upgrading from v2? v2.0.0 README · Migration from v2 to v3

Local development from a Git checkout

Using local PHP

composer install
vendor/bin/phpunit

Using Docker

docker compose up -d --build --remove-orphans
docker compose exec php bash

See Running examples in Docker for requirements and further instructions.

Choosing an approach

Approach When to use it
Native enum The default for a fixed set of domain values and intrinsic domain behavior.
EnumCase Add behavior outside an enum, reuse behavior through inheritance, or carry additional state.
EnumCollection Work with every case of an enum, optionally with a context-specific wrapper factory.
EnumComposite Represent several native cases as a single structured value with explicit comparison and duplicate policies.
Native enum traits Add common collection, comparison, and debugging operations to enums you own.
Class-based Enum Maintain existing integrations or model enum-like constant sets that can be extended or overridden through inheritance.

Working with enums regardless of their type

EnumEx provides a common API for pure and backed enums. A pure case's logical value is its name; a backed case's logical value is its original int or string backing value.

use Notonza\PhpEnumEx\Extension\Case\EnumCase;

EnumCase::of(Direction::North)->value(); // 'North' (UnitEnum only)
EnumCase::of(Currency::JPY)->value();    // 'JPY' (BackedEnum)

See common native enum contracts.

Useful patterns

These examples are organized around application needs rather than library types. The following API sections explain how the underlying abstractions work.

1. Presentation and context-specific behavior

Keep presentation concerns out of the domain layer. An order status is a domain concept, but its display label, color, icon, and localization are presentation concerns. Adding them directly to the domain enum would couple it to the needs of the UI. An extension keeps those responsibilities separate without changing the original enum.

The wrapper can also carry context such as a locale, which native enum cases cannot store as instance properties. The same enum can have separate wrappers for UI labels, colors, or other contexts without accumulating unrelated methods in its definition.

flowchart LR
    JA["OrderStatusPresentation<br/>locale: ja"] -->|wraps| P["OrderStatus::Paid"]
    EN["OrderStatusPresentation<br/>locale: en"] -->|wraps| P
    JA -->|label| J["支払い済み"]
    EN -->|label| E["Paid"]
Loading
use Notonza\PhpEnumEx\Extension\Case\EnumCase;
use Notonza\PhpEnumEx\Extension\Collection\EnumCollection;

enum OrderStatus {
    case Pending;
    case Paid;
}

/** @extends EnumCase<OrderStatus> */
final readonly class OrderStatusPresentation extends EnumCase {

    public function __construct(OrderStatus $status, private string $locale) {
        parent::__construct($status);
    }

    public function label(): string {
        return match ($this->unwrap()) {
            OrderStatus::Pending => $this->locale === 'ja' ? '支払い待ち' : 'Pending',
            OrderStatus::Paid    => $this->locale === 'ja' ? '支払い済み' : 'Paid',
        };
    }
}

Use the same native case with different presentation contexts:

$status = OrderStatus::Paid;

$ja = new OrderStatusPresentation($status, 'ja');
$en = new OrderStatusPresentation($status, 'en');

$ja->label(); // 支払い済み
$en->label(); // Paid

$ja->unwrap() === $status; // true
$ja->is($en); // true: both wrap the same native case

The same context-specific behavior can be applied to a collection:

$statuses = EnumCollection::of(OrderStatus::class);

$japanese = $statuses->wrapCasesAs(
    fn (OrderStatus $case)
        => new OrderStatusPresentation($case, 'ja'),
);
$english = $statuses->wrapCasesAs(
    fn (OrderStatus $case)
        => new OrderStatusPresentation($case, 'en'),
);

$japanese->fromName('Paid')->label(); // '支払い済み'
$english->fromName('Paid')->label();  // 'Paid'

$japanese->fromName('Paid')->is(
    $english->fromName('Paid'),
); // true

$statuses->fromValue('Paid')->value(); // 'Paid'

See Presentation / OrderStatus.

Byte units: same enum, different formatting

Keep the original native enum unchanged. Bit shifts define exact powers of two; independent wrappers provide decimal and hexadecimal behavior. The decimal wrapper also exposes the byte count, decimal digit count, and conversion to kilobytes.

use Notonza\PhpEnumEx\Extension\Case\EnumCase;
use Notonza\PhpEnumEx\Extension\Collection\EnumCollection;

enum ByteUnit: int {
    case BYTE     = 1;
    case KIBIBYTE = 1 << 10;
    case MEBIBYTE = 1 << 20;
    case GIBIBYTE = 1 << 30;
}

/** @extends EnumCase<ByteUnit> */
final readonly class ByteUnitDecimal extends EnumCase {

    public static function from(ByteUnit $unit): self {
        return new self($unit);
    }

    public function bytes(): int {
        return $this->unwrap()->value;
    }

    public function format(): string {
        return number_format($this->bytes());
    }

    public function digits(): int {
        return strlen((string) $this->bytes());
    }

    public function toKilobytes(): float {
        return $this->bytes() / 1000;
    }
}

/** @extends EnumCase<ByteUnit> */
final readonly class ByteUnitHex extends EnumCase {

    public static function from(ByteUnit $unit): self {
        return new self($unit);
    }

    public function format(): string {
        return '0x' . strtoupper(dechex($this->unwrap()->value));
    }
}

EnumCollection::of() selects the native enum. wrapCasesAs() selects how its cases are wrapped, returning a new collection without changing the original.

$units = EnumCollection::of(ByteUnit::class);

$decimal = $units->wrapCasesAs(ByteUnitDecimal::from(...));
$hex     = $units->wrapCasesAs(ByteUnitHex::from(...));

$decimal->fromName('MEBIBYTE')->format(); // '1,048,576'
$hex->fromName('MEBIBYTE')->format();     // '0x100000'
$units->fromName('MEBIBYTE')->value();   // 1048576

$unit = $decimal->fromName('MEBIBYTE');
$unit->bytes();       // 1048576
$unit->digits();      // 7
$unit->toKilobytes(); // 1048.576

$decimal->fromName('MEBIBYTE')->is($hex->fromName('MEBIBYTE')); // true

See ByteUnit. The decimal grouping and hexadecimal formatting are illustrative. toKilobytes() uses decimal kilobytes (1 kB = 1000 bytes), not kibibytes (1 KiB = 1024 bytes).

Formatting monetary amounts

Currency formatting is another presentation concern. A string-backed currency enum can retain its logical value while a wrapper supplies a display convention.

use Notonza\PhpEnumEx\Extension\Case\EnumCase;

enum Currency: string {
    case JPY = 'JPY';
    case USD = 'USD';
    case EUR = 'EUR';
}

/** @extends EnumCase<Currency> */
final readonly class CurrencyFormatter extends EnumCase {

    public static function from(Currency $currency): self {
        return new self($currency);
    }

    public function symbol(): string {
        return match ($this->unwrap()) {
            Currency::JPY => '¥',
            Currency::USD => '$',
            Currency::EUR => '€',
        };
    }

    public function format(int|float $amount, bool $grouping = true): string {
        $decimals = match ($this->unwrap()) {
            Currency::JPY                => 0,
            Currency::USD, Currency::EUR => 2,
        };

        return $this->symbol() . number_format($amount, $decimals, '.', $grouping ? ',' : '');
    }
}

$currency = CurrencyFormatter::from(Currency::JPY);

$currency->value(); // 'JPY'
$currency->symbol(); // '¥'
$currency->format(1234); // '¥1,234'
$currency->format(1234, grouping: false); // '¥1234'

CurrencyFormatter::from(Currency::USD)->format(1234.5); // '$1,234.50'
CurrencyFormatter::from(Currency::USD)->format(1234.5, grouping: false); // '$1234.50'
CurrencyFormatter::from(Currency::EUR)->format(1234.5); // '€1,234.50'

The formatter applies the currency's usual number of decimal places with a fixed display convention. Digit grouping is enabled by default and can be disabled with grouping: false. It is not locale-aware and does not perform currency conversion.

See Backed / Currency.

The byte unit example above uses the same extension mechanism with integer backing values.

2. Extend an enum from a third-party library

Suppose a vendor SDK exposes a PaymentStatus enum. Application-specific policies can be added without modifying the SDK or wrapping its values in a second enum definition.

use Notonza\PhpEnumEx\Extension\Case\EnumCase;
use Examples\NativeExtension\External\Vendor\PaymentStatus;

/** @extends EnumCase<PaymentStatus> */
final readonly class PaymentStatusPolicy extends EnumCase {

    public static function from(PaymentStatus $status): self {
        return new self($status);
    }

    public function requiresNotification(): bool {
        return match ($this->unwrap()) {
            PaymentStatus::Succeeded, PaymentStatus::Failed    => true,
            PaymentStatus::Processing, PaymentStatus::Refunded => false,
        };
    }
}

$policy = PaymentStatusPolicy::from(PaymentStatus::Failed);
$policy->requiresNotification(); // true
$policy->unwrap() === PaymentStatus::Failed; // true

The example simulates a vendor SDK; replace the imported enum with the actual vendor type in an application. See External / PaymentStatus.

3. Share and specialize behavior through inheritance

Native enums cannot inherit from other enums or classes. Extension classes can share implementation through an abstract parent and specialize it for distinct enum types.

use Notonza\PhpEnumEx\Extension\Case\EnumCase;

/**
 * @template TCase of BackedEnum
 * @extends EnumCase<TCase>
 */
abstract readonly class PermissionPolicy extends EnumCase {

    abstract public function level(): int;

    final public function allows(int $requiredLevel): bool {
        return $this->level() >= $requiredLevel;
    }
}

For example, ArticleAccess and UserAccess can extend this policy for ArticlePermission and UserPermission respectively, sharing level comparisons while defining their own operations. This assumes a hierarchical permission model; real authorization rules may require additional checks.

ArticleAccess::from(ArticlePermission::Write)->canPublish(); // false
UserAccess::from(UserPermission::Admin)->canDeleteUser(); // true

See Inheritance / Permission.

4. Strategy: vary behavior without changing the enum

Use a single native enum for weight categories and choose a strategy according to the destination. Each strategy receives the same type of enum case but supplies a different implementation. This example fixes the strategy constructor so the inherited factory can safely instantiate every subclass. If strategies require different constructor arguments, define factories in their concrete classes instead.

classDiagram
    class AirmailWeight {
        <<enumeration>>
        UpTo25Grams
        UpTo50Grams
    }
    class EnumCase
    class AirmailRateStrategy {
        <<abstract>>
        +postage() int
    }
    class AsiaAirmailRate {
        +postage() int
    }
    class EuropeAirmailRate {
        +postage() int
    }

    EnumCase <|-- AirmailRateStrategy
    AirmailRateStrategy <|-- AsiaAirmailRate
    AirmailRateStrategy <|-- EuropeAirmailRate
    AirmailRateStrategy --> AirmailWeight : wraps one case of
Loading
use Notonza\PhpEnumEx\Extension\Case\EnumCase;

enum AirmailWeight: int {
    case UpTo25Grams = 25;
    case UpTo50Grams = 50;
}

/** @extends EnumCase<AirmailWeight> */
abstract readonly class AirmailRateStrategy extends EnumCase {

    final protected function __construct(AirmailWeight $weight) {
        parent::__construct($weight);
    }

    final public static function from(AirmailWeight $weight): static {
        return new static($weight);
    }

    abstract public function postage(): int;
}

final readonly class AsiaAirmailRate extends AirmailRateStrategy {

    public function postage(): int {
        return match ($this->unwrap()) {
            AirmailWeight::UpTo25Grams => 90,
            AirmailWeight::UpTo50Grams => 160,
        };
    }
}

final readonly class EuropeAirmailRate extends AirmailRateStrategy {

    public function postage(): int {
        return match ($this->unwrap()) {
            AirmailWeight::UpTo25Grams => 110,
            AirmailWeight::UpTo50Grams => 190,
        };
    }
}

A business function can depend on the shared strategy type instead of selecting a destination itself. With a fixed origin, the concrete strategy determines the destination region, while the enum case determines the weight category.

function calculatePostage(AirmailRateStrategy $rate): int {
    return $rate->postage();
}

$weight = AirmailWeight::UpTo25Grams;

calculatePostage(AsiaAirmailRate::from($weight)); // 90
calculatePostage(EuropeAirmailRate::from($weight)); // 110

Use the same strategies across a collection:

use Notonza\PhpEnumEx\Extension\Collection\EnumCollection;

$weights = EnumCollection::of(AirmailWeight::class);

$asia   = $weights->wrapCasesAs(AsiaAirmailRate::from(...));
$europe = $weights->wrapCasesAs(EuropeAirmailRate::from(...));

calculatePostage($asia->fromValue(25)); // 90
calculatePostage($europe->fromValue(25)); // 110

$affordable = fn (AirmailRateStrategy $rate): bool
    => $rate->postage() <= 100;

array_keys($asia->filter($affordable)); // ['UpTo25Grams']
array_keys($europe->filter($affordable)); // []

The concrete strategies above are selected explicitly for illustration. In an application, configuration or runtime context can determine the strategy through a factory, a resolver, or a dependency injection container. The collection does not need to know how that choice was made.

For example, an application-defined resolver can return a factory, a strategy class, or a native enum case. The following are independent usage examples based on the linked implementation. The resolver implementations are omitted here; each approach has its own executable example linked below. They share the enum, strategies and business function from AirmailPostage.php.

Resolve a factory (a typed Closure) and pass it directly to the collection (AirmailPostageByFactory.php):

$destination = 'asia'; // Selected by application configuration or runtime context.

$rateFactory = AirmailRateFactory::resolve($destination); // returns Closure

$rates = EnumCollection::of(AirmailWeight::class)
    ->wrapCasesAs($rateFactory);

calculatePostage($rates->fromValue(25)); // 90 (for $destination = 'asia')

Alternatively, resolve a strategy type (a class-string) and turn its factory method into a Closure (AirmailPostageByType.php):

$rateType = AirmailRate::resolve($destination); // returns class-string

$rates = EnumCollection::of(AirmailWeight::class)
    ->wrapCasesAs($rateType::from(...));

calculatePostage($rates->fromValue(25)); // 90 (for $destination = 'asia')

Or resolve a native enum case that provides a strategy factory method (AirmailPostageByEnum.php):

$region = AirmailRegion::resolve($destination); // returns enum

$rates = EnumCollection::of(AirmailWeight::class)
    ->wrapCasesAs($region->rate(...));

calculatePostage($rates->fromValue(25)); // 90 (for $destination = 'asia')

All three approaches separate strategy selection from business logic. A factory can also capture additional configuration or dependencies when constructing wrappers. The enum-based approach lets one native enum determine the behavior of another. AirmailRateFactory, AirmailRate and AirmailRegion are application-defined examples, not EnumEx APIs.

The original enum remains unchanged. New strategies can be added without modifying its definition or existing strategies. The rates are illustrative, not current postal rates. The complete example also includes an Africa strategy. See Strategies / AirmailPostage.

5. Reuse and combine existing behaviors

Suppose a localized order-status label already exists, and a badge needs that label together with a badge-specific color. Rather than duplicating translation logic or inheriting from the presentation class, retain the existing presentation object and delegate its behavior.

$presentation = new OrderStatusPresentation(OrderStatus::Paid, 'ja');
$badge = new OrderStatusBadge($presentation);

$badge->label(); // '支払い済み'
$badge->color(); // 'green'
$badge->is($presentation); // true

The existing extension is reused without changing native case identity. See Composing Enum Extensions for the implementation.

6. Decisions based on combinations of enum cases

Some business rules depend on several independent enumerated conditions. For example, a cancellation policy may depend on both order status and user role. The rules can be expressed as a decision table:

Order status Admin Guest
Pending Allowed Allowed
Paid Allowed Denied
$admin = new OrderStatusPolicy(OrderStatus::Paid, UserRole::Admin);
$guest = new OrderStatusPolicy(OrderStatus::Paid, UserRole::Guest);

$admin->canCancel(); // true
$guest->canCancel(); // false
$admin->equals($guest); // false

A native enum method or a policy service is sufficient when only the predicate is needed. A composite is useful when the combination itself must also be carried, compared, or inspected as one value. EnumComposite represents one combination, not the decision table itself. See Domain-specific composites for the implementation.

7. File permissions: same enum, different context

A bit flag occupies one bit. Combine flags into an integer mask and give each wrapper the mask for its context, without changing the original enum.

use Notonza\PhpEnumEx\Extension\Case\EnumCase;
use Notonza\PhpEnumEx\Extension\Collection\EnumCollection;

enum FilePermission: int {
    case READ    = 1 << 0;
    case WRITE   = 1 << 1;
    case EXECUTE = 1 << 2;
}

/** @extends EnumCase<FilePermission> */
final readonly class PermissionCheck extends EnumCase {

    public function __construct(
        FilePermission $permission,
        private int    $mask,
    ) {
        parent::__construct($permission);
    }

    public function isGranted(): bool {
        $flag = $this->unwrap()->value;

        return ($this->mask & $flag) === $flag;
    }
}

Use filter() and reject() to select granted and denied permissions:

$mask = FilePermission::READ->value
      | FilePermission::WRITE->value;

$permissions = EnumCollection::of(FilePermission::class);
$checks = $permissions->wrapCasesAs(
    fn (FilePermission $case)
        => new PermissionCheck($case, $mask),
);

$granted = $checks->filter(
    fn (PermissionCheck $case): bool
        => $case->isGranted(),
);

$denied = $checks->reject(
    fn (PermissionCheck $case): bool
        => $case->isGranted(),
);

array_keys($granted); // ['READ', 'WRITE']
array_keys($denied);  // ['EXECUTE']

$guest = $permissions->wrapCasesAs(
    fn (FilePermission $case)
        => new PermissionCheck($case, FilePermission::READ->value),
);

$checks->fromName('WRITE')->isGranted(); // true
$guest->fromName('WRITE')->isGranted();  // false
$checks->fromName('WRITE')->is($guest->fromName('WRITE')); // true

The original native case remains the same, even when different masks produce different results. The mask is an integer, not an enum case; unknown bits do not create cases. This is an illustrative bit-flag example, not a complete authorization policy.

See FilePermission, the trait variant and the class-based inheritance variant.

Native Enum Extensions

Prefer native PHP enums for new domain types. Keep behavior intrinsic to the domain in the enum itself when appropriate. Use EnumCase when the behavior belongs outside that enum or needs a class-based extension mechanism.

For a simple method that naturally belongs to an enum you control, prefer an ordinary native enum method. A stateless helper or service may also be simpler than a wrapper when object state, inheritance, and instance-style APIs are not needed.

Extension contract

Extensions preserve the original native case. unwrap() returns that case, and is() / isNot() compare native case identity rather than wrapper state.

See the EnumCase reference for construction, typing and identity contracts.

Composing Enum Extensions

An EnumCase extension can retain another extension and reuse its behavior through delegation. This does not require any additional library API. Reuse the OrderStatus and OrderStatusPresentation definitions from the presentation example.

flowchart TD
    B["OrderStatusBadge"]
    P["OrderStatusPresentation"]
    S["OrderStatus::Paid"]

    B -->|retains and delegates label to| P
    B -->|wraps| S
    P -->|wraps| S
    B -->|color| C["green"]
    P -->|label| L["支払い済み"]
Loading
/** @extends EnumCase<OrderStatus> */
final readonly class OrderStatusBadge extends EnumCase {

    public function __construct(
        private OrderStatusPresentation $presentation,
    ) {
        parent::__construct($presentation->unwrap());
    }

    public function label(): string {
        return $this->presentation->label();
    }

    public function color(): string {
        return match ($this->unwrap()) {
            OrderStatus::Pending => 'gray',
            OrderStatus::Paid    => 'green',
        };
    }
}

$presentation = new OrderStatusPresentation(OrderStatus::Paid, 'ja');

$badge = new OrderStatusBadge($presentation);

$badge->label(); // '支払い済み'
$badge->color(); // 'green'

$badge->is($presentation);    // true
$badge->is(OrderStatus::Paid); // true

The badge explicitly retains and delegates to the presentation object while preserving native case identity. See composition contracts.

See Composition / OrderStatusBadge for the runnable example, including additional statuses and locale checks.

This combines behaviors around one native case. Native Enum Composites, in contrast, represent multiple native cases as a single structured value.

Native Enum Collections

Use EnumCollection when you want collection operations on an enum without modifying its definition. The default collection creates standard EnumCase wrappers; custom factories preserve the concrete wrapper type in PHPDoc-aware static analysis.

Continuing the presentation example, the same collections also support lookup, iteration and other collection operations:

$statuses->names(); // ['Pending', 'Paid']
$statuses->isEmpty(); // false
$statuses->isNotEmpty(); // true
$statuses->fromName('Paid')->unwrap(); // OrderStatus::Paid

$japanese->tryFromName('Unknown'); // null

foreach ($japanese as $name => $presentation) {
    echo $presentation->label();
}

See the EnumCollection reference for factory, lookup, iteration, typing and exception contracts.

Mapping Operations

A map makes the source and target explicit. In an EnumCollection, a case is the original native enum instance; an element is the EnumCase wrapper created by the configured factory.

Continuing the presentation example, the pure OrderStatus enum has Pending and Paid cases:

$statuses->nameToValue(); // ['Pending' => 'Pending', 'Paid' => 'Paid']
$statuses->valueToName(); // ['Pending' => 'Pending', 'Paid' => 'Paid']

$statuses->nameToCase()['Paid']; // OrderStatus::Paid
$statuses->valueToCase()['Paid']; // OrderStatus::Paid

$japanese->nameToElement()['Paid']; // OrderStatusPresentation wrapper
$japanese->valueToElement()['Paid']->unwrap(); // OrderStatus::Paid

See mapping operations for all six maps, key conversion and collision rules.

Qualified names and information

qualifiedName() identifies the case by its native enum class and case name; qualifiedInfo() also includes the exported backing value for backed cases.

EnumCase::of(OrderStatus::Paid)->qualifiedName(); // e.g. 'App\\OrderStatus::Paid'
EnumCase::of(OrderStatus::Paid)->qualifiedInfo(); // e.g. 'App\\OrderStatus::Paid'
$statuses->qualifiedNames(); // list of qualified names
$statuses->listQualifiedInfo(' = '); // list of qualified information strings

See qualified names and information for formatting details.

Selection Operations

The four selection operations return arrays keyed by case name. Their generator counterparts evaluate selection lazily.

Operation Array result Lazy generator
General inclusion filter(array|Closure $selector) iterateFilter(array|Closure $selector)
General exclusion reject(array|Closure $selector) iterateReject(array|Closure $selector)
Explicit inclusion only(array $targets) iterateOnly(array $targets)
Explicit exclusion except(array $targets) iterateExcept(array $targets)
$statuses->filter(fn (EnumCase $case): bool => $case->is(OrderStatus::Paid));
$statuses->reject(fn (EnumCase $case): bool => $case->is(OrderStatus::Paid));
$statuses->only([OrderStatus::Paid]);
$statuses->except([OrderStatus::Paid]);

foreach ($statuses->iterateOnly([OrderStatus::Paid]) as $name => $case) {
    // ...
}

The same selection operations are available on native enum traits and Class-based Enum. See selection operations for matching and evaluation rules.

Native Enum Composites

EnumComposite represents several native enum cases as one readonly value. Unlike an EnumCase wrapper's additional context, all retained cases participate in structural comparison. Cases may belong to different enum types or repeat the same type. A composite is not a collection of every case of one enum type.

Representing sequences of enum cases

A travel route needs both the order and the repeated occurrence of a country:

use Notonza\PhpEnumEx\Extension\Composite\CompositeDuplicates;
use Notonza\PhpEnumEx\Extension\Composite\CompositeOrder;
use Notonza\PhpEnumEx\Extension\Composite\EnumComposite;

enum Country {
    case Japan;
    case France;
}

$route = EnumComposite::of(
    Country::Japan,
    Country::France,
    Country::Japan,
);

$route->unwrap(); // [Country::Japan, Country::France, Country::Japan]
$route->at(1);    // Country::France
count($route);    // 3

Order and duplicate policies

The default is CompositeOrder::Sensitive + CompositeDuplicates::Preserve: order matters to equals(), and all occurrences are retained. Select other policies before supplying the cases:

enum Requirement {
    case IdentityVerification;
    case AgeVerification;
    case AddressVerification;
}

$defaultRequirements = [
    Requirement::IdentityVerification,
    Requirement::AgeVerification,
];

$regionalRequirements = [
    Requirement::IdentityVerification,
    Requirement::AddressVerification,
];

$requirements = EnumComposite::as(
    CompositeOrder::Insensitive,
    CompositeDuplicates::Remove,
)->of(
    ...$defaultRequirements,
    ...$regionalRequirements,
);

count($requirements); // 3
$requirements->has(Requirement::AddressVerification); // true

When merging requirements, a repeated verification is needed only once, and the order does not affect comparison. Both order policies preserve input order in storage and iteration. See order and duplicate policies for the complete contract.

Order Preserve Remove Reject
Sensitive Sequence Ordered unique sequence Ordered unique sequence (validated)
Insensitive Multiset Set Set (validated)

For more policy examples, see Composite / ConstructionPolicies: merge or validate an ordered workflow, compare package contents including quantities, and validate an unordered set of notification channels. Together with the examples above, these cover all six construction-policy combinations.

Structural equality

Compare the retained sequence with equalsExactly(), multiplicities with equalsIgnoringOrder(), or use the configured order policy with equals(). See structural equality for the full comparison contract.

For example, the same countries in a different order have the same multiplicities but are not the same sequence:

$other = EnumComposite::of(
    Country::France,
    Country::Japan,
    Country::Japan,
);

$route->equalsExactly($other);       // false
$route->equalsIgnoringOrder($other); // true
$route->equals($other);              // false

$unordered = EnumComposite::as(CompositeOrder::Insensitive);
$a = $unordered->of(...$route->unwrap());
$b = $unordered->of(...$other->unwrap());

$a->equals($b); // true

Membership and access

Use has(), hasAll(), and hasAny() to check membership; at() accesses cases by zero-based index. Native PHP serialization is not supported.

See membership, access and serialization contracts.

Domain-specific composites

A subclass can name the roles of its components and add behavior. Continuing the decision table example, reuse OrderStatus from the presentation example and define UserRole:

enum UserRole {
    case Admin;
    case Guest;
}

final readonly class OrderStatusPolicy extends EnumComposite {

    public function __construct(
        public OrderStatus $status,
        public UserRole    $role,
    ) {
        parent::__construct(
            CompositeOrder::Insensitive,
            CompositeDuplicates::Reject,
            $status,
            $role,
        );
    }

    public function canCancel(): bool {
        return match ([$this->status, $this->role]) {
            [OrderStatus::Pending, UserRole::Admin] => true,
            [OrderStatus::Pending, UserRole::Guest] => true,
            [OrderStatus::Paid, UserRole::Admin]    => true,
            default                                 => false,
        };
    }
}

Use the typed properties when the roles matter. Both cases participate in structural comparison. See domain-specific composites for subclass and factory contracts.

See EnumComposite for runnable examples, including typed subclasses, dynamic requirements and duplicate rejection.

Native Enum Traits

For enums you own, use traits to add shared operations without wrapping the enum. This is useful when collection operations or debugging helpers should be available directly on several native enum types, but there is no need for an extension object:

use Notonza\PhpEnumEx\EnumTraits\EnumCollections;
use Notonza\PhpEnumEx\EnumTraits\EnumMethods;

enum Status: string {
    use EnumCollections;
    use EnumMethods;

    case Pending = 'pending';
    case Paid    = 'paid';
}

Status::names(); // ['Pending', 'Paid']
Status::values(); // ['pending', 'paid']
Status::only(['paid']); // ['Paid' => Status::Paid]
Status::except([Status::Paid]); // ['Pending' => Status::Pending]
Status::fromValue('paid') === Status::Paid; // true
Status::Paid->qualifiedInfo(); // Status::Paid => 'paid'

EnumCollections provides static operations over native cases; EnumMethods provides single-case operations. Both work with pure and backed enums.

See the native enum traits reference for the method list and detailed contracts.

For example, a pure enum can use exactly the same value operations:

enum Direction {
    use EnumCollections;
    use EnumMethods;

    case North;
    case South;
}

Direction::values(); // ['North', 'South']
Direction::fromValue('North') === Direction::North; // true
Direction::North->value(); // 'North'

Working with bit flags

An int-backed enum can represent individual permission flags. A bitwise OR combines them into an integer mask; filter() and reject() can then select granted and denied permissions using a shared predicate.

use Notonza\PhpEnumEx\EnumTraits\EnumCollections;

enum FilePermission: int {
    use EnumCollections;

    case READ    = 1 << 0;
    case WRITE   = 1 << 1;
    case EXECUTE = 1 << 2;

    /** @return array<string, self> */
    public static function granted(int $mask): array {
        return self::filter(
            fn (self $permission): bool
                => $permission->isGrantedBy($mask),
        );
    }

    /** @return array<string, self> */
    public static function denied(int $mask): array {
        return self::reject(
            fn (self $permission): bool
                => $permission->isGrantedBy($mask),
        );
    }

    public function isGrantedBy(int $mask): bool {
        return ($mask & $this->value) === $this->value;
    }
}

$mask = FilePermission::READ->value
      | FilePermission::WRITE->value;

FilePermission::READ->isGrantedBy($mask);    // true
FilePermission::EXECUTE->isGrantedBy($mask); // false

array_keys(FilePermission::granted($mask)); // ['READ', 'WRITE']
array_keys(FilePermission::denied($mask));  // ['EXECUTE']

The mask is an integer, not an enum case. The collections contain the declared cases only, and unknown bits do not produce additional cases. This is a simplified bit-flag example, not a complete authorization policy.

See Collections / FilePermission and the class-based inheritance variant.

Combine library traits with your own traits

The library's collection methods can serve as building blocks for application-specific traits. For example, a custom JoinsEnumValues trait can turn all backing values into a comma- or semicolon-delimited list for an API filter or export configuration.

enum ShipmentStatus: string {
    use EnumCollections;
    use JoinsEnumValues;

    case Unspecified = '';
    case Pending     = '0';
    case Shipped     = '1';
    case Delivered   = '2';
}

ShipmentStatus::joinValues();                    // ',0,1,2'
ShipmentStatus::joinValues(';', skipEmpty: true); // '0;1;2'

JoinsEnumValues is an example of an application-defined trait, not a library API. It builds on values() and optionally excludes empty strings while preserving valid values such as '0'. See UseTrait / JoinsEnumValues.

Detailed documentation

See the documentation index for the complete API reference, public namespaces, migration guide and development documentation.

Running the native enum examples

After setting up your development environment, run each script independently with assertions enabled:

php -d zend.assertions=1 examples/NativeExtension/Presentation/OrderStatus.php

See the complete example list. Examples are not included in Composer dist archives.

Running examples in Docker

Use Docker Compose 2.39.3 or later so that the local build provenance setting is correctly forwarded to Bake.

Follow the Docker setup above, then run the same example commands or vendor/bin/phpunit inside the PHP container. Exit the shell and run docker compose down when finished.

See Docker development for configuration, dependency synchronization and troubleshooting.

Class-based Enums

The original class-based Enum is still part of this library. See its dedicated documentation for usage and examples.

Read the Class-based Enum documentation.

Background

This library was created in 2019 for PHP 7.0 and later, when PHP did not yet have built-in enums, inspired by this article (Japanese). Beyond simply defining enumerated values, its class-based Enum made it possible to express enumerated types with type-specific behavior and properties that could also be extended through inheritance.

With the introduction of native enums in PHP 8.1, the language itself took on many of the roles previously fulfilled by this library.

EnumEx has since evolved to extend the possibilities of native enums rather than replace them.

Through EnumCase, EnumCollection, EnumComposite and reusable traits, EnumEx extends native enum expressiveness while preserving native case identity.

The original class-based Enum also remains part of EnumEx, enabling forms of expression that native enums cannot provide.

I call it いーなめ

About

Native enum extensions, reusable enum traits, and class-based enums for PHP >= 8.4.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages