Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions README-ClassBased.md
Original file line number Diff line number Diff line change
Expand Up @@ -353,10 +353,42 @@ The method throws `EnumDomainException` if two distinct enum values produce the

`NAN` is not a supported enum constant value because it never equals itself, even in a strict comparison. An enum declaring it throws `UnsupportedEnumValueTypeException` during constant validation. Other float values, including `INF` and `-INF`, remain valid for ordinary enum operations.

### Mapping and qualified information aliases

The historical Class-based Enum methods and their internal implementations remain unchanged. The newer naming conventions are available through aliases and simple projections of the existing operations.

| New name | Existing operation |
| --- | --- |
| `qualifiedName()` | `canonicalName()` |
| `qualifiedInfo($delimiter)` | `debugOutput($delimiter)` |
| `listQualifiedInfo($delimiter)` | `listDebugOutput($delimiter)` |
| `qualifiedNames()` | List of existing `canonicalName()` results |
| `nameToValue()` | `constants()` |
| `nameToElement()` / `nameToCase()` | `elements()` |
| `valueToCase()` | `valueToElement()` |
| `valueToName()` | Existing `valueToElement()` map projected to element names |

The case-named aliases return the existing cached class-based enum elements, not native UnitEnum instances. Name-to-value maps preserve original scalar/null values and retain constant validation. Value-keyed maps retain the existing key conversions and collision checks described above, including for floats and null. Qualified formatting preserves the historical format and configurable delimiter.

The original names are not deprecated or removed. New final methods may conflict with methods already declared in custom subclasses; rename conflicting subclass methods when upgrading to the next major release.

The aliases also reserve new case-insensitive method names for the purposes of constant shortcut calls. See the following migration note; retaining the original methods does not guarantee compatibility with every previously valid constant shortcut.

### Constants that share a method name

PHP resolves method names case-insensitively. If `ExampleEnum` defines a `FILTER` constant, `ExampleEnum::FILTER()` resolves to the existing `filter()` method. Retrieve the enum element by its constant name with `ExampleEnum::of('FILTER')`. The same applies to other collection method names, such as `REJECT`, `ONLY`, `EXCEPT` and `ITERATEFILTER`.

**Migration from v2:** the newly introduced method names are `qualifiedName`, `qualifiedInfo`, `qualifiedNames`, `listQualifiedInfo`, `nameToValue`, `nameToElement`, `nameToCase`, `valueToCase`, and `valueToName`. If a constant has any of these names (regardless of case), its previous `CONSTANT()` shortcut is shadowed by the declared method. A static alias may return a map or list instead of the element; a non-static alias called statically raises an error. Constant declarations and explicit lookups remain valid.

For example, if an existing enum defines integer constants NAMETOVALUE and QUALIFIEDNAME:

```php
ExampleEnum::of('NAMETOVALUE'); // the original cached element
ExampleEnum::of('QUALIFIEDNAME'); // the original cached element
```

Replace affected shortcut calls with explicit `of()` lookups before upgrading. This is an additional breaking change for the next major release, not a removal of the historical API.

### Dispatching on enum objects

