diff --git a/README-ClassBased.md b/README-ClassBased.md index dfb4fbb..3dc5ea8 100644 --- a/README-ClassBased.md +++ b/README-ClassBased.md @@ -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). diff --git a/README.md b/README.md index 06be68d..8dacf48 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,8 @@ Native enum extensions, collections, composites, reusable enum traits, and [clas - [Extension contract](#extension-contract) - [Composing Enum Extensions](#composing-enum-extensions) - [Native Enum Collections](#native-enum-collections) + - [Mapping Operations](#mapping-operations) + - [Qualified names and information](#qualified-names-and-information) - [Selection Operations](#selection-operations) - [Native Enum Composites](#native-enum-composites) - [Representing sequences of enum cases](#representing-sequences-of-enum-cases) @@ -116,7 +118,7 @@ $unit->toKilobytes(); // 1048.576 $decimal->fromName('MEBIBYTE')->is($hex->fromName('MEBIBYTE')); // true ``` -See [ByteUnit](https://github.com/gachakra/php-enumex/blob/553c95e735aa88df371a59084cadb263815aba50/examples/NativeExtension/Backed/ByteUnit.php). The decimal grouping and hexadecimal formatting are illustrative. `toKilobytes()` uses decimal kilobytes (1 kB = 1000 bytes), not kibibytes (1 KiB = 1024 bytes). +See [ByteUnit](https://github.com/gachakra/php-enumex/blob/f00f7ac3412789ba8ce179fb449be4a3cb43b4c0/examples/NativeExtension/Backed/ByteUnit.php). 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 @@ -187,7 +189,7 @@ $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](https://github.com/gachakra/php-enumex/blob/59875a96a82a02e1c64d4f8132646af2bffd63bf/examples/NativeExtension/Collections/FilePermission.php), the [trait variant](#working-with-bit-flags) and the [class-based inheritance variant](README-ClassBased.md#extend-bit-flags-through-inheritance). +See [FilePermission](https://github.com/gachakra/php-enumex/blob/f00f7ac3412789ba8ce179fb449be4a3cb43b4c0/examples/NativeExtension/Collections/FilePermission.php), the [trait variant](#working-with-bit-flags) and the [class-based inheritance variant](README-ClassBased.md#extend-bit-flags-through-inheritance). ## Requirements and installation @@ -195,7 +197,7 @@ The Composer package is `notonza/php-enumex` (formerly `gachakra/php-enum`). Its 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 v2 API. Install the released v2 package with Composer. For features introduced after the installed release, use a checkout of the corresponding source revision: +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: ```bash composer require notonza/php-enumex:^2.0 @@ -318,7 +320,7 @@ $japanese->fromName('Paid')->is( $statuses->fromValue('Paid')->value(); // 'Paid' ``` -See [Presentation / OrderStatus](https://github.com/gachakra/php-enumex/blob/553c95e735aa88df371a59084cadb263815aba50/examples/NativeExtension/Presentation/OrderStatus.php). +See [Presentation / OrderStatus](https://github.com/gachakra/php-enumex/blob/f00f7ac3412789ba8ce179fb449be4a3cb43b4c0/examples/NativeExtension/Presentation/OrderStatus.php). #### Formatting monetary amounts @@ -372,7 +374,7 @@ 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](https://github.com/gachakra/php-enumex/blob/553c95e735aa88df371a59084cadb263815aba50/examples/NativeExtension/Backed/Currency.php). +See [Backed / Currency](https://github.com/gachakra/php-enumex/blob/f00f7ac3412789ba8ce179fb449be4a3cb43b4c0/examples/NativeExtension/Backed/Currency.php). The [byte unit example](#byte-units-same-enum-different-formatting) above uses the same extension mechanism with integer backing values. @@ -404,7 +406,7 @@ $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](https://github.com/gachakra/php-enumex/blob/553c95e735aa88df371a59084cadb263815aba50/examples/NativeExtension/External/PaymentStatus.php). +The example simulates a vendor SDK; replace the imported enum with the actual vendor type in an application. See [External / PaymentStatus](https://github.com/gachakra/php-enumex/blob/f00f7ac3412789ba8ce179fb449be4a3cb43b4c0/examples/NativeExtension/External/PaymentStatus.php). ### 3. Share and specialize behavior through inheritance @@ -434,7 +436,7 @@ ArticleAccess::from(ArticlePermission::Write)->canPublish(); // false UserAccess::from(UserPermission::Admin)->canDeleteUser(); // true ``` -See [Inheritance / Permission](https://github.com/gachakra/php-enumex/blob/553c95e735aa88df371a59084cadb263815aba50/examples/NativeExtension/Inheritance/Permission.php). +See [Inheritance / Permission](https://github.com/gachakra/php-enumex/blob/f00f7ac3412789ba8ce179fb449be4a3cb43b4c0/examples/NativeExtension/Inheritance/Permission.php). ### 4. Strategy: vary behavior without changing the enum @@ -518,9 +520,9 @@ 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](https://github.com/gachakra/php-enumex/blob/553c95e735aa88df371a59084cadb263815aba50/examples/NativeExtension/Strategies/AirmailPostage.php). +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](https://github.com/gachakra/php-enumex/blob/f00f7ac3412789ba8ce179fb449be4a3cb43b4c0/examples/NativeExtension/Strategies/AirmailPostage.php). -Resolve a factory (a typed Closure) and pass it directly to the collection ([AirmailPostageByFactory.php](https://github.com/gachakra/php-enumex/blob/553c95e735aa88df371a59084cadb263815aba50/examples/NativeExtension/Strategies/AirmailPostageByFactory.php)): +Resolve a factory (a typed Closure) and pass it directly to the collection ([AirmailPostageByFactory.php](https://github.com/gachakra/php-enumex/blob/f00f7ac3412789ba8ce179fb449be4a3cb43b4c0/examples/NativeExtension/Strategies/AirmailPostageByFactory.php)): ```php $destination = 'asia'; // Selected by application configuration or runtime context. @@ -533,7 +535,7 @@ $rates = EnumCollection::of(AirmailWeight::class) 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](https://github.com/gachakra/php-enumex/blob/553c95e735aa88df371a59084cadb263815aba50/examples/NativeExtension/Strategies/AirmailPostageByType.php)): +Alternatively, resolve a strategy type (a class-string) and turn its factory method into a Closure ([AirmailPostageByType.php](https://github.com/gachakra/php-enumex/blob/f00f7ac3412789ba8ce179fb449be4a3cb43b4c0/examples/NativeExtension/Strategies/AirmailPostageByType.php)): ```php $rateType = AirmailRate::resolve($destination); // returns class-string @@ -544,7 +546,7 @@ $rates = EnumCollection::of(AirmailWeight::class) calculatePostage($rates->fromValue(25)); // 90 (for $destination = 'asia') ``` -Or resolve a native enum case that provides a strategy factory method ([AirmailPostageByEnum.php](https://github.com/gachakra/php-enumex/blob/553c95e735aa88df371a59084cadb263815aba50/examples/NativeExtension/Strategies/AirmailPostageByEnum.php)): +Or resolve a native enum case that provides a strategy factory method ([AirmailPostageByEnum.php](https://github.com/gachakra/php-enumex/blob/f00f7ac3412789ba8ce179fb449be4a3cb43b4c0/examples/NativeExtension/Strategies/AirmailPostageByEnum.php)): ```php $region = AirmailRegion::resolve($destination); // returns enum @@ -557,7 +559,7 @@ 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](https://github.com/gachakra/php-enumex/blob/553c95e735aa88df371a59084cadb263815aba50/examples/NativeExtension/Strategies/AirmailPostage.php). +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](https://github.com/gachakra/php-enumex/blob/f00f7ac3412789ba8ce179fb449be4a3cb43b4c0/examples/NativeExtension/Strategies/AirmailPostage.php). ### 5. Reuse and combine existing behaviors @@ -606,7 +608,7 @@ For a simple method that naturally belongs to an enum you control, prefer an ord - Concrete extensions should accept the specific enum type in a constructor or factory, and declare the generic type with `@extends EnumCase`. - 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 throws `LogicException`. Readonly does not enforce deep immutability of additional objects. - `unwrap()` returns the original case. `is()` and `isNot()` compare native case identity, even across different extension classes; additional wrapper state is ignored. Wrapper object identity is not guaranteed. -- `canonicalName()` uses the native enum class and case name. `debugOutput()` adds the exported backing value for backed cases; pure cases show only the canonical name. +- `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. `OrderStatus` and `OrderStatusPresentation`, or `AirmailWeight` and `AirmailRateStrategy`. @@ -651,7 +653,7 @@ The badge retains the presentation object, delegates its localized label and sup 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](https://github.com/gachakra/php-enumex/blob/13d4e2ba3353f69f704fa422b7aebcb40df31161/examples/NativeExtension/Composition/OrderStatusBadge.php) for the runnable example, including additional statuses and locale checks. +See [Composition / OrderStatusBadge](https://github.com/gachakra/php-enumex/blob/f00f7ac3412789ba8ce179fb449be4a3cb43b4c0/examples/NativeExtension/Composition/OrderStatusBadge.php) for the runnable example, including additional statuses and locale checks. This combines behaviors around one native case. [Native Enum Composites](#native-enum-composites), in contrast, represent multiple native cases as a single structured value. @@ -676,11 +678,58 @@ foreach ($japanese as $name => $presentation) { - `of()` selects the enum type; `wrapCasesAs()` returns a new standard collection with a replacement factory that receives the original native case. The default factory is `EnumCase::of(...)`. No wrapper is generated until needed, and wrappers are not cached. - A factory must return an `EnumCase` wrapping the exact input case; non-wrapper results throw `TypeError`, different cases throw `LogicException`. Factory exceptions propagate, including in try lookups. -- `elements()`, selection operations and iterators preserve declaration order and case-name keys. `foreach` and `count()` are supported. `random()` throws `ValueError` for an empty enum. +- `nameToElement()`, selection operations and iterators preserve declaration order and case-name keys. `foreach` and `count()` are supported. `random()` throws `ValueError` for an empty enum. - `fromName()` / `fromValue()` throw `ValueError` for missing cases; their try variants return null for misses. Non-string names or non-int/string values throw `TypeError` even in weak mode. `has()` and `hasValue()` return false for invalid inputs. Pure logical values are case names. -- `names()`, `values()`, `count()`, `isEmpty()`, `isNotEmpty()`, `has()`, `hasValue()` and `listDebugOutput()` 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. +- `names()`, `values()`, `count()`, `isEmpty()`, `isNotEmpty()`, `has()`, `hasValue()`, `qualifiedNames()` and `listQualifiedInfo()` 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 `isEmpty()` and `isNotEmpty()` methods can conflict with methods already declared by a custom collection subclass. Rename conflicting subclass methods before upgrading. +- 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: + +```php +$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. + +```php +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](README-ClassBased.md#mapping-and-qualified-information-aliases) retains its original names. ### Selection Operations @@ -777,7 +826,7 @@ When merging requirements, a repeated verification is needed only once, and the | Sensitive | Sequence | Ordered unique sequence | Ordered unique sequence (validated) | | Insensitive | Multiset | Set | Set (validated) | -For more policy examples, see [Composite / ConstructionPolicies](https://github.com/gachakra/php-enumex/blob/e6cf23b108ef571c17604a77a4e2cc14e55122a8/examples/NativeExtension/Composite/ConstructionPolicies.php): 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. +For more policy examples, see [Composite / ConstructionPolicies](https://github.com/gachakra/php-enumex/blob/f00f7ac3412789ba8ce179fb449be4a3cb43b4c0/examples/NativeExtension/Composite/ConstructionPolicies.php): 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 @@ -846,7 +895,7 @@ final readonly class OrderStatusPolicy extends EnumComposite { 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](https://github.com/gachakra/php-enumex/blob/13d4e2ba3353f69f704fa422b7aebcb40df31161/examples/NativeExtension/Composite/EnumComposite.php) for runnable examples, including typed subclasses, dynamic requirements and duplicate rejection. +See [EnumComposite](https://github.com/gachakra/php-enumex/blob/f00f7ac3412789ba8ce179fb449be4a3cb43b4c0/examples/NativeExtension/Composite/EnumComposite.php) for runnable examples, including typed subclasses, dynamic requirements and duplicate rejection. ## Native Enum Traits @@ -869,11 +918,11 @@ 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->debugOutput(); // Status::Paid => 'paid' +Status::Paid->qualifiedInfo(); // Status::Paid => 'paid' ``` -- `EnumCollections` works with pure and backed enums. Both support `elements()`, `names()`, `count()`, `has()`, `of()` (alias of `fromName()`), `fromName()`, `tryFromName()`, `values()`, `hasValue()`, `fromValue()`, `tryFromValue()`, `valueToElement()`, `filter()`, `reject()`, `only()`, `except()`, `iterate()`, `iterateFilter()`, `iterateReject()`, `iterateOnly()`, `iterateExcept()`, `random()` and `listDebugOutput()`. -- `EnumMethods` adds `value()`, `is()`, `isNot()`, `canonicalName()` and `debugOutput()`. Both traits are stateless. +- `EnumCollections` works with pure and backed enums. Both support `nameToCase()`, `nameToValue()`, `valueToCase()`, `valueToName()`, `names()`, `count()`, `has()`, `of()` (alias of `fromName()`), `fromName()`, `tryFromName()`, `values()`, `hasValue()`, `fromValue()`, `tryFromValue()`, `qualifiedNames()`, `filter()`, `reject()`, `only()`, `except()`, `iterate()`, `iterateFilter()`, `iterateReject()`, `iterateOnly()`, `iterateExcept()`, `random()` and `listQualifiedInfo()`. +- `EnumMethods` adds `value()`, `is()`, `isNot()`, `qualifiedName()` and `qualifiedInfo()`. 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()` and `tryFrom()` are unchanged. Traits are opt-in; resolve method-name conflicts in the consuming enum. @@ -940,7 +989,7 @@ 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](https://github.com/gachakra/php-enumex/blob/59875a96a82a02e1c64d4f8132646af2bffd63bf/examples/NativeTraits/Collections/FilePermission.php) and the [class-based inheritance variant](README-ClassBased.md#extend-bit-flags-through-inheritance). +See [Collections / FilePermission](https://github.com/gachakra/php-enumex/blob/f00f7ac3412789ba8ce179fb449be4a3cb43b4c0/examples/NativeTraits/Collections/FilePermission.php) and the [class-based inheritance variant](README-ClassBased.md#extend-bit-flags-through-inheritance). ### Combine library traits with your own traits @@ -961,7 +1010,7 @@ 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](https://github.com/gachakra/php-enumex/blob/553c95e735aa88df371a59084cadb263815aba50/examples/NativeTraits/UseTrait/JoinsEnumValues.php). +`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](https://github.com/gachakra/php-enumex/blob/f00f7ac3412789ba8ce179fb449be4a3cb43b4c0/examples/NativeTraits/UseTrait/JoinsEnumValues.php). ## Running the native enum examples diff --git a/docs/adr/0011-mapping-and-qualified-formatting.md b/docs/adr/0011-mapping-and-qualified-formatting.md new file mode 100644 index 0000000..dfabca9 --- /dev/null +++ b/docs/adr/0011-mapping-and-qualified-formatting.md @@ -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. diff --git a/docs/adr/README.md b/docs/adr/README.md index 9b954a9..4b83989 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -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. diff --git a/docs/static-analysis/README.md b/docs/static-analysis/README.md index a325e19..ae67e8f 100644 --- a/docs/static-analysis/README.md +++ b/docs/static-analysis/README.md @@ -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`. 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. diff --git a/docs/static-analysis/check-selection-report.php b/docs/static-analysis/check-selection-report.php index af2a45a..58f9089 100644 --- a/docs/static-analysis/check-selection-report.php +++ b/docs/static-analysis/check-selection-report.php @@ -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); @@ -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; } diff --git a/docs/static-analysis/collection-positive.php b/docs/static-analysis/collection-positive.php index d168e25..0abd9db 100644 --- a/docs/static-analysis/collection-positive.php +++ b/docs/static-analysis/collection-positive.php @@ -73,3 +73,12 @@ function checkFactory(Closure $factory): void { foreach ($custom->iterateReject(['Paid']) as $element) { assertType('EnumExStaticAnalysis\LocalizedStatus', $element); } + +assertType('array', $custom->nameToCase()); +assertType('array', $custom->valueToCase()); +assertType('array', $custom->nameToElement()); +assertType('array', $custom->valueToElement()); +assertType('array', $custom->nameToValue()); +assertType('array', $custom->valueToName()); +assertType('list', $custom->qualifiedNames()); +assertType('list', $custom->listQualifiedInfo()); diff --git a/docs/static-analysis/selection-positive.php b/docs/static-analysis/selection-positive.php index 6dddc33..f3be184 100644 --- a/docs/static-analysis/selection-positive.php +++ b/docs/static-analysis/selection-positive.php @@ -61,3 +61,10 @@ final class Second extends Enum { foreach (First::iterateReject($targets) as $element) { assertType('EnumExSelectionStaticAnalysis\First', $element); } + +assertType('array', Colour::nameToCase()); +assertType('array', Colour::valueToCase()); +assertType('array', Colour::nameToValue()); +assertType('array', Colour::valueToName()); +assertType('list', Colour::qualifiedNames()); +assertType('list', Colour::listQualifiedInfo()); diff --git a/examples/NativeExtension/Backed/Currency.php b/examples/NativeExtension/Backed/Currency.php index a0d1c9e..91dfaba 100644 --- a/examples/NativeExtension/Backed/Currency.php +++ b/examples/NativeExtension/Backed/Currency.php @@ -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'"); diff --git a/examples/NativeExtension/Collections/FilePermission.php b/examples/NativeExtension/Collections/FilePermission.php index 8a4262d..0e419bc 100644 --- a/examples/NativeExtension/Collections/FilePermission.php +++ b/examples/NativeExtension/Collections/FilePermission.php @@ -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()); @@ -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(), diff --git a/examples/NativeTraits/Collections/EnumCollections.php b/examples/NativeTraits/Collections/EnumCollections.php index 0f76393..6047c2b 100644 --- a/examples/NativeTraits/Collections/EnumCollections.php +++ b/examples/NativeTraits/Collections/EnumCollections.php @@ -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]) === [ @@ -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)) === [ diff --git a/examples/NativeTraits/Collections/FilePermission.php b/examples/NativeTraits/Collections/FilePermission.php index 6f076ea..361c510 100644 --- a/examples/NativeTraits/Collections/FilePermission.php +++ b/examples/NativeTraits/Collections/FilePermission.php @@ -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) === []); diff --git a/src/ClassBased/Enum.php b/src/ClassBased/Enum.php index 44bc503..e47e116 100644 --- a/src/ClassBased/Enum.php +++ b/src/ClassBased/Enum.php @@ -192,6 +192,26 @@ public final function debugOutput(string $delimiter = ' => '): string { return $this->canonicalName() . $delimiter . var_export($this->scalar, true); } + /** + * Alias of canonicalName(). + * + * Example: + * Currency::JPY()->qualifiedName(); // 'App\\Currency::JPY' + */ + public final function qualifiedName(): string { + return $this->canonicalName(); + } + + /** + * Alias of debugOutput(). + * + * Example: + * Currency::JPY()->qualifiedInfo(); // 'App\\Currency::JPY => 392' + */ + public final function qualifiedInfo(string $delimiter = ' => '): string { + return $this->debugOutput($delimiter); + } + /** * Compares enum objects using PHP object equality (==), including their class and properties. * Separate instances can be equal; this does not require identical object references (===). @@ -293,6 +313,26 @@ public final static function elements(): array { return self::$elements[$enum] = $values; } + /** + * Alias of elements(): constant names mapped to cached class-based enum elements. + * + * @return array + * @throws RootEnumMethodCallException If called directly on the abstract root Enum. + */ + public final static function nameToElement(): array { + return static::elements(); + } + + /** + * Compatibility alias of elements(); returns class-based enum elements, not native cases. + * + * @return array + * @throws RootEnumMethodCallException If called directly on the abstract root Enum. + */ + public final static function nameToCase(): array { + return static::elements(); + } + /** * Returns all reflected constant names and original values, including inherited constants. * Validates supported scalar/null types, rejects NAN and duplicate values, and requires a single non-null value type. @@ -324,6 +364,16 @@ public final static function constants(): array { return self::$constants[$enum] = $constants; } + /** + * Alias of constants(): constant names mapped to original scalar/null values. + * + * @return array + * @throws RootEnumMethodCallException If called directly on the abstract root Enum. + */ + public final static function nameToValue(): array { + return static::constants(); + } + /** * Returns the reflected constant names in their original order. * @@ -442,6 +492,28 @@ private static function floatToArrayKey(float $value): int|string { return sprintf('%.17h', $value); } + /** + * Compatibility alias of valueToElement(); returns class-based enum elements, not native cases. + * + * @return array + * @throws EnumDomainException If distinct values produce the same PHP array key. + * @throws RootEnumMethodCallException If called directly on the abstract root Enum. + */ + public final static function valueToCase(): array { + return static::valueToElement(); + } + + /** + * Projects the existing value-to-element map to constant names, preserving its keys and checks. + * + * @return array + * @throws EnumDomainException If distinct values produce the same PHP array key. + * @throws RootEnumMethodCallException If called directly on the abstract root Enum. + */ + public final static function valueToName(): array { + return array_map(static fn(self $element): string => $element->name(), static::valueToElement()); + } + /** * Returns matching cached elements with original name keys and reflected constant order. * A closure receives each element; array entries match enum equality via equals() or an exact scalar/null value. @@ -668,6 +740,29 @@ public final static function listDebugOutput(string $delimiter = ' => '): array )); } + /** + * Returns the canonical names of all elements, in reflected constant order. + * + * @return list + * @throws RootEnumMethodCallException If called directly on the abstract root Enum. + */ + public final static function qualifiedNames(): array { + return array_values(array_map( + static fn(self $element): string => $element->canonicalName(), + static::elements(), + )); + } + + /** + * Alias of listDebugOutput(). + * + * @return list + * @throws RootEnumMethodCallException If called directly on the abstract root Enum. + */ + public final static function listQualifiedInfo(string $delimiter = ' => '): array { + return static::listDebugOutput($delimiter); + } + /** * Returns a randomly selected cached element. * diff --git a/src/EnumCase.php b/src/EnumCase.php index 4a88b0f..b831894 100644 --- a/src/EnumCase.php +++ b/src/EnumCase.php @@ -128,22 +128,22 @@ final public function isNot(UnitEnum|self $other): bool { * Returns the original native enum's fully qualified class name followed by :: and the case name. * * Example: - * EnumCase::of(Currency::JPY)->canonicalName(); // 'App\Currency::JPY' + * EnumCase::of(Currency::JPY)->qualifiedName(); // 'App\Currency::JPY' */ - final public function canonicalName(): string { - return CaseFormatter::canonicalName($this->unwrap()); + final public function qualifiedName(): string { + return CaseFormatter::qualifiedName($this->unwrap()); } /** - * Returns the canonical name and, for backed enums, the exported backing value. + * Returns the qualified name and, for backed enums, the exported backing value. * * Example: - * EnumCase::of(Currency::JPY)->debugOutput(); // 'App\Currency::JPY => 392' - * EnumCase::of(Direction::North)->debugOutput(); // 'App\Direction::North' + * EnumCase::of(Currency::JPY)->qualifiedInfo(); // 'App\Currency::JPY => 392' + * EnumCase::of(Direction::North)->qualifiedInfo(); // 'App\Direction::North' * - * @param string $delimiter Separator between the canonical name and backing value. + * @param string $delimiter Separator between the qualified name and backing value. */ - final public function debugOutput(string $delimiter = ' => '): string { - return CaseFormatter::debugOutput($this->unwrap(), $delimiter); + final public function qualifiedInfo(string $delimiter = ' => '): string { + return CaseFormatter::qualifiedInfo($this->unwrap(), $delimiter); } } diff --git a/src/EnumCollection.php b/src/EnumCollection.php index 7d162dd..13f330e 100644 --- a/src/EnumCollection.php +++ b/src/EnumCollection.php @@ -154,16 +154,29 @@ private function validateWrapper(mixed $wrapped, UnitEnum $case): void { * Creates wrappers for all declared cases, keyed by case name in declaration order. * * Example: - * $currencies->elements(); + * $currencies->nameToElement(); * // ['JPY' => EnumCase::of(Currency::JPY), 'USD' => EnumCase::of(Currency::USD), * // 'EUR' => EnumCase::of(Currency::EUR)] * * @return array */ - final public function elements(): array { + final public function nameToElement(): array { return iterator_to_array($this->iterate()); } + /** + * Returns native cases keyed by their exact names, in declaration order. + * Does not invoke the wrapper factory. + * + * Example: + * $currencies->nameToCase(); // ['JPY' => Currency::JPY, 'USD' => Currency::USD, 'EUR' => Currency::EUR] + * + * @return array + */ + final public function nameToCase(): array { + return NativeCaseLookup::mapByName($this->cases()); + } + /** * Returns the declared case names in declaration order. * Does not invoke the wrapper factory. @@ -320,6 +333,53 @@ final public function tryFromValue(mixed $value): ?EnumCase { return $case === null ? null : $this->wrap($case); } + /** + * Returns logical values keyed by case name, in declaration order. + * Pure cases use their names; backed cases use their original backing values. + * Does not invoke the wrapper factory. + * + * Example: + * $currencies->nameToValue(); // ['JPY' => 392, 'USD' => 840, 'EUR' => 978] + * + * @return array + */ + final public function nameToValue(): array { + return array_map(NativeCaseValue::of(...), NativeCaseLookup::mapByName($this->cases())); + } + + /** + * Returns case names keyed by logical value, in declaration order. + * Uses PHP array-key conversion and rejects duplicate keys. + * Does not invoke the wrapper factory. + * + * Example: + * $currencies->valueToName(); // [392 => 'JPY', 840 => 'USD', 978 => 'EUR'] + * + * @return array + * @throws \LogicException If two cases produce the same array key. + */ + final public function valueToName(): array { + return array_map( + static fn (UnitEnum $case): string => $case->name, + NativeCaseValue::map($this->cases()), + ); + } + + /** + * Returns native cases keyed by logical value, in declaration order. + * PHP converts integer-like string keys to integers; duplicate keys are rejected. + * Does not invoke the wrapper factory. + * + * Example: + * $currencies->valueToCase(); // [392 => Currency::JPY, 840 => Currency::USD, 978 => Currency::EUR] + * + * @return array + * @throws LogicException If two cases produce the same array key. + */ + final public function valueToCase(): array { + return NativeCaseValue::map($this->cases()); + } + /** * Creates a map of logical values to wrappers in declaration order. * PHP converts integer-like string array keys to integers; the logical values remain unchanged. @@ -530,21 +590,35 @@ final public function random(): EnumCase { } /** - * Returns debug strings for all cases in declaration order. - * Pure cases use their canonical names; backed cases append their exported backing values using the supplied delimiter. + * Returns the fully qualified enum class and case names in declaration order. + * Does not invoke the wrapper factory. + * + * Example: + * $currencies->qualifiedNames(); + * // ['App\\Currency::JPY', 'App\\Currency::USD', 'App\\Currency::EUR'] + * + * @return list + */ + final public function qualifiedNames(): array { + return array_map(CaseFormatter::qualifiedName(...), $this->cases()); + } + + /** + * Returns qualified information strings for all cases in declaration order. + * Pure cases use their qualified names; backed cases append their exported backing values using the supplied delimiter. * Does not invoke the wrapper factory. * * Example: - * $currencies->listDebugOutput(); + * $currencies->listQualifiedInfo(); * // ['App\Currency::JPY => 392', 'App\Currency::USD => 840', * // 'App\Currency::EUR => 978'] * * @return list * @param string $delimiter Separator between a backed case name and its value. */ - final public function listDebugOutput(string $delimiter = ' => '): array { + final public function listQualifiedInfo(string $delimiter = ' => '): array { return array_map( - static fn (UnitEnum $case): string => CaseFormatter::debugOutput($case, $delimiter), + static fn (UnitEnum $case): string => CaseFormatter::qualifiedInfo($case, $delimiter), $this->cases(), ); } diff --git a/src/EnumTraits/EnumCollections.php b/src/EnumTraits/EnumCollections.php index 820ab51..2488eef 100644 --- a/src/EnumTraits/EnumCollections.php +++ b/src/EnumTraits/EnumCollections.php @@ -28,12 +28,12 @@ trait EnumCollections { * Returns every declared case, keyed by its exact case name, in declaration order. * * Example: - * Currency::elements(); + * Currency::nameToCase(); * // ['JPY' => Currency::JPY, 'USD' => Currency::USD, 'EUR' => Currency::EUR] * * @return array */ - public static function elements(): array { + public static function nameToCase(): array { return NativeCaseLookup::mapByName(static::cases()); } @@ -169,20 +169,50 @@ public static function tryFromValue(mixed $value): ?static { return NativeCaseLookup::byValue(static::cases(), $value); } + /** + * Returns logical values keyed by case name, in declaration order. + * Pure cases use their names; backed cases use their original backing values. + * + * Example: + * Currency::nameToValue(); // ['JPY' => 392, 'USD' => 840, 'EUR' => 978] + * + * @return array + */ + public static function nameToValue(): array { + return array_map(NativeCaseValue::of(...), NativeCaseLookup::mapByName(static::cases())); + } + + /** + * Returns case names keyed by logical value, in declaration order. + * Uses PHP array-key conversion and rejects duplicate keys. + * + * Example: + * Currency::valueToName(); // [392 => 'JPY', 840 => 'USD', 978 => 'EUR'] + * + * @return array + * @throws \LogicException If two cases produce the same array key. + */ + public static function valueToName(): array { + return array_map( + static fn (UnitEnum $case): string => $case->name, + NativeCaseValue::map(static::cases()), + ); + } + /** * Returns cases keyed by logical value in declaration order. * PHP converts integer-like string array keys to integers; lookup values themselves remain unchanged. * * Example: - * Currency::valueToElement(); + * Currency::valueToCase(); * // [392 => Currency::JPY, 840 => Currency::USD, 978 => Currency::EUR] - * Direction::valueToElement(); + * Direction::valueToCase(); * // ['North' => Direction::North, 'South' => Direction::South] * * @return array * @throws \LogicException If two cases produce the same array key. */ - public static function valueToElement(): array { + public static function valueToCase(): array { return NativeCaseValue::map(static::cases()); } @@ -364,20 +394,33 @@ public static function random(): static { } /** - * Returns debug strings for all cases in declaration order. - * Pure cases use their canonical names; backed cases append their exported backing values using the supplied delimiter. + * Returns the fully qualified enum class and case names in declaration order. + * + * Example: + * Currency::qualifiedNames(); + * // ['App\\Currency::JPY', 'App\\Currency::USD', 'App\\Currency::EUR'] + * + * @return list + */ + public static function qualifiedNames(): array { + return array_map(CaseFormatter::qualifiedName(...), static::cases()); + } + + /** + * Returns qualified information strings for all cases in declaration order. + * Pure cases use their qualified names; backed cases append their exported backing values using the supplied delimiter. * * Example: - * Currency::listDebugOutput(); + * Currency::listQualifiedInfo(); * // ['App\Currency::JPY => 392', 'App\Currency::USD => 840', * // 'App\Currency::EUR => 978'] * * @return list * @param string $delimiter Separator between a backed case name and its value. */ - public static function listDebugOutput(string $delimiter = ' => '): array { + public static function listQualifiedInfo(string $delimiter = ' => '): array { return array_map( - static fn (UnitEnum $case): string => CaseFormatter::debugOutput($case, $delimiter), + static fn (UnitEnum $case): string => CaseFormatter::qualifiedInfo($case, $delimiter), static::cases(), ); } diff --git a/src/EnumTraits/EnumMethods.php b/src/EnumTraits/EnumMethods.php index 6eea57f..709fb5f 100644 --- a/src/EnumTraits/EnumMethods.php +++ b/src/EnumTraits/EnumMethods.php @@ -54,23 +54,23 @@ public function isNot(UnitEnum $other): bool { * Returns the enum's fully qualified class name followed by :: and the case name. * * Example: - * Currency::JPY->canonicalName(); // 'App\Currency::JPY' + * Currency::JPY->qualifiedName(); // 'App\Currency::JPY' */ - public function canonicalName(): string { - return CaseFormatter::canonicalName($this); + public function qualifiedName(): string { + return CaseFormatter::qualifiedName($this); } /** - * Pure cases use their canonical names; backed cases append their exported backing values using the supplied delimiter. - * Returns a debug string for this case. + * Pure cases use their qualified names; backed cases append their exported backing values using the supplied delimiter. + * Returns a qualified information string for this case. * * Example: - * Currency::JPY->debugOutput(); // 'App\Currency::JPY => 392' - * Direction::North->debugOutput(); // 'App\Direction::North' + * Currency::JPY->qualifiedInfo(); // 'App\Currency::JPY => 392' + * Direction::North->qualifiedInfo(); // 'App\Direction::North' * * @param string $delimiter Separator between a backed case name and its value. */ - public function debugOutput(string $delimiter = ' => '): string { - return CaseFormatter::debugOutput($this, $delimiter); + public function qualifiedInfo(string $delimiter = ' => '): string { + return CaseFormatter::qualifiedInfo($this, $delimiter); } } diff --git a/src/Internal/CaseFormatter.php b/src/Internal/CaseFormatter.php index c0b707f..2d1980b 100644 --- a/src/Internal/CaseFormatter.php +++ b/src/Internal/CaseFormatter.php @@ -21,21 +21,21 @@ private function __construct() {} * Formats the fully qualified native enum class and case name. * * Example: - * CaseFormatter::canonicalName(Currency::JPY); // 'App\Currency::JPY' + * CaseFormatter::qualifiedName(Currency::JPY); // 'App\Currency::JPY' */ - public static function canonicalName(UnitEnum $case): string { + public static function qualifiedName(UnitEnum $case): string { return $case::class . '::' . $case->name; } /** - * Formats a pure case as its canonical name, or a backed case as its canonical name plus exported value. + * Formats a pure case as its qualified name, or a backed case as its qualified name plus exported value. * * Example: - * CaseFormatter::debugOutput(Currency::JPY); // 'App\Currency::JPY => 392' - * CaseFormatter::debugOutput(Direction::North); // 'App\Direction::North' + * CaseFormatter::qualifiedInfo(Currency::JPY); // 'App\Currency::JPY => 392' + * CaseFormatter::qualifiedInfo(Direction::North); // 'App\Direction::North' */ - public static function debugOutput(UnitEnum $case, string $delimiter = ' => '): string { - $name = self::canonicalName($case); + public static function qualifiedInfo(UnitEnum $case, string $delimiter = ' => '): string { + $name = self::qualifiedName($case); return $case instanceof BackedEnum ? $name . $delimiter . var_export($case->value, true) diff --git a/tests/ClassBased/BasicMethods/DebugOutputTest.php b/tests/ClassBased/BasicMethods/DebugOutputTest.php index add7af4..9972208 100644 --- a/tests/ClassBased/BasicMethods/DebugOutputTest.php +++ b/tests/ClassBased/BasicMethods/DebugOutputTest.php @@ -15,6 +15,19 @@ public function testDebugOutputDistinguishesFalseNullAndTheEmptyString(): void { $this->assertSame(DebugTextEnumFixture::class . "::EMPTY => ''", DebugTextEnumFixture::EMPTY()->debugOutput()); } + public function testQualifiedAliasesPreserveOriginalFormatting(): void { + $element = DebugTextEnumFixture::EMPTY(); + $this->assertSame($element->canonicalName(), $element->qualifiedName()); + $this->assertSame($element->debugOutput(' = '), $element->qualifiedInfo(' = ')); + $this->assertSame(DebugTextEnumFixture::listDebugOutput(' = '), DebugTextEnumFixture::listQualifiedInfo(' = ')); + $this->assertSame([ + DebugTextEnumFixture::class . '::TEXT', + DebugTextEnumFixture::class . '::EMPTY', + DebugTextEnumFixture::class . '::NONE', + ], DebugTextEnumFixture::qualifiedNames()); + $this->assertSame(DebugBooleanEnumFixture::OFF()->debugOutput(), DebugBooleanEnumFixture::OFF()->qualifiedInfo()); + } + public function testListDebugOutputPreservesOrderAndUsesTheRequestedDelimiter(): void { $this->assertSame([ DebugTextEnumFixture::class . "::TEXT = '0'", diff --git a/tests/ClassBased/BasicMethods/EnumLookupTest.php b/tests/ClassBased/BasicMethods/EnumLookupTest.php index eb0afbb..22f6380 100644 --- a/tests/ClassBased/BasicMethods/EnumLookupTest.php +++ b/tests/ClassBased/BasicMethods/EnumLookupTest.php @@ -86,6 +86,30 @@ public function testConstantWithAMethodNameIsAccessibleThroughOf(): void { )); } + public function testNewMappingAliasShadowsConstantShortcutButPreservesExplicitLookup(): void { + $element = AliasCollisionEnumFixture::of('NAMETOVALUE'); + + $this->assertSame('NAMETOVALUE', $element->name()); + $this->assertSame(1, $element->value()); + $this->assertSame($element, AliasCollisionEnumFixture::fromValue(1)); + $this->assertSame([ + 'NAMETOVALUE' => 1, + 'QUALIFIEDNAME' => 2, + ], AliasCollisionEnumFixture::NAMETOVALUE()); + } + + public function testNewInstanceAliasShadowsConstantShortcutButPreservesExplicitLookup(): void { + $element = AliasCollisionEnumFixture::of('QUALIFIEDNAME'); + + $this->assertSame('QUALIFIEDNAME', $element->name()); + $this->assertSame(2, $element->value()); + $this->assertSame($element, AliasCollisionEnumFixture::fromValue(2)); + $this->assertSame(AliasCollisionEnumFixture::class . '::QUALIFIEDNAME', $element->qualifiedName()); + + $this->expectException(\Error::class); + AliasCollisionEnumFixture::QUALIFIEDNAME(); + } + public function testOfRejectsUnknownNames(): void { $this->expectException(EnumDomainException::class); @@ -129,3 +153,9 @@ final class FloatLookupEnumFixture extends Enum { private const float FRACTION = 1.25; private const NONE = null; } + +final class AliasCollisionEnumFixture extends Enum { + + private const int NAMETOVALUE = 1; + private const int QUALIFIEDNAME = 2; +} diff --git a/tests/ClassBased/BasicMethods/EnumValueMapSafetyTest.php b/tests/ClassBased/BasicMethods/EnumValueMapSafetyTest.php index 7abd302..e7ef637 100644 --- a/tests/ClassBased/BasicMethods/EnumValueMapSafetyTest.php +++ b/tests/ClassBased/BasicMethods/EnumValueMapSafetyTest.php @@ -33,6 +33,30 @@ public function testPreservesExistingSafeKeyConversions(): void { ], SafeFloatMapFixture::valueToElement()); } + public function testNewMapsDelegateToHistoricalMaps(): void { + $this->assertSame(SafeBooleanMapFixture::constants(), SafeBooleanMapFixture::nameToValue()); + $this->assertSame(['ON' => true, 'OFF' => false, 'NONE' => null], SafeBooleanMapFixture::nameToValue()); + $this->assertSame(SafeBooleanMapFixture::elements(), SafeBooleanMapFixture::nameToElement()); + $this->assertSame(SafeBooleanMapFixture::elements(), SafeBooleanMapFixture::nameToCase()); + $this->assertSame(SafeBooleanMapFixture::valueToElement(), SafeBooleanMapFixture::valueToCase()); + $this->assertSame([1 => 'ON', 0 => 'OFF', '' => 'NONE'], SafeBooleanMapFixture::valueToName()); + $this->assertSame([0 => 'ZERO', '01' => 'PADDED', 'text' => 'TEXT'], SafeStringMapFixture::valueToName()); + $this->assertSame(['1.25' => 'VALUE', '1.75' => 'OTHER'], FractionalMapFixture::valueToName()); + $this->assertSame(FractionalMapFixture::valueToElement(), FractionalMapFixture::valueToCase()); + $this->assertSame(['NONE' => null, 'EMPTY' => ''], CollidingStringMapFixture::nameToValue()); + } + + #[DataProvider('newValueMapAliases')] + public function testValueMapAliasesPreserveCollisionChecks(string $method): void { + $this->expectException(EnumDomainException::class); + CollidingStringMapFixture::$method(); + } + + public static function newValueMapAliases(): iterable { + yield ['valueToCase']; + yield ['valueToName']; + } + public function testNullAndEmptyStringCollisionThrowsInsteadOfOverwriting(): void { $this->assertCount(2, CollidingStringMapFixture::elements()); $this->assertSame(null, CollidingStringMapFixture::fromValue(null)->value()); diff --git a/tests/NativeCollection/EnumCollectionTest.php b/tests/NativeCollection/EnumCollectionTest.php index b84c404..2b7f73b 100644 --- a/tests/NativeCollection/EnumCollectionTest.php +++ b/tests/NativeCollection/EnumCollectionTest.php @@ -92,10 +92,17 @@ public function testCollectionAndTraitParity(string $enum): void { $this->assertSame($enum::count(), count($collection)); $this->assertSame($enum::cases() === [], $collection->isEmpty()); $this->assertSame($enum::cases() !== [], $collection->isNotEmpty()); - $this->assertSame($enum::elements(), $this->unwrap($collection->elements())); - $this->assertSame($enum::elements(), $this->unwrap(iterator_to_array($collection))); - $this->assertSame($enum::valueToElement(), $this->unwrap($collection->valueToElement())); - $this->assertSame($enum::listDebugOutput(), $collection->listDebugOutput()); + $this->assertSame($enum::nameToCase(), $collection->nameToCase()); + $this->assertSame($enum::nameToCase(), $this->unwrap($collection->nameToElement())); + $this->assertSame($enum::valueToCase(), $collection->valueToCase()); + $this->assertSame(array_combine($enum::names(), $enum::values()), $collection->nameToValue()); + $this->assertSame($enum::nameToValue(), $collection->nameToValue()); + $this->assertSame($enum::valueToName(), $collection->valueToName()); + $this->assertSame(array_map(static fn (UnitEnum $case): string => $case::class . '::' . $case->name, $enum::cases()), $collection->qualifiedNames()); + $this->assertSame($enum::qualifiedNames(), $collection->qualifiedNames()); + $this->assertSame($enum::nameToCase(), $this->unwrap(iterator_to_array($collection))); + $this->assertSame($enum::valueToCase(), $this->unwrap($collection->valueToElement())); + $this->assertSame($enum::listQualifiedInfo(), $collection->listQualifiedInfo()); foreach ($enum::cases() as $case) { $value = EnumCase::of($case)->value(); @@ -119,8 +126,8 @@ public function testCollectionAndTraitParity(string $enum): void { $this->assertFalse($collection->hasValue('unknown')); $this->assertSame([], $collection->filter([])); $this->assertSame([], $collection->only([])); - $this->assertSame($enum::elements(), $this->unwrap($collection->reject([]))); - $this->assertSame($enum::elements(), $this->unwrap($collection->except([]))); + $this->assertSame($enum::nameToCase(), $this->unwrap($collection->reject([]))); + $this->assertSame($enum::nameToCase(), $this->unwrap($collection->except([]))); } public static function enumTypes(): iterable { @@ -193,7 +200,12 @@ public function testLazyGenerationAndMetadata(): void { $collection->values(); $collection->has('Paid'); $collection->hasValue('Paid'); - $collection->listDebugOutput(); + $collection->nameToCase(); + $collection->valueToCase(); + $collection->nameToValue(); + $collection->valueToName(); + $collection->qualifiedNames(); + $collection->listQualifiedInfo(); $this->assertNull($collection->tryFromValue('unknown')); $this->assertSame([], $generated); @@ -339,7 +351,56 @@ public function testDuplicateValueMapRejectsBeforeGeneratingWrappers(): void { } $this->expectException(LogicException::class); - DuplicateValue::valueToElement(); + DuplicateValue::valueToCase(); + } + + public function testMappingMetadataAndWrapperFactories(): void { + $calls = 0; + $collection = EnumCollection::of(StringStatus::class)->wrapCasesAs( + static function (StringStatus $case) use (&$calls): EnumCase { + ++$calls; + return EnumCase::of($case); + }, + ); + + $this->assertSame(['Zero' => '0', 'Empty' => '', 'LeadingZero' => '00'], $collection->nameToValue()); + $this->assertSame([0 => 'Zero', '' => 'Empty', '00' => 'LeadingZero'], $collection->valueToName()); + $this->assertSame(StringStatus::Zero, $collection->nameToCase()['Zero']); + $this->assertSame(StringStatus::Zero, $collection->valueToCase()[0]); + $this->assertSame(0, $calls); + + $elements = $collection->nameToElement(); + $this->assertSame(3, $calls); + $this->assertSame(StringStatus::Zero, $elements['Zero']->unwrap()); + $byValue = $collection->valueToElement(); + $this->assertSame(6, $calls); + $this->assertSame(StringStatus::Zero, $byValue[0]->unwrap()); + $this->assertNotSame($elements['Zero'], $byValue[0]); + } + + #[DataProvider('valueMapsWithDuplicateKeys')] + public function testAllValueMapsRejectDuplicateKeys(string $method): void { + $calls = 0; + $collection = EnumCollection::of(DuplicateValue::class)->wrapCasesAs( + static function (DuplicateValue $case) use (&$calls): EnumCase { + ++$calls; + return EnumCase::of($case); + }, + ); + + try { + $collection->$method(); + $this->fail('Duplicate value map was accepted'); + } catch (LogicException $exception) { + $this->assertStringContainsString('Duplicate enum value key', $exception->getMessage()); + } + $this->assertSame(0, $calls); + } + + public static function valueMapsWithDuplicateKeys(): iterable { + yield ['valueToCase']; + yield ['valueToName']; + yield ['valueToElement']; } public function testCustomCollectionRequiresExplicitFactory(): void { diff --git a/tests/NativeExtension/EnumCaseTest.php b/tests/NativeExtension/EnumCaseTest.php index 7817bb5..01421de 100644 --- a/tests/NativeExtension/EnumCaseTest.php +++ b/tests/NativeExtension/EnumCaseTest.php @@ -62,18 +62,18 @@ public function testPureCaseAndContext(): void { $this->assertTrue($ja->is(PureStatus::Paid)); $this->assertTrue($ja->isNot(PureStatus::Pending)); $this->assertFalse($ja->is(BackedStatus::Paid)); - $this->assertSame(PureStatus::class . '::Paid', $ja->canonicalName()); - $this->assertSame(PureStatus::class . '::Paid', $ja->debugOutput(' / ')); + $this->assertSame(PureStatus::class . '::Paid', $ja->qualifiedName()); + $this->assertSame(PureStatus::class . '::Paid', $ja->qualifiedInfo(' / ')); } - public function testBackedCaseAndDebugOutput(): void { + public function testBackedCaseAndQualifiedInfo(): void { $status = StatusFormatter::from(BackedStatus::Paid); $this->assertSame(BackedStatus::Paid, $status->unwrap()); $this->assertSame('paid', $status->value()); $this->assertSame('paid', (string) $status); - $this->assertSame(BackedStatus::class . "::Paid => 'paid'", $status->debugOutput()); - $this->assertSame(BackedStatus::class . "::Paid / 'paid'", $status->debugOutput(' / ')); + $this->assertSame(BackedStatus::class . "::Paid => 'paid'", $status->qualifiedInfo()); + $this->assertSame(BackedStatus::class . "::Paid / 'paid'", $status->qualifiedInfo(' / ')); $this->assertTrue($status->isNot(OtherStatus::Paid)); } @@ -109,8 +109,8 @@ public static function caseAccessOperations(): iterable { yield ['__toString', []]; yield ['is', [PureStatus::Paid]]; yield ['isNot', [PureStatus::Paid]]; - yield ['canonicalName', []]; - yield ['debugOutput', []]; + yield ['qualifiedName', []]; + yield ['qualifiedInfo', []]; } public function testComparisonRejectsUninitializedOtherExtension(): void { @@ -143,7 +143,7 @@ public function __construct(NumericStatus $case) { $this->assertSame(0, $status->value()); $this->assertSame('0', (string) $status); - $this->assertSame(NumericStatus::class . '::Zero => 0', $status->debugOutput()); + $this->assertSame(NumericStatus::class . '::Zero => 0', $status->qualifiedInfo()); } } diff --git a/tests/NativeTraits/EnumCollectionsTest.php b/tests/NativeTraits/EnumCollectionsTest.php index 2210a66..dd7dd7d 100644 --- a/tests/NativeTraits/EnumCollectionsTest.php +++ b/tests/NativeTraits/EnumCollectionsTest.php @@ -119,7 +119,7 @@ enum EnumWithOwnElements { case Pending; case Paid; - public static function elements(): array { + public static function nameToCase(): array { return ['Paid' => self::Paid]; } } @@ -145,7 +145,9 @@ public function testApplicationComparisonDoesNotChangeLibraryIsNot(): void { } public function testCollectionMethodsDoNotDelegateToApplicationOverrides(): void { - $this->assertSame(['Paid' => EnumWithOwnElements::Paid], EnumWithOwnElements::elements()); + $this->assertSame(['Paid' => EnumWithOwnElements::Paid], EnumWithOwnElements::nameToCase()); + $this->assertSame(['Pending' => 'Pending', 'Paid' => 'Paid'], EnumWithOwnElements::nameToValue()); + $this->assertSame(['Pending' => 'Pending', 'Paid' => 'Paid'], EnumWithOwnElements::valueToName()); $this->assertSame(['Paid' => EnumWithOwnIteration::Paid], iterator_to_array(EnumWithOwnIteration::iterate())); $this->assertSame([ 'Pending' => EnumWithOwnElements::Pending, @@ -217,7 +219,13 @@ public function testPureCollections(): void { 'Shipped' => PureStatus::Shipped, ]; - $this->assertSame($expected, PureStatus::elements()); + $this->assertSame($expected, PureStatus::nameToCase()); + $this->assertSame(['Pending' => 'Pending', 'Paid' => 'Paid', 'Shipped' => 'Shipped'], PureStatus::nameToValue()); + $this->assertSame(PureStatus::nameToValue(), PureStatus::valueToName()); + $this->assertSame(['Zero' => '0', 'Empty' => ''], StringStatus::nameToValue()); + $this->assertSame([0 => 'Zero', '' => 'Empty'], StringStatus::valueToName()); + $this->assertSame(['Zero' => 0, 'One' => 1, 'Two' => 2], NumericStatus::nameToValue()); + $this->assertSame([0 => 'Zero', 1 => 'One', 2 => 'Two'], NumericStatus::valueToName()); $this->assertSame(array_keys($expected), PureStatus::names()); $this->assertSame(3, PureStatus::count()); $this->assertSame(PureStatus::Paid, PureStatus::of('Paid')); @@ -237,7 +245,7 @@ public function testPureCollections(): void { $this->assertSame([], PureStatus::filter([])); $this->assertSame([], PureStatus::only([])); $this->assertSame(['Pending', 'Paid', 'Shipped'], PureStatus::values()); - $this->assertSame($expected, PureStatus::valueToElement()); + $this->assertSame($expected, PureStatus::valueToCase()); $this->assertSame(PureStatus::Paid, PureStatus::fromValue('Paid')); $this->assertSame(PureStatus::Paid, PureStatus::fromName('Paid')); $this->assertSame(PureStatus::Paid, PureStatus::tryFromName('Paid')); @@ -266,20 +274,20 @@ public function testSelectionAndExclusionShareStrictMatching(): void { foreach ([[], [new \stdClass(), 'unknown', null]] as $nonMatches) { $this->assertSame([], $enum::filter($nonMatches)); $this->assertSame([], $enum::only($nonMatches)); - $this->assertSame($enum::elements(), $enum::reject($nonMatches)); - $this->assertSame($enum::elements(), $enum::except($nonMatches)); + $this->assertSame($enum::nameToCase(), $enum::reject($nonMatches)); + $this->assertSame($enum::nameToCase(), $enum::except($nonMatches)); $this->assertSame([], iterator_to_array($enum::iterateFilter($nonMatches))); $this->assertSame([], iterator_to_array($enum::iterateOnly($nonMatches))); - $this->assertSame($enum::elements(), iterator_to_array($enum::iterateReject($nonMatches))); - $this->assertSame($enum::elements(), iterator_to_array($enum::iterateExcept($nonMatches))); + $this->assertSame($enum::nameToCase(), iterator_to_array($enum::iterateReject($nonMatches))); + $this->assertSame($enum::nameToCase(), iterator_to_array($enum::iterateExcept($nonMatches))); } - $this->assertSame($enum::elements(), $enum::filter($enum::cases())); - $this->assertSame($enum::elements(), $enum::only($enum::cases())); + $this->assertSame($enum::nameToCase(), $enum::filter($enum::cases())); + $this->assertSame($enum::nameToCase(), $enum::only($enum::cases())); $this->assertSame([], $enum::reject($enum::cases())); $this->assertSame([], $enum::except($enum::cases())); - $this->assertSame($enum::elements(), iterator_to_array($enum::iterateFilter($enum::cases()))); - $this->assertSame($enum::elements(), iterator_to_array($enum::iterateOnly($enum::cases()))); + $this->assertSame($enum::nameToCase(), iterator_to_array($enum::iterateFilter($enum::cases()))); + $this->assertSame($enum::nameToCase(), iterator_to_array($enum::iterateOnly($enum::cases()))); $this->assertSame([], iterator_to_array($enum::iterateReject($enum::cases()))); $this->assertSame([], iterator_to_array($enum::iterateExcept($enum::cases()))); } @@ -306,7 +314,7 @@ public function testApplicationMethodsDoNotReplaceCollectionMatching(): void { } public function testNumericCollectionsDoNotCoerceNonMatchingCandidates(): void { - $all = NumericStatus::elements(); + $all = NumericStatus::nameToCase(); foreach ([[false], [0.0], ['0'], [StringStatus::Zero]] as $condition) { $this->assertSame([], NumericStatus::filter($condition)); @@ -372,7 +380,7 @@ public function testBackedCollectionsUseStrictValues(): void { $this->assertSame(NumericStatus::Zero, NumericStatus::tryFromValue(0)); $this->assertNull(StringStatus::tryFromValue(0)); $this->assertSame(StringStatus::Zero, StringStatus::tryFromValue('0')); - $this->assertSame([0 => NumericStatus::Zero, 1 => NumericStatus::One, 2 => NumericStatus::Two], NumericStatus::valueToElement()); + $this->assertSame([0 => NumericStatus::Zero, 1 => NumericStatus::One, 2 => NumericStatus::Two], NumericStatus::valueToCase()); $this->assertSame(NumericStatus::Zero, NumericStatus::fromValue(0)); $this->assertTrue(NumericStatus::hasValue(0)); $this->assertFalse(NumericStatus::hasValue('0')); @@ -384,7 +392,7 @@ public function testBackedCollectionsUseStrictValues(): void { $this->assertSame(['0', ''], StringStatus::values()); $this->assertSame(StringStatus::Zero, StringStatus::fromValue('0')); $this->assertSame(StringStatus::Empty, StringStatus::fromValue('')); - $this->assertSame([0 => StringStatus::Zero, '' => StringStatus::Empty], StringStatus::valueToElement()); + $this->assertSame([0 => StringStatus::Zero, '' => StringStatus::Empty], StringStatus::valueToCase()); $this->assertFalse(StringStatus::hasValue(0)); } @@ -441,18 +449,27 @@ public function testDebugAndComparison(): void { $this->assertTrue(PureStatus::Paid->is(PureStatus::Paid)); $this->assertTrue(PureStatus::Paid->isNot(PureStatus::Pending)); $this->assertFalse(NumericStatus::Zero->is(StringStatus::Zero)); - $this->assertSame(PureStatus::class . '::Paid', PureStatus::Paid->canonicalName()); - $this->assertSame(PureStatus::class . '::Paid', PureStatus::Paid->debugOutput()); + $this->assertSame(PureStatus::class . '::Paid', PureStatus::Paid->qualifiedName()); + $this->assertSame(PureStatus::class . '::Paid', PureStatus::Paid->qualifiedInfo()); $this->assertSame([ PureStatus::class . '::Pending', PureStatus::class . '::Paid', PureStatus::class . '::Shipped', - ], PureStatus::listDebugOutput()); + ], PureStatus::listQualifiedInfo()); + $this->assertSame([ + PureStatus::class . '::Pending', + PureStatus::class . '::Paid', + PureStatus::class . '::Shipped', + ], PureStatus::qualifiedNames()); + $this->assertSame([ + StringStatus::class . '::Zero', + StringStatus::class . '::Empty', + ], StringStatus::qualifiedNames()); $this->assertSame([ StringStatus::class . "::Zero / '0'", StringStatus::class . "::Empty / ''", - ], StringStatus::listDebugOutput(' / ')); - $this->assertSame(NumericStatus::class . '::Zero => 0', NumericStatus::Zero->debugOutput()); + ], StringStatus::listQualifiedInfo(' / ')); + $this->assertSame(NumericStatus::class . '::Zero => 0', NumericStatus::Zero->qualifiedInfo()); } public function testUnknownIntegerBackingValue(): void { @@ -464,7 +481,7 @@ public function testUnknownIntegerBackingValue(): void { public function testEmptyBackedEnumCollections(): void { $this->assertSame([], EmptyBackedEnum::values()); - $this->assertSame([], EmptyBackedEnum::valueToElement()); + $this->assertSame([], EmptyBackedEnum::valueToCase()); $this->assertFalse(EmptyBackedEnum::hasValue(0)); $this->expectException(ValueError::class); @@ -472,7 +489,11 @@ public function testEmptyBackedEnumCollections(): void { } public function testEmptyEnumCollections(): void { - $this->assertSame([], EmptyEnum::elements()); + $this->assertSame([], EmptyEnum::nameToCase()); + $this->assertSame([], EmptyEnum::nameToValue()); + $this->assertSame([], EmptyEnum::valueToCase()); + $this->assertSame([], EmptyEnum::valueToName()); + $this->assertSame([], EmptyEnum::qualifiedNames()); $this->assertSame([], EmptyEnum::names()); $this->assertSame(0, EmptyEnum::count()); $this->assertFalse(EmptyEnum::has('Unknown')); @@ -491,7 +512,7 @@ public function testEmptyEnumCollections(): void { } $this->assertSame(0, $calls); } - $this->assertSame([], EmptyEnum::listDebugOutput()); + $this->assertSame([], EmptyEnum::listQualifiedInfo()); $this->expectException(ValueError::class); EmptyEnum::random();