diff --git a/README.md b/README.md index d0e5a10..57a3276 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,7 @@ final readonly class ByteUnitHex extends EnumCase { $units = EnumCollection::of(ByteUnit::class); $decimal = $units->wrapCasesAs(ByteUnitDecimal::from(...)); -$hex = $units->wrapCasesAs(ByteUnitHex::from(...)); +$hex = $units->wrapCasesAs(ByteUnitHex::from(...)); $decimal->fromName('MEBIBYTE')->format(); // '1,048,576' $hex->fromName('MEBIBYTE')->format(); // '0x100000' @@ -505,7 +505,7 @@ use Notonza\PhpEnumEx\EnumCollection; $weights = EnumCollection::of(AirmailWeight::class); -$asia = $weights->wrapCasesAs(AsiaAirmailRate::from(...)); +$asia = $weights->wrapCasesAs(AsiaAirmailRate::from(...)); $europe = $weights->wrapCasesAs(EuropeAirmailRate::from(...)); calculatePostage($asia->fromValue(25)); // 90 @@ -956,10 +956,6 @@ enum FilePermission: int { case WRITE = 1 << 1; case EXECUTE = 1 << 2; - public function isGrantedBy(int $mask): bool { - return ($mask & $this->value) === $this->value; - } - /** @return array */ public static function granted(int $mask): array { return self::filter( @@ -975,6 +971,10 @@ enum FilePermission: int { => $permission->isGrantedBy($mask), ); } + + public function isGrantedBy(int $mask): bool { + return ($mask & $this->value) === $this->value; + } } $mask = FilePermission::READ->value diff --git a/docs/coding-style.md b/docs/coding-style.md index 4f4d6b7..470ea7f 100644 --- a/docs/coding-style.md +++ b/docs/coding-style.md @@ -74,6 +74,14 @@ final readonly class CaseLabel implements Stringable { The example illustrates method placement only; public API documentation is omitted for brevity. The ordering is a default for new and revised code, not a requirement to rearrange unrelated existing methods. The placement of trait declarations, constants, properties, non-factory static methods, protected methods, private helpers, abstract methods, interface implementations, and enum cases is not yet prescribed by a complete ordering rule. Preserve meaningful existing organization for these members. Do not let a formatter determine their semantic placement. +## Aliases and Projections + +A forwarding alias exposes the same operation under another name. Keep it immediately after the original method (group multiple aliases together), even when a mechanical sort would separate them. Describe the alias and reference the original with `@see`; do not duplicate the original Example section. Retain type information, generic return shapes, exception contracts and any meaningful alias-specific notes. + +A projection transforms the result of another operation and provides a distinct contract. Document that contract and give the projection its own Example section. Keep related projections with their conceptual API family. + +The historical Class-based Enum is an exception to the placement rules: preserve the established order and implementation of existing methods. Newly added methods may be grouped at the end of the class instead of adjacent to their historical counterparts. Apply the alias and projection PHPDoc conventions to these new methods, without rewriting the historical documentation or implementations. + ## Basic Layout - Use four spaces for indentation, not tabs. diff --git a/examples/NativeExtension/Backed/ByteUnit.php b/examples/NativeExtension/Backed/ByteUnit.php index 2a06add..316e2d3 100644 --- a/examples/NativeExtension/Backed/ByteUnit.php +++ b/examples/NativeExtension/Backed/ByteUnit.php @@ -10,7 +10,6 @@ use Notonza\PhpEnumEx\EnumCollection; enum ByteUnit: int { - case BYTE = 1; case KIBIBYTE = 1 << 10; case MEBIBYTE = 1 << 20; @@ -55,7 +54,7 @@ public function format(): string { $units = EnumCollection::of(ByteUnit::class); $decimal = $units->wrapCasesAs(ByteUnitDecimal::from(...)); -$hex = $units->wrapCasesAs(ByteUnitHex::from(...)); +$hex = $units->wrapCasesAs(ByteUnitHex::from(...)); assert($decimal->fromName('MEBIBYTE')->format() === '1,048,576'); $unit = $decimal->fromName('MEBIBYTE'); diff --git a/examples/NativeExtension/Collections/FilePermission.php b/examples/NativeExtension/Collections/FilePermission.php index 0e419bc..6cb38cd 100644 --- a/examples/NativeExtension/Collections/FilePermission.php +++ b/examples/NativeExtension/Collections/FilePermission.php @@ -13,7 +13,6 @@ enum NoPermission { } enum FilePermission: int { - case READ = 1 << 0; case WRITE = 1 << 1; case EXECUTE = 1 << 2; diff --git a/examples/NativeExtension/Composite/EnumComposite.php b/examples/NativeExtension/Composite/EnumComposite.php index 7348daf..d733f5e 100644 --- a/examples/NativeExtension/Composite/EnumComposite.php +++ b/examples/NativeExtension/Composite/EnumComposite.php @@ -95,7 +95,7 @@ public function canCancel(): bool { assert($requirements->hasAll(Requirement::IdentityVerification, Requirement::AddressVerification)); $policy = new OrderStatusPolicy(OrderStatus::Paid, UserRole::Admin); -$guest = new OrderStatusPolicy(OrderStatus::Paid, UserRole::Guest); +$guest = new OrderStatusPolicy(OrderStatus::Paid, UserRole::Guest); assert($policy->canCancel()); assert(!$guest->canCancel()); diff --git a/examples/NativeExtension/Presentation/OrderStatus.php b/examples/NativeExtension/Presentation/OrderStatus.php index 8032f8f..d54b2ce 100644 --- a/examples/NativeExtension/Presentation/OrderStatus.php +++ b/examples/NativeExtension/Presentation/OrderStatus.php @@ -46,10 +46,6 @@ public function label(): string { }; } - public function __toString(): string { - return $this->label(); - } - public function color(): string { return match ($this->unwrap()) { OrderStatus::Pending => 'yellow', @@ -58,11 +54,15 @@ public function color(): string { OrderStatus::Cancelled => 'gray', }; } + + public function __toString(): string { + return $this->label(); + } } $status = OrderStatus::Paid; -$ja = new OrderStatusPresentation($status, 'ja'); -$en = new OrderStatusPresentation($status, 'en'); +$ja = new OrderStatusPresentation($status, 'ja'); +$en = new OrderStatusPresentation($status, 'en'); assert($status->canCancel()); assert($ja->label() === '支払い済み'); diff --git a/examples/NativeExtension/Strategies/AirmailPostageByEnum.php b/examples/NativeExtension/Strategies/AirmailPostageByEnum.php index eda578f..357844e 100644 --- a/examples/NativeExtension/Strategies/AirmailPostageByEnum.php +++ b/examples/NativeExtension/Strategies/AirmailPostageByEnum.php @@ -9,7 +9,6 @@ use Notonza\PhpEnumEx\EnumCollection; enum AirmailRegion { - case Asia; case Europe; case Africa; diff --git a/examples/NativeTraits/Collections/FilePermission.php b/examples/NativeTraits/Collections/FilePermission.php index 361c510..c73e758 100644 --- a/examples/NativeTraits/Collections/FilePermission.php +++ b/examples/NativeTraits/Collections/FilePermission.php @@ -9,17 +9,12 @@ use Notonza\PhpEnumEx\EnumTraits\EnumCollections; enum FilePermission: int { - use EnumCollections; case READ = 1 << 0; case WRITE = 1 << 1; case EXECUTE = 1 << 2; - public function isGrantedBy(int $mask): bool { - return ($mask & $this->value) === $this->value; - } - /** @return array */ public static function granted(int $mask): array { return self::filter( @@ -35,6 +30,10 @@ public static function denied(int $mask): array { => $permission->isGrantedBy($mask), ); } + + public function isGrantedBy(int $mask): bool { + return ($mask & $this->value) === $this->value; + } } $mask = FilePermission::READ->value diff --git a/src/ClassBased/Enum.php b/src/ClassBased/Enum.php index e47e116..302cc1c 100644 --- a/src/ClassBased/Enum.php +++ b/src/ClassBased/Enum.php @@ -192,26 +192,6 @@ 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 (===). @@ -313,26 +293,6 @@ 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. @@ -364,16 +324,6 @@ 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. * @@ -492,28 +442,6 @@ 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. @@ -740,29 +668,6 @@ 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. * @@ -910,4 +815,108 @@ private static function throwAgainstUnknownValue($value): void { } throw new EnumDomainException("Unknown Enum value in $enum: [$value]"); } + + /** + * Alias of canonicalName(). + * + * @see self::canonicalName() + */ + public final function qualifiedName(): string { + return $this->canonicalName(); + } + + /** + * Alias of debugOutput(). + * + * @see self::debugOutput() + */ + public final function qualifiedInfo(string $delimiter = ' => '): string { + return $this->debugOutput($delimiter); + } + + /** + * Returns the canonical names of all elements, in reflected constant order. + * + * Example: + * Currency::qualifiedNames(); // ['App\\Currency::JPY', 'App\\Currency::USD', 'App\\Currency::EUR'] + * + * @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(). + * + * @see self::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); + } + + /** + * Alias of constants(): constant names mapped to original scalar/null values. + * + * @see self::constants() + * @return array + * @throws RootEnumMethodCallException If called directly on the abstract root Enum. + */ + public final static function nameToValue(): array { + return static::constants(); + } + + /** + * Compatibility alias of elements(); returns class-based enum elements, not native cases. + * + * @see self::elements() + * @return array + * @throws RootEnumMethodCallException If called directly on the abstract root Enum. + */ + public final static function nameToCase(): array { + return static::elements(); + } + + /** + * Alias of elements(): constant names mapped to cached class-based enum elements. + * + * @see self::elements() + * @return array + * @throws RootEnumMethodCallException If called directly on the abstract root Enum. + */ + public final static function nameToElement(): array { + return static::elements(); + } + + /** + * Projects the existing value-to-element map to constant names, preserving its keys and checks. + * + * Example: + * Currency::valueToName(); // [392 => 'JPY', 840 => 'USD', 978 => 'EUR'] + * + * @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()); + } + + /** + * Compatibility alias of valueToElement(); returns class-based enum elements, not native cases. + * + * @see self::valueToElement() + * @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(); + } } diff --git a/src/EnumCase.php b/src/EnumCase.php index b831894..d851699 100644 --- a/src/EnumCase.php +++ b/src/EnumCase.php @@ -20,6 +20,17 @@ */ readonly class EnumCase implements Stringable { + /** + * Stores the original native case; subclasses must call this constructor before accessing case data. + * + * Example: + * // Inside a custom case wrapper's constructor: + * parent::__construct(Currency::JPY); + * + * @param TCase $case + */ + protected function __construct(private UnitEnum $case) {} + /** * Creates a new standard EnumCase wrapper around the supplied native case, not an instance of a calling subclass. * The native case is retained unchanged; repeated calls do not cache wrappers. @@ -36,65 +47,65 @@ final public static function of(UnitEnum $case): self { } /** - * Returns the stable logical value: the case name for pure enums or its int/string backing value for backed enums. + * Returns the exact original native enum case. * * Example: - * EnumCase::of(Currency::JPY)->value(); // 392 - * EnumCase::of(Direction::North)->value(); // 'North' + * EnumCase::of(Currency::JPY)->unwrap(); // Currency::JPY + * + * @return TCase + * @throws LogicException If a subclass did not call the parent constructor. */ - final public function value(): int|string { - return NativeCaseValue::of($this->unwrap()); + final public function unwrap(): UnitEnum { // @phpstan-ignore throws.unusedType (Subclasses may omit the parent constructor.) + // @phpstan-ignore isset.initializedProperty (Subclasses may omit the parent constructor.) + if (!isset($this->case)) { + throw new LogicException(static::class . ' must call parent::__construct() with a native enum case'); + } + + return $this->case; } /** - * Converts the logical value to a string by default. - * Subclasses may override this for presentation without changing value() or case identity. + * Returns the native case name, with its original spelling and case. * * Example: - * (string) EnumCase::of(Currency::JPY); // '392' - * (string) EnumCase::of(Direction::North); // 'North' + * EnumCase::of(Currency::JPY)->name(); // 'JPY' */ - public function __toString(): string { - return (string) $this->value(); + final public function name(): string { + return $this->unwrap()->name; } /** - * Stores the original native case; subclasses must call this constructor before accessing case data. + * Returns the stable logical value: the case name for pure enums or its int/string backing value for backed enums. * * Example: - * // Inside a custom case wrapper's constructor: - * parent::__construct(Currency::JPY); - * - * @param TCase $case + * EnumCase::of(Currency::JPY)->value(); // 392 + * EnumCase::of(Direction::North)->value(); // 'North' */ - protected function __construct(private UnitEnum $case) {} + final public function value(): int|string { + return NativeCaseValue::of($this->unwrap()); + } /** - * Returns the exact original native enum case. + * Returns the original native enum's fully qualified class name followed by :: and the case name. * * Example: - * EnumCase::of(Currency::JPY)->unwrap(); // Currency::JPY - * - * @return TCase - * @throws LogicException If a subclass did not call the parent constructor. + * EnumCase::of(Currency::JPY)->qualifiedName(); // 'App\Currency::JPY' */ - final public function unwrap(): UnitEnum { // @phpstan-ignore throws.unusedType (Subclasses may omit the parent constructor.) - // @phpstan-ignore isset.initializedProperty (Subclasses may omit the parent constructor.) - if (!isset($this->case)) { - throw new LogicException(static::class . ' must call parent::__construct() with a native enum case'); - } - - return $this->case; + final public function qualifiedName(): string { + return CaseFormatter::qualifiedName($this->unwrap()); } /** - * Returns the native case name, with its original spelling and case. + * Returns the qualified name and, for backed enums, the exported backing value. * * Example: - * EnumCase::of(Currency::JPY)->name(); // 'JPY' + * EnumCase::of(Currency::JPY)->qualifiedInfo(); // 'App\Currency::JPY => 392' + * EnumCase::of(Direction::North)->qualifiedInfo(); // 'App\Direction::North' + * + * @param string $delimiter Separator between the qualified name and backing value. */ - final public function name(): string { - return $this->unwrap()->name; + final public function qualifiedInfo(string $delimiter = ' => '): string { + return CaseFormatter::qualifiedInfo($this->unwrap(), $delimiter); } /** @@ -125,25 +136,14 @@ 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)->qualifiedName(); // 'App\Currency::JPY' - */ - final public function qualifiedName(): string { - return CaseFormatter::qualifiedName($this->unwrap()); - } - - /** - * Returns the qualified name and, for backed enums, the exported backing value. + * Converts the logical value to a string by default. + * Subclasses may override this for presentation without changing value() or case identity. * * Example: - * EnumCase::of(Currency::JPY)->qualifiedInfo(); // 'App\Currency::JPY => 392' - * EnumCase::of(Direction::North)->qualifiedInfo(); // 'App\Direction::North' - * - * @param string $delimiter Separator between the qualified name and backing value. + * (string) EnumCase::of(Currency::JPY); // '392' + * (string) EnumCase::of(Direction::North); // 'North' */ - final public function qualifiedInfo(string $delimiter = ' => '): string { - return CaseFormatter::qualifiedInfo($this->unwrap(), $delimiter); + public function __toString(): string { + return (string) $this->value(); } } diff --git a/src/EnumCollection.php b/src/EnumCollection.php index 13f330e..312dbc1 100644 --- a/src/EnumCollection.php +++ b/src/EnumCollection.php @@ -151,186 +151,187 @@ private function validateWrapper(mixed $wrapped, UnitEnum $case): void { } /** - * Creates wrappers for all declared cases, keyed by case name in declaration order. + * Returns a factory-created wrapper for the case with the exact, case-sensitive name. + * Factory exceptions propagate unchanged. * * Example: - * $currencies->nameToElement(); - * // ['JPY' => EnumCase::of(Currency::JPY), 'USD' => EnumCase::of(Currency::USD), - * // 'EUR' => EnumCase::of(Currency::EUR)] + * $currencies->fromName('JPY'); // EnumCase wrapping Currency::JPY + * $currencies->fromName('GBP'); // throws ValueError * - * @return array + * @return TElement + * @throws \TypeError If the name is not a string. + * @throws ValueError If no case has that name. */ - final public function nameToElement(): array { - return iterator_to_array($this->iterate()); + final public function fromName(mixed $name): EnumCase { + return $this->tryFromName($name) + ?? throw new ValueError('Unknown enum case: ' . $this->enumClass() . '::' . $name); } /** - * Returns native cases keyed by their exact names, in declaration order. - * Does not invoke the wrapper factory. + * Returns a factory-created wrapper for the exact case name, or null if no case matches. + * No wrapper is created on a miss; factory exceptions are not caught. * * Example: - * $currencies->nameToCase(); // ['JPY' => Currency::JPY, 'USD' => Currency::USD, 'EUR' => Currency::EUR] + * $currencies->tryFromName('USD'); // EnumCase wrapping Currency::USD + * $currencies->tryFromName('GBP'); // null * - * @return array + * @return TElement|null + * @throws \TypeError If the name is not a string. */ - final public function nameToCase(): array { - return NativeCaseLookup::mapByName($this->cases()); + final public function tryFromName(mixed $name): ?EnumCase { + $case = NativeCaseLookup::byName($this->cases(), $name); + + return $case === null ? null : $this->wrap($case); } /** - * Returns the declared case names in declaration order. - * Does not invoke the wrapper factory. + * Returns a factory-created wrapper for the case with the exact logical value, without scalar coercion. + * Factory exceptions propagate unchanged. * * Example: - * $currencies->names(); // ['JPY', 'USD', 'EUR'] + * $currencies->fromValue(392)->unwrap(); // Currency::JPY + * $currencies->fromValue('392'); // throws ValueError * - * @return list + * @return TElement + * @throws \TypeError If the value is neither int nor string. + * @throws ValueError If no case has that exact value. */ - final public function names(): array { - return array_map(static fn (UnitEnum $case): string => $case->name, $this->cases()); + final public function fromValue(mixed $value): EnumCase { + return $this->tryFromValue($value) + ?? throw new ValueError('Unknown enum value for ' . $this->enumClass() . ': ' . var_export($value, true)); } /** - * Returns the number of declared cases, including zero for an empty enum. - * Does not invoke the wrapper factory. + * Returns a factory-created wrapper for the exact logical value, or null if no case matches. + * No wrapper is created on a miss; factory exceptions are not caught. * * Example: - * $currencies->count(); // 3 - * count($currencies); // 3 - */ - final public function count(): int { - return count($this->cases()); - } - - /** - * Returns true when the native enum declares no cases. - * Does not invoke the wrapper factory. + * $currencies->tryFromValue(840); // EnumCase wrapping Currency::USD + * $currencies->tryFromValue('840'); // null + * $currencies->tryFromValue(false); // throws TypeError * - * Example: - * $currencies->isEmpty(); // false - * EnumCollection::of(EmptyEnum::class)->isEmpty(); // true + * @return TElement|null + * @throws \TypeError If the value is neither int nor string. */ - final public function isEmpty(): bool { - return $this->cases() === []; + final public function tryFromValue(mixed $value): ?EnumCase { + $case = NativeCaseLookup::byValue($this->cases(), $value); + + return $case === null ? null : $this->wrap($case); } /** - * Returns true when the native enum declares at least one case. - * Does not invoke the wrapper factory. + * Randomly selects a declared native case and creates a wrapper for it. * * Example: - * $currencies->isNotEmpty(); // true - * EnumCollection::of(EmptyEnum::class)->isNotEmpty(); // false + * $currencies->random(); // e.g. EnumCase wrapping Currency::USD + * + * @return TElement + * @throws ValueError If the enum has no cases. */ - final public function isNotEmpty(): bool { - return !$this->isEmpty(); + final public function random(): EnumCase { + $cases = $this->cases(); + + return $this->wrap($cases[array_rand($cases)]); } /** - * Checks whether the exact case name exists. Non-string inputs return false without coercion. + * Returns the declared case names in declaration order. * Does not invoke the wrapper factory. * * Example: - * $currencies->has('JPY'); // true - * $currencies->has(392); // false + * $currencies->names(); // ['JPY', 'USD', 'EUR'] + * + * @return list */ - final public function has(mixed $name): bool { - return NativeCaseLookup::hasName($this->cases(), $name); + final public function names(): array { + return array_map(static fn (UnitEnum $case): string => $case->name, $this->cases()); } /** - * Returns a factory-created wrapper for the case with the exact, case-sensitive name. - * Factory exceptions propagate unchanged. + * Returns logical values in declaration order: case names for pure enums, backing values for backed enums. + * Does not invoke the wrapper factory. * * Example: - * $currencies->fromName('JPY'); // EnumCase wrapping Currency::JPY - * $currencies->fromName('GBP'); // throws ValueError + * $currencies->values(); // [392, 840, 978] + * EnumCollection::of(Direction::class)->values(); // ['North', 'South'] * - * @return TElement - * @throws \TypeError If the name is not a string. - * @throws ValueError If no case has that name. + * @return list */ - final public function fromName(mixed $name): EnumCase { - return $this->tryFromName($name) - ?? throw new ValueError('Unknown enum case: ' . $this->enumClass() . '::' . $name); + final public function values(): array { + return array_map(NativeCaseValue::of(...), $this->cases()); } /** - * Returns a factory-created wrapper for the exact case name, or null if no case matches. - * No wrapper is created on a miss; factory exceptions are not caught. + * Returns the number of declared cases, including zero for an empty enum. + * Does not invoke the wrapper factory. * * Example: - * $currencies->tryFromName('USD'); // EnumCase wrapping Currency::USD - * $currencies->tryFromName('GBP'); // null - * - * @return TElement|null - * @throws \TypeError If the name is not a string. + * $currencies->count(); // 3 + * count($currencies); // 3 */ - final public function tryFromName(mixed $name): ?EnumCase { - $case = NativeCaseLookup::byName($this->cases(), $name); - - return $case === null ? null : $this->wrap($case); + final public function count(): int { + return count($this->cases()); } /** - * Returns logical values in declaration order: case names for pure enums, backing values for backed enums. + * Returns the fully qualified enum class and case names in declaration order. * Does not invoke the wrapper factory. * * Example: - * $currencies->values(); // [392, 840, 978] - * EnumCollection::of(Direction::class)->values(); // ['North', 'South'] + * $currencies->qualifiedNames(); + * // ['App\\Currency::JPY', 'App\\Currency::USD', 'App\\Currency::EUR'] * - * @return list + * @return list */ - final public function values(): array { - return array_map(NativeCaseValue::of(...), $this->cases()); + final public function qualifiedNames(): array { + return array_map(CaseFormatter::qualifiedName(...), $this->cases()); } /** - * Checks whether an exact logical value exists. Non-int/string inputs return false; no coercion is performed. + * 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->hasValue(392); // true - * $currencies->hasValue('392'); // false + * $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 hasValue(mixed $value): bool { - return NativeCaseLookup::hasValue($this->cases(), $value); + final public function listQualifiedInfo(string $delimiter = ' => '): array { + return array_map( + static fn (UnitEnum $case): string => CaseFormatter::qualifiedInfo($case, $delimiter), + $this->cases(), + ); } /** - * Returns a factory-created wrapper for the case with the exact logical value, without scalar coercion. - * Factory exceptions propagate unchanged. + * Returns native cases keyed by their exact names, in declaration order. + * Does not invoke the wrapper factory. * * Example: - * $currencies->fromValue(392)->unwrap(); // Currency::JPY - * $currencies->fromValue('392'); // throws ValueError + * $currencies->nameToCase(); // ['JPY' => Currency::JPY, 'USD' => Currency::USD, 'EUR' => Currency::EUR] * - * @return TElement - * @throws \TypeError If the value is neither int nor string. - * @throws ValueError If no case has that exact value. + * @return array */ - final public function fromValue(mixed $value): EnumCase { - return $this->tryFromValue($value) - ?? throw new ValueError('Unknown enum value for ' . $this->enumClass() . ': ' . var_export($value, true)); + final public function nameToCase(): array { + return NativeCaseLookup::mapByName($this->cases()); } /** - * Returns a factory-created wrapper for the exact logical value, or null if no case matches. - * No wrapper is created on a miss; factory exceptions are not caught. + * Creates wrappers for all declared cases, keyed by case name in declaration order. * * Example: - * $currencies->tryFromValue(840); // EnumCase wrapping Currency::USD - * $currencies->tryFromValue('840'); // null - * $currencies->tryFromValue(false); // throws TypeError + * $currencies->nameToElement(); + * // ['JPY' => EnumCase::of(Currency::JPY), 'USD' => EnumCase::of(Currency::USD), + * // 'EUR' => EnumCase::of(Currency::EUR)] * - * @return TElement|null - * @throws \TypeError If the value is neither int nor string. + * @return array */ - final public function tryFromValue(mixed $value): ?EnumCase { - $case = NativeCaseLookup::byValue($this->cases(), $value); - - return $case === null ? null : $this->wrap($case); + final public function nameToElement(): array { + return iterator_to_array($this->iterate()); } /** @@ -347,24 +348,6 @@ 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. @@ -402,6 +385,24 @@ final public function valueToElement(): array { return $elements; } + /** + * 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 wrappers for matching cases, keyed by case name in declaration order. * A closure receives one wrapper per evaluated case; array selectors match native case identity (including the case inside a wrapper) or exact logical value. @@ -575,51 +576,50 @@ private function iterateCondition(Closure|array $condition, bool $negate): Gener } /** - * Randomly selects a declared native case and creates a wrapper for it. + * Returns true when the native enum declares no cases. + * Does not invoke the wrapper factory. * * Example: - * $currencies->random(); // e.g. EnumCase wrapping Currency::USD - * - * @return TElement - * @throws ValueError If the enum has no cases. + * $currencies->isEmpty(); // false + * EnumCollection::of(EmptyEnum::class)->isEmpty(); // true */ - final public function random(): EnumCase { - $cases = $this->cases(); - - return $this->wrap($cases[array_rand($cases)]); + final public function isEmpty(): bool { + return $this->cases() === []; } /** - * Returns the fully qualified enum class and case names in declaration order. + * Returns true when the native enum declares at least one case. * Does not invoke the wrapper factory. * * Example: - * $currencies->qualifiedNames(); - * // ['App\\Currency::JPY', 'App\\Currency::USD', 'App\\Currency::EUR'] - * - * @return list + * $currencies->isNotEmpty(); // true + * EnumCollection::of(EmptyEnum::class)->isNotEmpty(); // false */ - final public function qualifiedNames(): array { - return array_map(CaseFormatter::qualifiedName(...), $this->cases()); + final public function isNotEmpty(): bool { + return !$this->isEmpty(); } /** - * 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. + * Checks whether the exact case name exists. Non-string inputs return false without coercion. * Does not invoke the wrapper factory. * * Example: - * $currencies->listQualifiedInfo(); - * // ['App\Currency::JPY => 392', 'App\Currency::USD => 840', - * // 'App\Currency::EUR => 978'] + * $currencies->has('JPY'); // true + * $currencies->has(392); // false + */ + final public function has(mixed $name): bool { + return NativeCaseLookup::hasName($this->cases(), $name); + } + + /** + * Checks whether an exact logical value exists. Non-int/string inputs return false; no coercion is performed. + * Does not invoke the wrapper factory. * - * @return list - * @param string $delimiter Separator between a backed case name and its value. + * Example: + * $currencies->hasValue(392); // true + * $currencies->hasValue('392'); // false */ - final public function listQualifiedInfo(string $delimiter = ' => '): array { - return array_map( - static fn (UnitEnum $case): string => CaseFormatter::qualifiedInfo($case, $delimiter), - $this->cases(), - ); + final public function hasValue(mixed $value): bool { + return NativeCaseLookup::hasValue($this->cases(), $value); } } diff --git a/src/EnumComposite.php b/src/EnumComposite.php index b8f9e0a..1125cd9 100644 --- a/src/EnumComposite.php +++ b/src/EnumComposite.php @@ -127,6 +127,22 @@ final public function unwrap(): array { return $this->cases; } + /** + * Returns the retained native case at the given zero-based index. + * + * Example: + * $route->at(0); // Country::Japan + * $route->at(1); // Country::France + * $route->at(3); // throws OutOfBoundsException + * + * @throws OutOfBoundsException If the zero-based index does not exist. + */ + final public function at(int $index): UnitEnum { + $cases = $this->unwrap(); + + return $cases[$index] ?? throw new OutOfBoundsException('No native enum case at index ' . $index); + } + /** * Returns the comparison policy; it does not change the iteration order. * @@ -153,28 +169,6 @@ final public function count(): int { return count($this->unwrap()); } - /** - * Returns true when the composite contains no cases. - * - * Example: - * $route->isEmpty(); // false - * EnumComposite::of()->isEmpty(); // true - */ - final public function isEmpty(): bool { - return $this->unwrap() === []; - } - - /** - * Returns true when the composite contains at least one case. - * - * Example: - * $route->isNotEmpty(); // true - * EnumComposite::of()->isNotEmpty(); // false - */ - final public function isNotEmpty(): bool { - return !$this->isEmpty(); - } - /** * Iterates over the retained native cases with zero-based integer keys, in input order. * Changes to the returned iterator do not change the composite. @@ -193,22 +187,6 @@ final public function getIterator(): ArrayIterator { return new ArrayIterator($this->unwrap()); } - /** - * Returns the retained native case at the given zero-based index. - * - * Example: - * $route->at(0); // Country::Japan - * $route->at(1); // Country::France - * $route->at(3); // throws OutOfBoundsException - * - * @throws OutOfBoundsException If the zero-based index does not exist. - */ - final public function at(int $index): UnitEnum { - $cases = $this->unwrap(); - - return $cases[$index] ?? throw new OutOfBoundsException('No native enum case at index ' . $index); - } - /** * Checks whether the exact native case occurs at least once. * @@ -262,6 +240,28 @@ final public function hasAny(UnitEnum ...$cases): bool { return false; } + /** + * Returns true when the composite contains no cases. + * + * Example: + * $route->isEmpty(); // false + * EnumComposite::of()->isEmpty(); // true + */ + final public function isEmpty(): bool { + return $this->unwrap() === []; + } + + /** + * Returns true when the composite contains at least one case. + * + * Example: + * $route->isNotEmpty(); // true + * EnumComposite::of()->isNotEmpty(); // false + */ + final public function isNotEmpty(): bool { + return !$this->isEmpty(); + } + /** * Compares the retained sequence, including order and multiplicity, independently of policy. * @@ -315,6 +315,23 @@ final public function equals(self $other): bool { }; } + /** + * Enum cases are singleton objects. Their object IDs are unique while the input cases are alive. + * + * @param array $cases + * @return array + */ + private static function frequencies(array $cases): array { + $counts = []; + + foreach ($cases as $case) { + $id = spl_object_id($case); + $counts[$id] = ($counts[$id] ?? 0) + 1; + } + + return $counts; + } + /** * Native PHP object serialization is not supported yet. * The inherited magic hooks reject serialization and object-format restoration. @@ -336,6 +353,9 @@ final public function __serialize(): array { * Rejects native PHP object-format restoration, which would bypass the construction contract. * Legacy Serializable restoration is outside the supported contract. * + * Example: + * $route->__unserialize([]); // throws LogicException + * * @param array $data * @throws LogicException Always. */ @@ -344,21 +364,4 @@ final public function __unserialize(array $data): void { 'Deserialization of EnumComposite is not supported YET', ); } - - /** - * Enum cases are singleton objects. Their object IDs are unique while the input cases are alive. - * - * @param array $cases - * @return array - */ - private static function frequencies(array $cases): array { - $counts = []; - - foreach ($cases as $case) { - $id = spl_object_id($case); - $counts[$id] = ($counts[$id] ?? 0) + 1; - } - - return $counts; - } } diff --git a/src/EnumCompositeBuilder.php b/src/EnumCompositeBuilder.php index 095e7ab..999ccb2 100644 --- a/src/EnumCompositeBuilder.php +++ b/src/EnumCompositeBuilder.php @@ -20,7 +20,9 @@ public function __construct(private Closure $factory) {} * Creates a standard composite using the selected policies. * The same factory can create multiple independent composites. * - * Example (with App\Country::Japan and App\Country::France): + * The following example assumes App\Country::Japan and App\Country::France. + * + * Example: * $factory = EnumComposite::as( * CompositeOrder::Insensitive, * CompositeDuplicates::Remove, diff --git a/src/EnumTraits/EnumCollections.php b/src/EnumTraits/EnumCollections.php index 2488eef..7968793 100644 --- a/src/EnumTraits/EnumCollections.php +++ b/src/EnumTraits/EnumCollections.php @@ -25,93 +25,103 @@ trait EnumCollections { /** - * Returns every declared case, keyed by its exact case name, in declaration order. + * Returns the native case with the exact name, equivalent to the library's fromName() lookup. + * Does not delegate to application-defined overrides of fromName() or tryFromName(). * * Example: - * Currency::nameToCase(); - * // ['JPY' => Currency::JPY, 'USD' => Currency::USD, 'EUR' => Currency::EUR] + * Currency::of('JPY'); // Currency::JPY + * Currency::of('GBP'); // throws ValueError * - * @return array + * @throws \TypeError If the name is not a string. + * @throws ValueError If no case has that name. */ - public static function nameToCase(): array { - return NativeCaseLookup::mapByName(static::cases()); + public static function of(mixed $name): static { + return NativeCaseLookup::byName(static::cases(), $name) + ?? throw new ValueError('Unknown enum case: ' . static::class . '::' . $name); } /** - * Returns the declared case names in declaration order. + * Looks up a case by its exact, case-sensitive name without coercing the input. * * Example: - * Currency::names(); // ['JPY', 'USD', 'EUR'] + * Currency::fromName('JPY'); // Currency::JPY + * Currency::fromName(392); // throws TypeError * - * @return list + * @throws \TypeError If the name is not a string. + * @throws ValueError If no case has that name. */ - public static function names(): array { - return array_map(static fn (UnitEnum $case): string => $case->name, static::cases()); + public static function fromName(mixed $name): static { + return NativeCaseLookup::byName(static::cases(), $name) + ?? throw new ValueError('Unknown enum case: ' . static::class . '::' . $name); } /** - * Returns the number of declared cases, including zero for an empty enum. + * Looks up a case by its exact name, returning null if no case matches. * * Example: - * Currency::count(); // 3 + * Currency::tryFromName('USD'); // Currency::USD + * Currency::tryFromName('GBP'); // null + * + * @throws \TypeError If the name is not a string. */ - public static function count(): int { - return count(static::cases()); + public static function tryFromName(mixed $name): ?static { + return NativeCaseLookup::byName(static::cases(), $name); } /** - * Checks whether the exact case name exists. Non-string inputs return false without coercion. + * Looks up a case by its logical value using strict comparison, without scalar coercion. * * Example: - * Currency::has('JPY'); // true - * Currency::has('jpy'); // false + * Currency::fromValue(392); // Currency::JPY + * Currency::fromValue('392'); // throws ValueError + * Direction::fromValue('North'); // Direction::North + * + * @throws \TypeError If the value is neither int nor string. + * @throws ValueError If no case has that exact value. */ - public static function has(mixed $name): bool { - return NativeCaseLookup::hasName(static::cases(), $name); + public static function fromValue(mixed $value): static { + return NativeCaseLookup::byValue(static::cases(), $value) + ?? throw new ValueError('Unknown enum value for ' . static::class . ': ' . var_export($value, true)); } /** - * Returns the native case with the exact name, equivalent to the library's fromName() lookup. - * Does not delegate to application-defined overrides of fromName() or tryFromName(). + * Looks up a case by its exact logical value, returning null if no case matches. * * Example: - * Currency::of('JPY'); // Currency::JPY - * Currency::of('GBP'); // throws ValueError + * Currency::tryFromValue(840); // Currency::USD + * Currency::tryFromValue('840'); // null + * Currency::tryFromValue(false); // throws TypeError * - * @throws \TypeError If the name is not a string. - * @throws ValueError If no case has that name. + * @throws \TypeError If the value is neither int nor string. */ - public static function of(mixed $name): static { - return NativeCaseLookup::byName(static::cases(), $name) - ?? throw new ValueError('Unknown enum case: ' . static::class . '::' . $name); + public static function tryFromValue(mixed $value): ?static { + return NativeCaseLookup::byValue(static::cases(), $value); } /** - * Looks up a case by its exact, case-sensitive name without coercing the input. + * Returns a randomly selected case from the declared cases. * * Example: - * Currency::fromName('JPY'); // Currency::JPY - * Currency::fromName(392); // throws TypeError + * Currency::random(); // e.g. Currency::USD * - * @throws \TypeError If the name is not a string. - * @throws ValueError If no case has that name. + * @throws ValueError If the enum has no cases. */ - public static function fromName(mixed $name): static { - return NativeCaseLookup::byName(static::cases(), $name) - ?? throw new ValueError('Unknown enum case: ' . static::class . '::' . $name); + public static function random(): static { + $cases = static::cases(); + + return $cases[array_rand($cases)]; } /** - * Looks up a case by its exact name, returning null if no case matches. + * Returns the declared case names in declaration order. * * Example: - * Currency::tryFromName('USD'); // Currency::USD - * Currency::tryFromName('GBP'); // null + * Currency::names(); // ['JPY', 'USD', 'EUR'] * - * @throws \TypeError If the name is not a string. + * @return list */ - public static function tryFromName(mixed $name): ?static { - return NativeCaseLookup::byName(static::cases(), $name); + public static function names(): array { + return array_map(static fn (UnitEnum $case): string => $case->name, static::cases()); } /** @@ -128,75 +138,71 @@ public static function values(): array { } /** - * Checks whether an exact logical value exists. Non-int/string inputs return false; no coercion is performed. + * Returns the number of declared cases, including zero for an empty enum. * * Example: - * Currency::hasValue(392); // true - * Currency::hasValue('392'); // false - * Direction::hasValue('North'); // true + * Currency::count(); // 3 */ - public static function hasValue(mixed $value): bool { - return NativeCaseLookup::hasValue(static::cases(), $value); + public static function count(): int { + return count(static::cases()); } /** - * Looks up a case by its logical value using strict comparison, without scalar coercion. + * Returns the fully qualified enum class and case names in declaration order. * * Example: - * Currency::fromValue(392); // Currency::JPY - * Currency::fromValue('392'); // throws ValueError - * Direction::fromValue('North'); // Direction::North + * Currency::qualifiedNames(); + * // ['App\\Currency::JPY', 'App\\Currency::USD', 'App\\Currency::EUR'] * - * @throws \TypeError If the value is neither int nor string. - * @throws ValueError If no case has that exact value. + * @return list */ - public static function fromValue(mixed $value): static { - return NativeCaseLookup::byValue(static::cases(), $value) - ?? throw new ValueError('Unknown enum value for ' . static::class . ': ' . var_export($value, true)); + public static function qualifiedNames(): array { + return array_map(CaseFormatter::qualifiedName(...), static::cases()); } /** - * Looks up a case by its exact logical value, returning null if no case matches. + * 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::tryFromValue(840); // Currency::USD - * Currency::tryFromValue('840'); // null - * Currency::tryFromValue(false); // throws TypeError + * Currency::listQualifiedInfo(); + * // ['App\Currency::JPY => 392', 'App\Currency::USD => 840', + * // 'App\Currency::EUR => 978'] * - * @throws \TypeError If the value is neither int nor string. + * @return list + * @param string $delimiter Separator between a backed case name and its value. */ - public static function tryFromValue(mixed $value): ?static { - return NativeCaseLookup::byValue(static::cases(), $value); + public static function listQualifiedInfo(string $delimiter = ' => '): array { + return array_map( + static fn (UnitEnum $case): string => CaseFormatter::qualifiedInfo($case, $delimiter), + static::cases(), + ); } /** - * Returns logical values keyed by case name, in declaration order. - * Pure cases use their names; backed cases use their original backing values. + * Returns every declared case, keyed by its exact case name, in declaration order. * * Example: - * Currency::nameToValue(); // ['JPY' => 392, 'USD' => 840, 'EUR' => 978] + * Currency::nameToCase(); + * // ['JPY' => Currency::JPY, 'USD' => Currency::USD, 'EUR' => Currency::EUR] * - * @return array + * @return array */ - public static function nameToValue(): array { - return array_map(NativeCaseValue::of(...), NativeCaseLookup::mapByName(static::cases())); + public static function nameToCase(): array { + return NativeCaseLookup::mapByName(static::cases()); } /** - * Returns case names keyed by logical value, in declaration order. - * Uses PHP array-key conversion and rejects duplicate keys. + * Returns logical values keyed by case name, in declaration order. + * Pure cases use their names; backed cases use their original backing values. * * Example: - * Currency::valueToName(); // [392 => 'JPY', 840 => 'USD', 978 => 'EUR'] + * Currency::nameToValue(); // ['JPY' => 392, 'USD' => 840, 'EUR' => 978] * - * @return array - * @throws \LogicException If two cases produce the same array key. + * @return array */ - public static function valueToName(): array { - return array_map( - static fn (UnitEnum $case): string => $case->name, - NativeCaseValue::map(static::cases()), - ); + public static function nameToValue(): array { + return array_map(NativeCaseValue::of(...), NativeCaseLookup::mapByName(static::cases())); } /** @@ -216,6 +222,23 @@ public static function valueToCase(): array { return NativeCaseValue::map(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 matching cases with their original name keys and declaration order. * A closure receives each case; an array matches native case identity (including wrappers) or an exact logical value. @@ -380,48 +403,25 @@ public static function iterateExcept(array $targets): Generator { } /** - * Returns a randomly selected case from the declared cases. - * - * Example: - * Currency::random(); // e.g. Currency::USD - * - * @throws ValueError If the enum has no cases. - */ - public static function random(): static { - $cases = static::cases(); - - return $cases[array_rand($cases)]; - } - - /** - * Returns the fully qualified enum class and case names in declaration order. + * Checks whether the exact case name exists. Non-string inputs return false without coercion. * * Example: - * Currency::qualifiedNames(); - * // ['App\\Currency::JPY', 'App\\Currency::USD', 'App\\Currency::EUR'] - * - * @return list + * Currency::has('JPY'); // true + * Currency::has('jpy'); // false */ - public static function qualifiedNames(): array { - return array_map(CaseFormatter::qualifiedName(...), static::cases()); + public static function has(mixed $name): bool { + return NativeCaseLookup::hasName(static::cases(), $name); } /** - * 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. + * Checks whether an exact logical value exists. Non-int/string inputs return false; no coercion is performed. * * Example: - * 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. + * Currency::hasValue(392); // true + * Currency::hasValue('392'); // false + * Direction::hasValue('North'); // true */ - public static function listQualifiedInfo(string $delimiter = ' => '): array { - return array_map( - static fn (UnitEnum $case): string => CaseFormatter::qualifiedInfo($case, $delimiter), - static::cases(), - ); + public static function hasValue(mixed $value): bool { + return NativeCaseLookup::hasValue(static::cases(), $value); } } diff --git a/src/EnumTraits/EnumMethods.php b/src/EnumTraits/EnumMethods.php index 709fb5f..a25690b 100644 --- a/src/EnumTraits/EnumMethods.php +++ b/src/EnumTraits/EnumMethods.php @@ -28,28 +28,6 @@ public function value(): int|string { return NativeCaseValue::of($this); } - /** - * Checks whether the other native enum case is the exact same case instance. - * - * Example: - * Currency::JPY->is(Currency::JPY); // true - * Currency::JPY->is(Currency::USD); // false - */ - public function is(UnitEnum $other): bool { - return $this === $other; - } - - /** - * Checks whether the other native enum case is a different case instance. - * - * Example: - * Currency::JPY->isNot(Currency::USD); // true - * Currency::JPY->isNot(Currency::JPY); // false - */ - public function isNot(UnitEnum $other): bool { - return $this !== $other; - } - /** * Returns the enum's fully qualified class name followed by :: and the case name. * @@ -73,4 +51,26 @@ public function qualifiedName(): string { public function qualifiedInfo(string $delimiter = ' => '): string { return CaseFormatter::qualifiedInfo($this, $delimiter); } + + /** + * Checks whether the other native enum case is the exact same case instance. + * + * Example: + * Currency::JPY->is(Currency::JPY); // true + * Currency::JPY->is(Currency::USD); // false + */ + public function is(UnitEnum $other): bool { + return $this === $other; + } + + /** + * Checks whether the other native enum case is a different case instance. + * + * Example: + * Currency::JPY->isNot(Currency::USD); // true + * Currency::JPY->isNot(Currency::JPY); // false + */ + public function isNot(UnitEnum $other): bool { + return $this !== $other; + } } diff --git a/src/Internal/NativeCaseValue.php b/src/Internal/NativeCaseValue.php index 91da9c7..df5d1ff 100644 --- a/src/Internal/NativeCaseValue.php +++ b/src/Internal/NativeCaseValue.php @@ -28,6 +28,7 @@ private function __construct() {} public static function of(UnitEnum $case): int|string { return $case instanceof BackedEnum ? $case->value : $case->name; } + /** * Maps logical values to native cases in the supplied order. * PHP converts integer-like string array keys to integers. diff --git a/tests/NativeCollection/EnumCollectionTest.php b/tests/NativeCollection/EnumCollectionTest.php index 2b7f73b..44aa9da 100644 --- a/tests/NativeCollection/EnumCollectionTest.php +++ b/tests/NativeCollection/EnumCollectionTest.php @@ -27,14 +27,14 @@ enum NumericStatus: int { use EnumCollections; case Zero = 0; - case One = 1; + case One = 1; } enum StringStatus: string { use EnumCollections; - case Zero = '0'; - case Empty = ''; + case Zero = '0'; + case Empty = ''; case LeadingZero = '00'; } @@ -46,7 +46,7 @@ enum OtherStatus { enum DuplicateValue: string { use EnumCollections; - case First = '0'; + case First = '0'; case Second = '0'; } diff --git a/tests/NativeTraits/EnumCollectionsTest.php b/tests/NativeTraits/EnumCollectionsTest.php index dd7dd7d..766b4be 100644 --- a/tests/NativeTraits/EnumCollectionsTest.php +++ b/tests/NativeTraits/EnumCollectionsTest.php @@ -69,14 +69,14 @@ enum EnumWithTraitCollectionPredicate: string { use ApplicationCollectionPredicate; case Pending = 'pending'; - case Paid = 'paid'; + case Paid = 'paid'; } enum EnumWithOwnLookup: int { use EnumCollections; case Pending = 0; - case Paid = 1; + case Paid = 1; public static function tryFromValue(mixed $value): ?self { return self::Paid; @@ -95,7 +95,7 @@ enum EnumWithOwnTryLookup: int { use EnumCollections; case Pending = 0; - case Paid = 1; + case Paid = 1; public static function tryFromName(mixed $name): ?self { return self::Paid;