`switch` compares enum objects with `==`, the same comparison as `Enum::is()`. Separate instances of the same class with equal properties can match. Both functions below use `AirmailWeightType` from the [AirMail example](https://github.com/gachakra/php-enumex/blob/553c95e735aa88df371a59084cadb263815aba50/examples/ClassBased/Strategies/AirmailPostage.php).
Expand Down
97 changes: 73 additions & 24 deletions README.md

Large diffs are not rendered by default.

49 changes: 49 additions & 0 deletions docs/adr/0011-mapping-and-qualified-formatting.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# ADR 0011: Explicit mapping and qualified formatting APIs

- Status: Proposed (implementation candidate for the next major release)
- Date: 2026-12-03
- Related: ADR 0004, 0006, 0007, 0009, 0010

## Context

The native APIs used elements() for a name-keyed map and valueToElement() for a value-keyed map. This obscured the difference between native cases and configured wrapper elements. Canonical names and debug output were useful technical representations but their names did not clearly express qualification or distinguish returning strings from printing.

The owner chose to revise the native API in the next major development cycle and preserve historical Class-based Enum operations through aliases rather than rewriting their implementation. The release version remains a separate decision.

## Mapping decision

Use the source-to-target pattern for complete maps, not individual lookups:

- nameToValue() and valueToName(): original logical values and exact case names.
- nameToCase() and valueToCase(): original native instances.
- nameToElement() and valueToElement(): configured EnumCase wrappers in the instance collection.

The native collection exposes all six. The native trait exposes the four case and scalar maps because it has no wrapper factory. Rename native elements() to nameToElement() in the instance collection and to nameToCase() in the trait; rename the trait's valueToElement() to valueToCase(). Do not add native aliases for the replaced names. Keep the instance valueToElement() contract. Native cases(), protected raw-case access, single lookup, selection and iteration retain their existing meanings.

Scalar and native-case maps do not invoke the wrapper factory. The maps preserve declaration order. Logical values remain their original int/string types; PHP array-key conversions apply only to value keys. Reuse the existing checked value map for all value-keyed operations; detect key collisions before invoking any wrapper factory. Empty maps are valid. Do not use application-overridable trait methods as implementation dependencies.

## Qualified formatting decision

Use qualifiedName() and qualifiedInfo() for single cases; qualifiedNames() and listQualifiedInfo() for collections. Retire native canonicalName(), debugOutput() and listDebugOutput(). Qualification describes the technical identity of the case, not a business name or stable persistence identifier. The receiver already identifies a case, so a Case prefix would be redundant. Info is not pluralized; list makes the collection return shape explicit.

Example: App\\Currency::JPY and App\\Currency::JPY => 392. Preserve the existing format without a leading namespace separator, the delimiter parameter, exported backing values and the pure-case name-only rule. Return strings, never print. Do not include wrapper-specific extra state. Qualified list operations do not invoke wrapper factories.

Considered alternatives include fullName(), caseInfo(), enumInfo(), debugString(), debugStrings(), qualifiedCaseName(), and qualifiedNameAndValue(). FullName may suggest a business display name; debug-only names unnecessarily restrict usage; Case repeats the receiver's concept; long names expose formatting details. QualifiedInfo is a library-specific term paired with qualifiedName. FQCN denotes a class name, not a case-qualified name.

## Historical class-based API

Keep constants(), elements(), valueToElement(), canonicalName(), debugOutput() and listDebugOutput() and their internal calls intact. Add nameToValue() as an alias of constants(); nameToElement() and nameToCase() as aliases of elements(); valueToCase() as an alias of valueToElement(). The case aliases return the existing class-based elements, not native cases. ValueToName() projects the checked value-to-element map to names. QualifiedName(), qualifiedInfo() and listQualifiedInfo() delegate to their existing counterparts; qualifiedNames() projects canonical names. These projections reuse existing implementations instead of introducing independent formatting, caching or key-conversion algorithms.

Do not change the historical logical value domain (bool, float, int, string, null), validation, caches, exceptions or internal usage. Keep old names available without deprecation.

## Compatibility and verification

Native renames are breaking API changes. New final methods may collide with downstream subclass methods, including class-based subclasses even though historical names remain. Do not treat this as a backward-compatible v2 release. Update public migration instructions, PHPDoc, executable examples and type/runtime fixtures. Review all changed signatures, array-key behavior, empty cases, lazy wrapper generation, and class-based aliases on PHP 8.4 and 8.5 before release.

### Independent review follow-up

The maintainer approved retaining the new aliases after the review of PR #18. PHP resolves declared method names case-insensitively before __callStatic(), so the new names can shadow previously valid constant shortcuts. Static aliases return their normal map or list; a non-static alias called statically raises an error. Explicit of() lookups still return the original cached element. The migration guide lists all newly reserved names, and regression tests cover both dispatch outcomes and explicit lookup. This is an accepted breaking change for the next major release, distinct from subclass declaration conflicts.

Keep the native valueToName() projection intact. The PHPStan 2.3.7 diagnostic for the empty trait consumer is a false positive because the map callback is never executed. Use the existing report checker with an exact consumer, method range, identifier and message match; keep the empty fixture and fail unrelated diagnostics. Revisit the allowance on analyser upgrades. Omit the unresolved Pure attribute from the new qualifiedInfo() forwarding alias while leaving the original debugOutput() annotation and implementation intact.

Mapping is separate from scalar lookups, EnumComposite, and future immutable/lazy collection designs.
3 changes: 2 additions & 1 deletion docs/adr/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,6 @@ These records capture the motivation and decisions behind PHP EnumEx, including
| [0008](0008-lazy-collection-view.md) | Consider a lazy collection view | Proposed |
| [0009](0009-documentation-and-extension-composition.md) | Explain common enum behavior and composition through useful examples | Proposed |
| [0010](0010-composite-enum-cases.md) | Explore a composite of native enum cases | Proposed |
| [0011](0011-mapping-and-qualified-formatting.md) | Explicit mapping and qualified formatting APIs | Proposed |

Accepted means the architectural direction was agreed on 2026-12-02. Open implementation details are identified separately and must not be treated as finalized API contracts. Amend or supersede these records when decisions change.
Accepted means the architectural direction has been agreed. Open implementation details are identified separately and must not be treated as finalized API contracts. Amend or supersede these records when decisions change.
8 changes: 8 additions & 0 deletions docs/static-analysis/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,11 @@ phpstan analyse --level=max --autoload-file=vendor/autoload.php docs/static-anal
The positive check requires zero diagnostics, including the standard factory return types, list and iterator contracts, and typed subclass properties. The negative fixture must report exactly four argument-type diagnostics on the deliberately invalid calls. The CI step checks their identifiers and line numbers; do not suppress unrelated findings.

The Composite `unwrap()` initialization guard remains necessary for subclasses that omit the parent constructor. PHPStan 2.3.7 no longer reports `throws.unusedType` or `isset.initializedProperty` for this guard after custom serialization hooks were introduced: its initialization analysis treats classes with custom serialization as potentially uninitialized outside construction. The formerly required local ignores were therefore removed after independent re-review. Keep the runtime guard and the explicit exception contract; do not suppress unmatched ignores or narrow the CI analysis scope to hide diagnostics.

## Mapping and qualified formatting contracts

The collection positive fixture also checks the distinct native case and configured wrapper types in nameToCase(), valueToCase(), nameToElement() and valueToElement(), plus the scalar maps and qualified information lists. The selection consumer fixture checks the matching native trait APIs. These checks are part of the existing CI commands.

Independent review of PR #18 at commit [103b668](https://github.com/gachakra/php-enumex/commit/103b6682145ad51d3b145dbef9f41af4c0928c69) reproduced a PHPStan 2.3.7 false positive for EnumCollections::valueToName() on both PHP 8.4 and 8.5. For the empty consumer, the checked value map is inferred as `array<int|string, never>`. The callback parameter is specialized to never, and its name property access produces a return-type diagnostic. At runtime array_map() never calls the callback and returns an empty array. The report checker therefore allows only the exact trait path and EmptyColour consumer, the reflected valueToName() method range, identifier `return.type` and message `Anonymous function should return string but returns mixed.`. It reports this separately as a known false positive; the empty fixture and the direct map projection remain unchanged. Other diagnostics must still fail the check. Recheck and remove this allowance when upgrading PHPStan if the diagnostic is resolved.

The new Class-based qualifiedInfo() forwarding alias omits the unresolved JetBrains Pure attribute. The historical debugOutput() method and its existing annotation are unchanged. No new tool dependency or broad source-analysis suppression is introduced.
14 changes: 13 additions & 1 deletion docs/static-analysis/check-selection-report.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@
'iterateReject' => ['foreach.emptyArray', 'generator.keyType'],
];

