notonza / php-enumex
Native enum extensions, reusable enum traits, and class-based enums for PHP >= 8.4
Requires
- php: ^8.4
Requires (Dev)
- phpunit/phpunit: ^13.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
- dev-main
- v2.0.0
- v1.1.0
- v1.0.0
- dev-chore/apply-coding-style
- dev-chore/separate-composer-service
- dev-feature/mapping-and-qualified-formatting
- dev-feature/enum-composite
- dev-develop-v2
- dev-feature/v2-selection-api
- dev-feature/collection-examples
- dev-feature/enum-case-collection
- dev-develop
- dev-feature/collection-filter-except
- dev-refactor/enumex
- dev-style/align-enum-declarations
- dev-ci/php-matrix
- dev-refactor/notonza
- dev-fix/class-based-enum-value-safety
- dev-feature/native-enum-extension
- dev-test/enum-coverage
- dev-feature/php84-enum
- dev-feature/unit_tests_2
- dev-feature/to_strings
- dev-feature/examples
- dev-feature/unit_tests
- dev-feature/base
This package is auto-updated.
Last update: 2026-12-03 08:01:46 UTC
README
Same enum, different behavior.
EnumEx (pronounced "enum-E-X", or simply "enum-ex") stands for Enum Extension, bringing extra flexibility and expressiveness to PHP enums.
Native enum extensions, collections, composites, reusable enum traits, and class-based enums for PHP >= 8.4.
Table of contents
- Quick examples
- Requirements and installation
- Choosing an approach
- Working with enums regardless of their type
- Useful patterns
- Native Enum Extensions
- Composing Enum Extensions
- Native Enum Collections
- Native Enum Composites
- Native Enum Traits
- Running the native enum examples
- Running examples in Docker
- Class-based Enums
- Background
Quick examples
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\EnumCase; use Notonza\PhpEnumEx\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).
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\EnumCase; use Notonza\PhpEnumEx\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.
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 describes the development API for the next major release. The native mapping and qualified-formatting names below replace v2 names and are not available in the released v2 package. For the stable v2 API, use the README at the installed release tag:
composer require notonza/php-enumex:^2.0
For local development from a Git checkout:
composer install vendor/bin/phpunit
The public APIs are organized by approach:
| Namespace | Purpose |
|---|---|
Notonza\PhpEnumEx |
EnumCase, EnumCollection, and EnumComposite |
Notonza\PhpEnumEx\EnumTraits |
EnumMethods and EnumCollections |
Notonza\PhpEnumEx\ClassBased |
Original class-based Enum and its exceptions |
The Internal namespace is not a public API.
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 lets you work with both pure enums (UnitEnum only) and backed enums (BackedEnum) through the same API, without having to distinguish between them.
For example, given a pure Direction enum with North and a string-backed Currency enum with JPY = 'JPY':
use Notonza\PhpEnumEx\EnumCase; EnumCase::of(Direction::North)->value(); // 'North' (UnitEnum only) EnumCase::of(Currency::JPY)->value(); // 'JPY' (BackedEnum)
A pure case's logical value is its name; a backed case's logical value is its original int or string backing value. The default string conversion uses the logical value. EnumCollection and the EnumCollections trait share the logical-value, lookup, and selection contracts. Native operations such as from() and tryFrom() remain specific to backed enums; the original native type is preserved.
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.
use Notonza\PhpEnumEx\EnumCase; use Notonza\PhpEnumEx\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.
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\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\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\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
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.
use Notonza\PhpEnumEx\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\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.
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 wrap a native case; they are not themselves
UnitEnumorBackedEnum. - Concrete extensions should accept the specific enum type in a constructor or factory, and declare the generic type with
@extends EnumCase<YourEnum>. - A subclass overriding the constructor must call
parent::__construct()with the wrapped case. Readonly subclasses may add their own initialized readonly state. If the parent constructor is omitted, case access throwsLogicException. Readonly does not enforce deep immutability of additional objects. unwrap()returns the original case.is()andisNot()compare native case identity, even across different extension classes; additional wrapper state is ignored. Wrapper object identity is not guaranteed.qualifiedName()uses the native enum class and case name.qualifiedInfo()adds the exported backing value for backed cases; pure cases show only the qualified name.EnumCase::of($case)creates a standard wrapper for any native case.value()always returns an int or string;__toString()may be overridden for presentation without changing logical values or identity.- Choose domain names for native enums and role-specific names for wrappers, e.g.
OrderStatusandOrderStatusPresentation, orAirmailWeightandAirmailRateStrategy.
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.
/** @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 retains the presentation object, delegates its localized label and supplies its own color policy. The original native case remains the identity of both extensions. Additional context and wrapper class do not participate in is(). This is explicit composition and delegation, not an automatic wrapper-flattening mechanism.
Rewrapping a case through unwrap() alone does not retain the previous wrapper. Use explicit composition when the existing extension's state or behavior must remain available.
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(); }
of()selects the enum type;wrapCasesAs()returns a new standard collection with a replacement factory that receives the original native case. The default factory isEnumCase::of(...). No wrapper is generated until needed, and wrappers are not cached.- A factory must return an
EnumCasewrapping the exact input case; non-wrapper results throwTypeError, different cases throwLogicException. Factory exceptions propagate, including in try lookups. nameToElement(), selection operations and iterators preserve declaration order and case-name keys.foreachandcount()are supported.random()throwsValueErrorfor an empty enum.fromName()/fromValue()throwValueErrorfor missing cases; their try variants return null for misses. Non-string names or non-int/string values throwTypeErroreven in weak mode.has()andhasValue()return false for invalid inputs. Pure logical values are case names.names(),values(),count(),isEmpty(),isNotEmpty(),has(),hasValue(),qualifiedNames()andlistQualifiedInfo()do not create wrappers.isEmpty()checks whether the enum declares zero cases;isNotEmpty()is its complement.valueToElement()follows PHP array-key conversion rules and rejects duplicate resulting keys before invoking the factory.- Custom readonly collection subclasses must pass an explicit typed factory to the protected parent constructor; the standard public factories create the base collection, not arbitrary subclasses.
- Compatibility note for upgrades from v2.0.0: the new final collection methods can conflict with methods already declared by custom subclasses. Rename conflicting methods before upgrading. See the mapping and qualified-formatting migration notes below.
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
For an int-backed Currency enum with JPY = 392, USD = 840 and EUR = 978, the same methods produce the following mappings:
| Operation | Result |
|---|---|
nameToValue() |
['JPY' => 392, 'USD' => 840, 'EUR' => 978] |
valueToName() |
[392 => 'JPY', 840 => 'USD', 978 => 'EUR'] |
nameToCase() |
['JPY' => Currency::JPY, ...] |
valueToCase() |
[392 => Currency::JPY, ...] |
nameToElement() |
['JPY' => EnumCase::of(Currency::JPY), ...] |
valueToElement() |
[392 => EnumCase::of(Currency::JPY), ...] |
All maps preserve declaration order. Only element maps invoke the wrapper factory; case and scalar maps work directly with the native cases. Name-to-value maps retain original logical values, including numeric strings. Value-keyed maps use PHP array-key conversion (for example, the string '0' becomes the integer key 0) and throw LogicException on duplicate keys. Value-to-element maps validate all keys before invoking the factory. Empty enums return empty maps.
The native EnumCollections trait provides the four case and scalar maps as static operations. It has no wrapper factory, so it does not provide element maps. Native cases() remains a list, and fromName() / fromValue() remain individual strict lookups rather than map access.
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. These are technical, human-readable strings for diagnostics, logs and developer tools, not stable business identifiers. Pure cases use only their qualified name. Neither method prints or changes state.
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
The default delimiter is ' => ' for backed cases. Both collection operations return a list in declaration order without creating wrappers. The native traits provide the corresponding single-case and static collection operations.
Migration from v2: for native EnumCase and EnumMethods, replace canonicalName() with qualifiedName() and debugOutput() with qualifiedInfo(). Replace listDebugOutput() with listQualifiedInfo() on EnumCollection and EnumCollections. Replace EnumCollection's elements() with nameToElement(), and the EnumCollections trait's elements() / valueToElement() with nameToCase() / valueToCase(). EnumCollection's valueToElement() is unchanged. The historical Class-based Enum API retains its original names.
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) { // ... }
Array selection matches native case identity (including the case inside an EnumCase wrapper) or exact logical values, not wrapper reference identity. An empty array matches nothing: inclusion returns no elements and exclusion retains all elements. Closure selectors receive the configured wrapper. Array selection constructs only retained wrappers; closure selection constructs one wrapper per evaluated case.
The same selection operations are available as static methods on the native collection trait and Class-based Enum. To exclude cases using a closure, use reject() or iterateReject(), not except() or iterateExcept().
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\CompositeDuplicates; use Notonza\PhpEnumEx\CompositeOrder; use Notonza\PhpEnumEx\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. Duplicate handling is a construction policy: Preserve retains occurrences, Remove retains the first occurrence of each case, and Reject throws InvalidArgumentException if a case is repeated. Duplicate detection uses native case identity, not names or backing values.
| 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
equalsExactly() compares the retained sequence; equalsIgnoringOrder() compares multiplicities without order. Both ignore the construction and comparison policies. equals() requires the same order policy on both operands and uses the corresponding comparison. Subclass and additional state do not affect these comparisons.
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. Repeated targets in hasAll() require repeated occurrences. Empty and singleton composites are supported. isEmpty() and isNotEmpty() check whether the composite itself contains any cases. hasAll() with no targets is true and hasAny() with no targets is false, regardless of whether the composite is empty. at() throws OutOfBoundsException for a missing zero-based index. Named variadic keys are not retained.
Native PHP serialization and deserialization are not supported yet. The final __serialize() and __unserialize() hooks throw LogicException for serialization and ordinary object-format restoration of EnumComposite and its subclasses. Subclasses implementing the legacy Serializable interface are outside the supported serialization contract: PHP can dispatch legacy C records directly to their unserialize() method, bypassing the inherited hook. Do not use this interface to persist composites. Persist the required domain data explicitly and reconstruct the composite through its normal construction API instead.
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. The composite's structural comparison and membership operations remain available, and both status and role participate in equality. The standard of() and as()->of() factories always create a standard EnumComposite, not a subclass.
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'
EnumCollectionsworks with pure and backed enums. Both supportnameToCase(),nameToValue(),valueToCase(),valueToName(),names(),count(),has(),of()(alias offromName()),fromName(),tryFromName(),values(),hasValue(),fromValue(),tryFromValue(),qualifiedNames(),filter(),reject(),only(),except(),iterate(),iterateFilter(),iterateReject(),iterateOnly(),iterateExcept(),random()andlistQualifiedInfo().EnumMethodsaddsvalue(),is(),isNot(),qualifiedName()andqualifiedInfo(). Both traits are stateless.- Collection operations follow the same strict lookup, matching, key and order rules as the instance collection, but yield native cases rather than wrappers. Closure predicates receive native cases. Built-in operations use the declared native cases directly, not other application-overridable trait methods.
- Pure enum logical values are case names; backed enum logical values are backing values. Native
cases(),from()andtryFrom()are unchanged. Traits are opt-in; resolve method-name conflicts in the consuming enum.
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; public function isGrantedBy(int $mask): bool { return ($mask & $this->value) === $this->value; } /** @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), ); } } $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.
Running the native enum examples
The examples use directory-based Examples\... namespaces and are available in the linked source revision, not in the Composer dist archive. To run them, use a Git checkout of the corresponding version and run composer install first. Run each script independently with assertions enabled:
php -d zend.assertions=1 examples/NativeExtension/Presentation/OrderStatus.php php -d zend.assertions=1 examples/NativeExtension/Composition/OrderStatusBadge.php php -d zend.assertions=1 examples/NativeExtension/Composite/EnumComposite.php php -d zend.assertions=1 examples/NativeExtension/Composite/ConstructionPolicies.php php -d zend.assertions=1 examples/NativeExtension/External/PaymentStatus.php php -d zend.assertions=1 examples/NativeExtension/Inheritance/Permission.php php -d zend.assertions=1 examples/NativeExtension/Strategies/AirmailPostage.php php -d zend.assertions=1 examples/NativeExtension/Strategies/AirmailPostageByFactory.php php -d zend.assertions=1 examples/NativeExtension/Strategies/AirmailPostageByType.php php -d zend.assertions=1 examples/NativeExtension/Strategies/AirmailPostageByEnum.php php -d zend.assertions=1 examples/NativeExtension/Backed/Currency.php php -d zend.assertions=1 examples/NativeExtension/Backed/ByteUnit.php php -d zend.assertions=1 examples/NativeExtension/Collections/FilePermission.php php -d zend.assertions=1 examples/NativeTraits/Collections/EnumCollections.php php -d zend.assertions=1 examples/NativeTraits/Collections/FilePermission.php php -d zend.assertions=1 examples/NativeTraits/UseTrait/JoinsEnumValues.php
Running examples in Docker
From a Git checkout (not the installed Composer package):
docker compose up -d --build --remove-orphans docker compose ps -a
Docker is a CLI-only development environment; no HTTP service or host port is published. The --remove-orphans option also removes the obsolete Nginx service if you used an older checkout.
Both services use the same PHP 8.4 CLI image and mount the project directory. Only the composer service builds the shared local image; the php service uses that image without pulling it. To build the image explicitly, run docker compose build composer.
The one-shot composer service installs the locked development dependencies into the host project's vendor/ directory, then exits. On a fresh startup with docker compose up, the php service waits for Composer to exit successfully and then remains available for development. The host IDE and both services see the same installed dependencies. The named composer-cache volume retains downloaded package data independently of the installed dependencies.
An exited Composer service with exit code 0 is expected. If installation fails during a fresh startup, the dependent PHP service does not start; inspect docker compose logs composer. This startup condition is not a continuous dependency health check: an already-running PHP container can remain available after a failed installation, and docker compose restart does not guarantee successful dependency synchronization. Use the explicit Composer command below to synchronize dependencies while PHP is running, and check its exit status before running tests.
Enter the PHP container to run examples or tests:
docker compose exec php bash
php -d zend.assertions=1 examples/NativeExtension/Presentation/OrderStatus.php
vendor/bin/phpunit
After switching branches, changing the lock file, or recovering from a failed installation, synchronize dependencies explicitly (also when PHP is already running):
docker compose run --rm composer
To deliberately update dependency versions and the lock file:
docker compose run --rm composer composer update
The service command can also be overridden with other Composer commands. Avoid running tests or another Composer installation while the shared vendor/ directory is being modified. The current development image runs as root; on native Linux, files created in the bind mount may be owned by root.
Use docker compose down to stop and remove the development containers. The host vendor/ directory and the named download cache persist. Removing volumes with docker compose down -v also removes the download cache.
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 composition with EnumCase and EnumCollection, as well as reusable traits, EnumEx makes it possible to add behavior suited to different purposes and contexts while respecting native enums.
The original class-based Enum also remains part of EnumEx, enabling forms of expression that native enums cannot provide.
I call it いーなめ