// PHPStan 2.3.7 specializes the map callback to never for this empty consumer.
// The callback is never executed at runtime. Keep the exception specific to
// this consumer, method, diagnostic identifier and exact message.
$valueToName = $trait->getMethod('valueToName');
$emptyColourPath = $traitPath . ' (in context of class EnumExSelectionStaticAnalysis\\EmptyColour)';

$failed = $report['totals']['errors'] !== 0;
foreach ($report['errors'] as $error) {
fwrite(STDERR, $error . PHP_EOL);
Expand All @@ -41,7 +47,13 @@
}
}
}
echo $known ? '[pre-existing] ' : '[unexpected] ';
$emptyMapFalsePositive = $path === $emptyColourPath
&& $diagnostic['line'] >= $valueToName->getStartLine()
&& $diagnostic['line'] <= $valueToName->getEndLine()
&& ($diagnostic['identifier'] ?? '') === 'return.type'
&& $diagnostic['message'] === 'Anonymous function should return string but returns mixed.';
echo $emptyMapFalsePositive ? '[known false positive] ' : ($known ? '[pre-existing] ' : '[unexpected] ');
$known = $known || $emptyMapFalsePositive;
echo $path, ':', $diagnostic['line'], ': [', $diagnostic['identifier'] ?? 'unknown', '] ', $diagnostic['message'], PHP_EOL;
$failed = $failed || !$known;
}
Expand Down
9 changes: 9 additions & 0 deletions docs/static-analysis/collection-positive.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,12 @@ function checkFactory(Closure $factory): void {
foreach ($custom->iterateReject(['Paid']) as $element) {
assertType('EnumExStaticAnalysis\LocalizedStatus', $element);
}

assertType('array<string, EnumExStaticAnalysis\\Status>', $custom->nameToCase());
assertType('array<int|string, EnumExStaticAnalysis\\Status>', $custom->valueToCase());
assertType('array<string, EnumExStaticAnalysis\\LocalizedStatus>', $custom->nameToElement());
assertType('array<int|string, EnumExStaticAnalysis\\LocalizedStatus>', $custom->valueToElement());
assertType('array<string, int|string>', $custom->nameToValue());
assertType('array<int|string, string>', $custom->valueToName());
assertType('list<string>', $custom->qualifiedNames());
assertType('list<string>', $custom->listQualifiedInfo());
7 changes: 7 additions & 0 deletions docs/static-analysis/selection-positive.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,10 @@ final class Second extends Enum {
foreach (First::iterateReject($targets) as $element) {
assertType('EnumExSelectionStaticAnalysis\First', $element);
}

assertType('array<string, EnumExSelectionStaticAnalysis\\Colour>', Colour::nameToCase());
assertType('array<int|string, EnumExSelectionStaticAnalysis\\Colour>', Colour::valueToCase());
assertType('array<string, int|string>', Colour::nameToValue());
assertType('array<int|string, string>', Colour::valueToName());
assertType('list<string>', Colour::qualifiedNames());
assertType('list<string>', Colour::listQualifiedInfo());
2 changes: 1 addition & 1 deletion examples/NativeExtension/Backed/Currency.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,4 @@ public function format(int|float $amount, bool $grouping = true): string {
assert(CurrencyFormatter::from(Currency::EUR)->format(1234.5, grouping: false) === '€1234.50');
assert(CurrencyFormatter::from(Currency::EUR)->format(1234.5) === '€1,234.50');
assert(CurrencyFormatter::from(Currency::USD)->format(0) === '$0.00');
assert($currency->debugOutput() === Currency::class . "::JPY => 'JPY'");
assert($currency->qualifiedInfo() === Currency::class . "::JPY => 'JPY'");
9 changes: 9 additions & 0 deletions examples/NativeExtension/Collections/FilePermission.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ public function isGranted(): bool {
$permissions = EnumCollection::of(FilePermission::class);
assert(!$permissions->isEmpty());
assert($permissions->isNotEmpty());
assert($permissions->nameToValue() === ['READ' => 1, 'WRITE' => 2, 'EXECUTE' => 4]);
assert($permissions->valueToName() === [1 => 'READ', 2 => 'WRITE', 4 => 'EXECUTE']);
assert($permissions->nameToCase()['WRITE'] === FilePermission::WRITE);
assert($permissions->valueToCase()[2] === FilePermission::WRITE);
assert($permissions->qualifiedNames()[1] === FilePermission::class . '::WRITE');
assert($permissions->listQualifiedInfo(' = ')[1] === FilePermission::class . '::WRITE = 2');

$empty = EnumCollection::of(NoPermission::class);
assert($empty->isEmpty());
Expand All @@ -52,6 +58,9 @@ public function isGranted(): bool {
=> new PermissionCheck($case, $mask),
);

assert($checks->nameToElement()['WRITE']->isGranted());
assert($checks->valueToElement()[2]->unwrap() === FilePermission::WRITE);

$granted = $checks->filter(
fn (PermissionCheck $case): bool
=> $case->isGranted(),
Expand Down
14 changes: 12 additions & 2 deletions examples/NativeTraits/Collections/EnumCollections.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,19 @@ enum OrderStatus: string {
'Monday' => DayOfWeek::Monday,
'Wednesday' => DayOfWeek::Wednesday,
]);
assert(DayOfWeek::Monday->debugOutput() === DayOfWeek::class . '::Monday');
assert(DayOfWeek::Monday->qualifiedInfo() === DayOfWeek::class . '::Monday');

assert(OrderStatus::values() === ['pending', 'paid', 'shipped']);
assert(OrderStatus::nameToValue() === ['Pending' => 'pending', 'Paid' => 'paid', 'Shipped' => 'shipped']);
assert(OrderStatus::valueToName() === ['pending' => 'Pending', 'paid' => 'Paid', 'shipped' => 'Shipped']);
assert(OrderStatus::nameToCase()['Paid'] === OrderStatus::Paid);
assert(OrderStatus::valueToCase()['paid'] === OrderStatus::Paid);
assert(OrderStatus::qualifiedNames() === [
OrderStatus::class . '::Pending',
OrderStatus::class . '::Paid',
OrderStatus::class . '::Shipped',
]);
assert(OrderStatus::listQualifiedInfo(' = ')[1] === OrderStatus::class . "::Paid = 'paid'");
assert(OrderStatus::fromValue('paid') === OrderStatus::Paid);
assert(OrderStatus::hasValue('pending'));
assert(OrderStatus::filter(['paid', OrderStatus::Pending]) === [
Expand All @@ -53,7 +63,7 @@ enum OrderStatus: string {
'Pending' => OrderStatus::Pending,
'Paid' => OrderStatus::Paid,
]);
assert(OrderStatus::Paid->debugOutput() === OrderStatus::class . "::Paid => 'paid'");
assert(OrderStatus::Paid->qualifiedInfo() === OrderStatus::class . "::Paid => 'paid'");

assert(OrderStatus::only(['paid']) === ['Paid' => OrderStatus::Paid]);
assert(OrderStatus::reject(static fn (OrderStatus $case): bool => $case->is(OrderStatus::Paid)) === [
Expand Down
4 changes: 2 additions & 2 deletions examples/NativeTraits/Collections/FilePermission.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,6 @@ public static function denied(int $mask): array {
]);

assert(FilePermission::granted(0) === []);
assert(FilePermission::denied(0) === FilePermission::elements());
assert(FilePermission::granted($mask | FilePermission::EXECUTE->value) === FilePermission::elements());
assert(FilePermission::denied(0) === FilePermission::nameToCase());
assert(FilePermission::granted($mask | FilePermission::EXECUTE->value) === FilePermission::nameToCase());
assert(FilePermission::denied($mask | FilePermission::EXECUTE->value) === []);
Loading