From 2c1ff6d5da130e94e021c403c30ba1ae7bc15150 Mon Sep 17 00:00:00 2001 From: Kangin Kim Date: Thu, 3 Dec 2026 02:11:31 +0900 Subject: [PATCH 01/13] Implement initial EnumComposite with independent construction policies --- docs/adr/0010-composite-enum-cases.md | 15 +- .../Composite/EnumComposite.php | 112 +++++++++ src/CompositeDuplicates.php | 12 + src/CompositeOrder.php | 11 + src/EnumComposite.php | 189 +++++++++++++++ src/EnumCompositeBuilder.php | 23 ++ tests/NativeExtension/EnumCompositeTest.php | 219 ++++++++++++++++++ 7 files changed, 580 insertions(+), 1 deletion(-) create mode 100644 examples/NativeExtension/Composite/EnumComposite.php create mode 100644 src/CompositeDuplicates.php create mode 100644 src/CompositeOrder.php create mode 100644 src/EnumComposite.php create mode 100644 src/EnumCompositeBuilder.php create mode 100644 tests/NativeExtension/EnumCompositeTest.php diff --git a/docs/adr/0010-composite-enum-cases.md b/docs/adr/0010-composite-enum-cases.md index 7dd0d6a..ad7d000 100644 --- a/docs/adr/0010-composite-enum-cases.md +++ b/docs/adr/0010-composite-enum-cases.md @@ -1,6 +1,6 @@ # ADR 0010: Explore a composite of native enum cases -- Status: Proposed (exploration; not implemented) +- Status: Proposed (draft implementation; pending review) - Date: 2026-12-03 - Related: ADR 0001, 0004, 0006, 0007, 0008, 0009 @@ -287,3 +287,16 @@ Before requesting an implementation, settle naming, structural and construction Test order-sensitive reversal; repeated cases; differing multiplicities; distinct enum types with equal names/values; empty/singleton inputs if allowed; duplicate policy; readonly construction; symmetric comparisons across policies/subclasses; pure/int-backed/string-backed cases; and generic inference. Add supported PHP 8.4/8.5 tests, runnable examples and migration/documentation review if the feature is accepted. Do not publish a version or commit to a compatibility policy before scope is agreed. This record captures an exploration after v2.0.0, not an accepted public API or a release plan. No runtime changes are authorized by this ADR. + +## Initial implementation candidate (2026-12-03) + +The owner selected EnumComposite and requested implementation. The draft uses CompositeOrder and CompositeDuplicates rather than CompositeType. The following are implementation choices for review, not released API: + +- Standard factories of() and as()->of() both use Sensitive + Preserve by default. The immutable EnumCompositeBuilder receives a construction closure from the base class scope. Factories return the standard base instance, even when called through a subclass. +- The base accepts zero or more UnitEnum cases, including heterogeneous types and repeated types. Named variadic keys are discarded. Both order policies preserve input order; Remove retains the first occurrence, Reject throws InvalidArgumentException. Duplicate detection uses strict native identity. +- unwrap() returns a list; at() uses zero-based indexes and throws OutOfBoundsException on missing indexes. Countable and IteratorAggregate expose the retained sequence. Missing parent initialization throws LogicException. +- hasAll() requires every requested occurrence (including repeated targets); zero targets is true. hasAny() requires any target; zero targets is false. has() checks exact native case identity. +- equalsExactly() compares retained sequence; equalsIgnoringOrder() compares multiplicities by singleton object identity. Both ignore policies and subclass state. equals() requires matching order policies and chooses the corresponding explicit comparison, ensuring symmetry. The duplicate policy is construction-only and is not retained or compared. +- The initial draft exposes UnitEnum types instead of promising heterogeneous tuple inference. Domain subclasses can provide typed properties. Type-based retrieval, convenience factories, wrapper input, table and lazy views are deferred. + +Tests and executable examples accompany the draft. Keep this ADR Proposed until the API is reviewed and accepted. diff --git a/examples/NativeExtension/Composite/EnumComposite.php b/examples/NativeExtension/Composite/EnumComposite.php new file mode 100644 index 0000000..9651d25 --- /dev/null +++ b/examples/NativeExtension/Composite/EnumComposite.php @@ -0,0 +1,112 @@ +status, $this->role]) { + [OrderStatus::Pending, UserRole::Admin] => true, + [OrderStatus::Pending, UserRole::Guest] => true, + [OrderStatus::Paid, UserRole::Admin] => true, + default => false, + }; + } +} + +$route = EnumComposite::of(Country::Japan, Country::France, Country::Japan); + +assert($route->unwrap() === [Country::Japan, Country::France, Country::Japan]); +assert(count($route) === 3); +assert($route->at(1) === Country::France); +assert(iterator_to_array($route) === $route->unwrap()); +assert($route->hasAll(Country::Japan, Country::Japan)); + +$defaultRequirements = [ + Requirement::IdentityVerification, + Requirement::AgeVerification, +]; + +$regionalRequirements = [ + Requirement::IdentityVerification, + Requirement::AddressVerification, +]; + +$requirements = EnumComposite::as( + CompositeOrder::Insensitive, + CompositeDuplicates::Remove, +)->of( + ...$defaultRequirements, + ...$regionalRequirements, +); + +assert(count($requirements) === 3); +assert($requirements->hasAll(Requirement::IdentityVerification, Requirement::AddressVerification)); + +$policy = new OrderStatusPolicy(OrderStatus::Paid, UserRole::Admin); +$guest = new OrderStatusPolicy(OrderStatus::Paid, UserRole::Guest); + +assert($policy->canCancel()); +assert(!$guest->canCancel()); +assert(!$policy->equals($guest)); + +$reversed = EnumComposite::as(CompositeOrder::Insensitive)->of(UserRole::Admin, OrderStatus::Paid); +assert($policy->equals($reversed)); +assert(!$policy->equalsExactly($reversed)); +assert($policy->equalsIgnoringOrder($reversed)); + +$result = match ($policy->unwrap()) { + [OrderStatus::Paid, UserRole::Admin] => 'refund', + default => 'deny', +}; + +assert($result === 'refund'); + +try { + EnumComposite::as(duplicates: CompositeDuplicates::Reject)->of(Country::Japan, Country::Japan); + throw new \LogicException('Expected duplicate rejection'); +} catch (InvalidArgumentException) { + // The duplicate was rejected rather than silently removed. +} diff --git a/src/CompositeDuplicates.php b/src/CompositeDuplicates.php new file mode 100644 index 0000000..542abf4 --- /dev/null +++ b/src/CompositeDuplicates.php @@ -0,0 +1,12 @@ + + */ +readonly class EnumComposite implements Countable, IteratorAggregate { + + /** @var list */ + private array $cases; + + /** + * Stores native cases in input order. Subclasses choose the policies explicitly. + * Named variadic keys are discarded; only the supplied cases and their order matter. + * + * @throws InvalidArgumentException If Reject is selected and a case is repeated. + */ + protected function __construct( + private CompositeOrder $order, + CompositeDuplicates $duplicates, + UnitEnum ...$cases, + ) { + $retained = []; + + foreach ($cases as $case) { + if ($duplicates !== CompositeDuplicates::Preserve && in_array($case, $retained, true)) { + if ($duplicates === CompositeDuplicates::Reject) { + throw new InvalidArgumentException( + 'Duplicate native enum case: ' . $case::class . '::' . $case->name, + ); + } + + continue; + } + + $retained[] = $case; + } + + $this->cases = $retained; + } + + /** Creates a standard composite with order sensitivity and duplicate preservation. */ + final public static function of(UnitEnum ...$cases): self { + return new self( + CompositeOrder::Sensitive, + CompositeDuplicates::Preserve, + ...array_values($cases), + ); + } + + /** Selects the comparison and construction policies before supplying the cases. */ + final public static function as( + CompositeOrder $order = CompositeOrder::Sensitive, + CompositeDuplicates $duplicates = CompositeDuplicates::Preserve, + ): EnumCompositeBuilder { + return new EnumCompositeBuilder( + static fn (array $cases): self => new self($order, $duplicates, ...$cases), + ); + } + + /** + * Returns the retained native cases as a zero-based list in input order. + * + * @return list + * @throws LogicException If a subclass did not call the parent constructor. + */ + final public function unwrap(): array { // @phpstan-ignore throws.unusedType (Subclasses may omit the parent constructor.) + // @phpstan-ignore isset.initializedProperty (Subclasses may omit the parent constructor.) + if (!isset($this->cases)) { + throw new LogicException(static::class . ' must call parent::__construct() with native enum cases'); + } + + return $this->cases; + } + + /** Returns the comparison policy; it does not change the iteration order. */ + final public function order(): CompositeOrder { + $this->unwrap(); + + return $this->order; + } + + /** Returns the number of retained occurrences, including duplicates. */ + final public function count(): int { + return count($this->unwrap()); + } + + /** @return ArrayIterator */ + final public function getIterator(): ArrayIterator { + return new ArrayIterator($this->unwrap()); + } + + /** @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. */ + final public function has(UnitEnum $case): bool { + return in_array($case, $this->unwrap(), true); + } + + /** Checks that every requested occurrence exists; repeated targets require repeated cases. */ + final public function hasAll(UnitEnum ...$cases): bool { + $available = self::frequencies($this->unwrap()); + + foreach (self::frequencies($cases) as $id => $count) { + if (($available[$id] ?? 0) < $count) { + return false; + } + } + + return true; + } + + /** Checks that at least one requested native case exists. No targets returns false. */ + final public function hasAny(UnitEnum ...$cases): bool { + $retained = $this->unwrap(); + + foreach ($cases as $case) { + if (in_array($case, $retained, true)) { + return true; + } + } + + return false; + } + + /** Compares the retained sequence, including order and multiplicity, independently of policy. */ + final public function equalsExactly(self $other): bool { + return $this->unwrap() === $other->unwrap(); + } + + /** Compares the retained case multiplicities, ignoring order and comparison policy. */ + final public function equalsIgnoringOrder(self $other): bool { + // Integer identity keys and integer counts; map insertion order is irrelevant. + return self::frequencies($this->unwrap()) == self::frequencies($other->unwrap()); + } + + /** + * Compares composites with the same order policy according to that policy. + * Different order policies are unequal; construction history, subclass and extra state are ignored. + */ + final public function equals(self $other): bool { + $order = $this->order(); + + if ($order !== $other->order()) { + return false; + } + + return match ($order) { + CompositeOrder::Sensitive => $this->equalsExactly($other), + CompositeOrder::Insensitive => $this->equalsIgnoringOrder($other), + }; + } + + /** + * 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 new file mode 100644 index 0000000..4c318bf --- /dev/null +++ b/src/EnumCompositeBuilder.php @@ -0,0 +1,23 @@ +): EnumComposite $factory + */ + public function __construct(private Closure $factory) {} + + /** Creates a standard composite using the selected policies. */ + public function of(UnitEnum ...$cases): EnumComposite { + return ($this->factory)(array_values($cases)); + } +} diff --git a/tests/NativeExtension/EnumCompositeTest.php b/tests/NativeExtension/EnumCompositeTest.php new file mode 100644 index 0000000..2606b2e --- /dev/null +++ b/tests/NativeExtension/EnumCompositeTest.php @@ -0,0 +1,219 @@ +assertSame($cases, $composite->unwrap()); + $this->assertSame($cases, iterator_to_array($composite)); + $this->assertCount(3, $composite); + $this->assertSame(CompositeCountry::France, $composite->at(1)); + $this->assertSame(CompositeOrder::Sensitive, $composite->order()); + $this->assertTrue($composite->equals(EnumComposite::as()->of(...$cases))); + $this->assertNotSame($composite, EnumComposite::of(...$cases)); + $copy = $composite->unwrap(); + $copy[0] = CompositeCountry::France; + $this->assertSame($cases, $composite->unwrap()); + } + + #[DataProvider('policies')] + public function testAllConstructionPolicies(CompositeOrder $order, CompositeDuplicates $duplicates): void { + $builder = EnumComposite::as($order, $duplicates); + $a = CompositeCountry::Japan; + $b = CompositeCountry::France; + + $unique = $builder->of($a, $b); + $reverse = $builder->of($b, $a); + $this->assertSame([$a, $b], $unique->unwrap()); + $this->assertSame([$b, $a], $reverse->unwrap()); + $this->assertSame($order, $unique->order()); + $this->assertFalse($unique->equalsExactly($reverse)); + $this->assertTrue($unique->equalsIgnoringOrder($reverse)); + $this->assertSame($order === CompositeOrder::Insensitive, $unique->equals($reverse)); + $this->assertSame($unique->equals($reverse), $reverse->equals($unique)); + + if ($duplicates === CompositeDuplicates::Reject) { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Duplicate native enum case: ' . CompositeCountry::class . '::Japan'); + } + + $actual = $builder->of(...[$a, $b], ...[$a]); + $expected = $duplicates === CompositeDuplicates::Remove ? [$a, $b] : [$a, $b, $a]; + $this->assertSame($expected, $actual->unwrap()); + $this->assertSame([$a, $b], $unique->unwrap()); + } + + public static function policies(): iterable { + foreach (CompositeOrder::cases() as $order) { + foreach (CompositeDuplicates::cases() as $duplicates) { + yield $order->name . ' ' . $duplicates->name => [$order, $duplicates]; + } + } + } + + public function testStrictIdentityAndMultiplicity(): void { + $a = CompositeCountry::Japan; + $b = CompositeStatus::Paid; + $c = CompositeOtherStatus::Paid; + $d = CompositeNumber::Paid; + $composite = EnumComposite::of($a, $b, $a, $d); + + $this->assertTrue($composite->has($b)); + $this->assertFalse($composite->has($c)); + $this->assertTrue($composite->hasAll($a, $a, $b)); + $this->assertFalse($composite->hasAll($b, $b)); + $this->assertFalse($composite->hasAll($a, $c)); + $this->assertTrue($composite->hasAny($c, $a)); + $this->assertFalse($composite->hasAny($c)); + $this->assertTrue($composite->equalsIgnoringOrder(EnumComposite::of($d, $a, $b, $a))); + $this->assertFalse($composite->equalsIgnoringOrder(EnumComposite::of($d, $a, $b))); + $this->assertFalse($composite->equalsIgnoringOrder(EnumComposite::of($d, $a, $c, $a))); + + foreach (CompositeDuplicates::cases() as $duplicates) { + $distinct = EnumComposite::as(duplicates: $duplicates)->of($a, $b, $c, $d); + $this->assertSame([$a, $b, $c, $d], $distinct->unwrap()); + } + } + + public function testPoliciesAndConstructionHistory(): void { + $a = CompositeCountry::Japan; + $b = CompositeCountry::France; + $removed = EnumComposite::as(CompositeOrder::Insensitive, CompositeDuplicates::Remove)->of($a, $b, $a); + $rejected = EnumComposite::as(CompositeOrder::Insensitive, CompositeDuplicates::Reject)->of($a, $b); + $preserved = EnumComposite::as(CompositeOrder::Insensitive)->of($b, $a); + $sensitive = EnumComposite::of($a, $b); + + $this->assertTrue($removed->equals($rejected)); + $this->assertTrue($rejected->equals($preserved)); + $this->assertTrue($removed->equals($preserved)); + $this->assertTrue($removed->equals($removed)); + $this->assertTrue($removed->equalsExactly($sensitive)); + $this->assertTrue($sensitive->equalsIgnoringOrder($removed)); + $this->assertFalse($removed->equals($sensitive)); + $this->assertFalse($sensitive->equals($removed)); + } + + public function testEmptySingletonAndNamedVariadicKeys(): void { + $empty = EnumComposite::of(); + $a = CompositeCountry::Japan; + + $this->assertSame([], $empty->unwrap()); + $this->assertCount(0, $empty); + $this->assertTrue($empty->hasAll()); + $this->assertFalse($empty->hasAny()); + $this->assertFalse($empty->has($a)); + $this->assertFalse($empty->hasAll($a)); + $this->assertTrue($empty->equals(EnumComposite::of())); + $this->assertFalse($empty->equalsIgnoringOrder(EnumComposite::of($a))); + $this->assertSame([$a], EnumComposite::of($a)->unwrap()); + $this->assertSame([$a], EnumComposite::of(order: $a)->unwrap()); + $this->assertSame([$a], EnumComposite::as()->of(duplicates: $a)->unwrap()); + } + + #[DataProvider('invalidIndexes')] + public function testMissingIndex(int $index): void { + $this->expectException(OutOfBoundsException::class); + + EnumComposite::of(CompositeCountry::Japan)->at($index); + } + + public static function invalidIndexes(): iterable { + yield [-1]; + yield [1]; + } + + public function testSubclassAndStandardFactories(): void { + $a = CompositeCountry::Japan; + $b = CompositeCountry::France; + $route = new CompositeRoute($a, $b); + $standard = EnumComposite::of($a, $b); + + $this->assertSame($a, $route->origin); + $this->assertSame($b, $route->destination); + $this->assertTrue($route->equals($standard)); + $this->assertTrue($standard->equals($route)); + $this->assertSame(EnumComposite::class, CompositeRoute::of($a, $b)::class); + $this->assertSame(EnumComposite::class, CompositeRoute::as()->of($a, $b)::class); + } + + public function testInvalidCaseType(): void { + $this->expectException(TypeError::class); + + EnumComposite::of('Japan'); + } + + #[DataProvider('operations')] + public function testMissingParentConstructor(string $method, array $arguments): void { + $broken = new readonly class extends EnumComposite { + public function __construct() {} + }; + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('must call parent::__construct()'); + + $broken->$method(...$arguments); + } + + public static function operations(): iterable { + $valid = EnumComposite::of(); + yield ['unwrap', []]; + yield ['order', []]; + yield ['count', []]; + yield ['getIterator', []]; + yield ['at', [0]]; + yield ['has', [CompositeCountry::Japan]]; + yield ['hasAll', []]; + yield ['hasAny', []]; + yield ['equals', [$valid]]; + yield ['equalsExactly', [$valid]]; + yield ['equalsIgnoringOrder', [$valid]]; + } +} From 1d35f478efe43f7b8fceea1c2a2778d5a8edb22e Mon Sep 17 00:00:00 2001 From: Kangin Kim Date: Thu, 3 Dec 2026 02:31:35 +0900 Subject: [PATCH 02/13] Document EnumComposite construction, comparison and domain examples --- README.md | 86 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 85 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index d235c49..e0c939f 100644 --- a/README.md +++ b/README.md @@ -178,7 +178,7 @@ The public APIs are organized by approach: | Namespace | Purpose | | --- | --- | -| `Notonza\PhpEnumEx` | `EnumCase` and `EnumCollection` | +| `Notonza\PhpEnumEx` | `EnumCase`, `EnumCollection`, and `EnumComposite` | | `Notonza\PhpEnumEx\EnumTraits` | `EnumMethods` and `EnumCollections` | | `Notonza\PhpEnumEx\ClassBased` | Original class-based Enum and its exceptions | @@ -191,6 +191,7 @@ The `Internal` namespace is not a public API. | Native enum | The default for a fixed set of domain values and intrinsic domain behavior. | | `EnumCase` | Add behavior outside an enum, reuse behavior through inheritance, or carry additional state. | | `EnumCollection` | Work with every case of an enum, optionally with a context-specific wrapper factory. | +| `EnumComposite` | Represent several native cases as a single structured value with explicit comparison and duplicate policies. | | Native enum traits | Add common collection, comparison, and debugging operations to enums you own. | | Class-based `Enum` | Maintain existing integrations or model enum-like constant sets that can be extended or overridden through inheritance. | @@ -573,6 +574,89 @@ Array selection matches native case identity (including the case inside an `Enum The same selection operations are available as static methods on the native collection trait and [Class-based Enum](README-ClassBased.md). To exclude cases using a closure, use `reject()` or `iterateReject()`, not `except()` or `iterateExcept()`. +## Native Enum Composites + +`EnumComposite` represents several native enum cases as one readonly value. Unlike an EnumCase wrapper's additional context, all retained cases participate in structural comparison. Cases may belong to different enum types or repeat the same type. + +```php +use Notonza\PhpEnumEx\CompositeDuplicates; +use Notonza\PhpEnumEx\CompositeOrder; +use Notonza\PhpEnumEx\EnumComposite; + +enum Country { + case Japan; + case France; +} + +$route = EnumComposite::of( + Country::Japan, + Country::France, + Country::Japan, +); + +$route->unwrap(); // [Country::Japan, Country::France, Country::Japan] +$route->at(1); // Country::France +count($route); // 3 +``` + +The default preserves input order and duplicates. Select other policies before supplying the cases: + +```php +$countries = EnumComposite::as( + CompositeOrder::Insensitive, + CompositeDuplicates::Remove, +)->of( + Country::Japan, + Country::France, + Country::Japan, +); + +$countries->unwrap(); // [Country::Japan, Country::France] +$countries->equalsIgnoringOrder( + EnumComposite::of(Country::France, Country::Japan), +); // true +``` + +Both order policies preserve iteration order. Duplicate handling is a construction policy: Preserve retains occurrences, Remove retains the first occurrence of each case, and Reject throws InvalidArgumentException if a case is repeated. Duplicate detection uses native case identity, not names or backing values. + +`equalsExactly()` compares the retained sequence; `equalsIgnoringOrder()` compares multiplicities without order. Both ignore the construction and comparison policies. `equals()` requires the same order policy on both operands and uses the corresponding comparison. Subclass and additional state do not affect these comparisons. + +Use `has()`, `hasAll()`, and `hasAny()` to check membership. Repeated targets in hasAll() require repeated occurrences. Empty and singleton composites are supported; hasAll() with no targets is true and hasAny() with no targets is false. `at()` throws OutOfBoundsException for a missing zero-based index. Named variadic keys are not retained. + +### Domain-specific composites + +A subclass can name the roles of its components and add behavior. For example, an order status and a user role can form a cancellation policy: + +```php +final readonly class OrderStatusPolicy extends EnumComposite { + + public function __construct( + public OrderStatus $status, + public UserRole $role, + ) { + parent::__construct( + CompositeOrder::Insensitive, + CompositeDuplicates::Reject, + $status, + $role, + ); + } + + public function canCancel(): bool { + return match ([$this->status, $this->role]) { + [OrderStatus::Pending, UserRole::Admin] => true, + [OrderStatus::Pending, UserRole::Guest] => true, + [OrderStatus::Paid, UserRole::Admin] => true, + default => false, + }; + } +} +``` + +Use the native cases directly in a match expression when order matters, or use the composite's comparison and membership methods for order-independent decisions. The standard of() and as()->of() factories always create a standard EnumComposite, not a subclass. + +See [EnumComposite](https://github.com/gachakra/php-enumex/blob/2c1ff6d5da130e94e021c403c30ba1ae7bc15150/examples/NativeExtension/Composite/EnumComposite.php) for runnable examples, including typed subclasses, dynamic requirements and duplicate rejection. + ## Native Enum Traits For enums you own, use traits to add shared operations without wrapping the enum. This is useful when collection operations or debugging helpers should be available directly on several native enum types, but there is no need for an extension object: From 5276a6e8a0c3a26e06ffbd3723a13c9d38ffcc0b Mon Sep 17 00:00:00 2001 From: Kangin Kim Date: Thu, 3 Dec 2026 02:49:41 +0900 Subject: [PATCH 03/13] Add PHPDoc usage examples to EnumComposite and its builder --- src/EnumComposite.php | 146 ++++++++++++++++++++++++++++++++--- src/EnumCompositeBuilder.php | 15 +++- 2 files changed, 149 insertions(+), 12 deletions(-) diff --git a/src/EnumComposite.php b/src/EnumComposite.php index 39c7636..6c582ea 100644 --- a/src/EnumComposite.php +++ b/src/EnumComposite.php @@ -16,6 +16,12 @@ * Readonly composite of native enum cases, possibly from different enum types. * Input order is retained regardless of the comparison policy. * + * Examples below assume App\Country is a pure enum with Japan and France, + * App\OrderStatus has Paid, and App\UserRole has Admin. + * $route denotes EnumComposite::of(Country::Japan, Country::France, Country::Japan). + * $pair denotes EnumComposite::of(Country::Japan, Country::France). + * $reverse denotes EnumComposite::of(Country::France, Country::Japan). + * * @implements IteratorAggregate */ readonly class EnumComposite implements Countable, IteratorAggregate { @@ -27,6 +33,15 @@ * Stores native cases in input order. Subclasses choose the policies explicitly. * Named variadic keys are discarded; only the supplied cases and their order matter. * + * Example: + * // Inside a custom route composite's constructor: + * parent::__construct( + * CompositeOrder::Sensitive, + * CompositeDuplicates::Preserve, + * $origin, + * $destination, + * ); + * * @throws InvalidArgumentException If Reject is selected and a case is repeated. */ protected function __construct( @@ -53,7 +68,16 @@ protected function __construct( $this->cases = $retained; } - /** Creates a standard composite with order sensitivity and duplicate preservation. */ + /** + * Creates a standard composite with order sensitivity and duplicate preservation. + * Always returns a standard EnumComposite, not an instance of a calling subclass. + * + * Example: + * EnumComposite::of(Country::Japan, Country::France, Country::Japan); + * // Composite retaining [Country::Japan, Country::France, Country::Japan] + * EnumComposite::of(OrderStatus::Paid, UserRole::Admin); + * // Composite retaining [OrderStatus::Paid, UserRole::Admin] + */ final public static function of(UnitEnum ...$cases): self { return new self( CompositeOrder::Sensitive, @@ -62,7 +86,19 @@ final public static function of(UnitEnum ...$cases): self { ); } - /** Selects the comparison and construction policies before supplying the cases. */ + /** + * Selects the comparison and construction policies before supplying the cases. + * Returns an immutable, reusable factory; no composite is created until of() is called. + * + * Example: + * $countries = EnumComposite::as( + * CompositeOrder::Insensitive, + * CompositeDuplicates::Remove, + * )->of(Country::Japan, Country::France, Country::Japan); + * $countries->unwrap(); // [Country::Japan, Country::France] + * EnumComposite::as(duplicates: CompositeDuplicates::Reject) + * ->of(Country::Japan, Country::Japan); // throws InvalidArgumentException + */ final public static function as( CompositeOrder $order = CompositeOrder::Sensitive, CompositeDuplicates $duplicates = CompositeDuplicates::Preserve, @@ -75,6 +111,11 @@ final public static function as( /** * Returns the retained native cases as a zero-based list in input order. * + * Example: + * $route->unwrap(); // [Country::Japan, Country::France, Country::Japan] + * [$origin, $destination] = $pair->unwrap(); + * // $origin = Country::Japan, $destination = Country::France + * * @return list * @throws LogicException If a subclass did not call the parent constructor. */ @@ -87,36 +128,87 @@ final public function unwrap(): array { // @phpstan-ignore throws.unusedType (Su return $this->cases; } - /** Returns the comparison policy; it does not change the iteration order. */ + /** + * Returns the comparison policy; it does not change the iteration order. + * + * Example: + * $route->order(); // CompositeOrder::Sensitive + * EnumComposite::as(CompositeOrder::Insensitive) + * ->of(Country::Japan, Country::France)->order(); // CompositeOrder::Insensitive + */ final public function order(): CompositeOrder { $this->unwrap(); return $this->order; } - /** Returns the number of retained occurrences, including duplicates. */ + /** + * Returns the number of retained occurrences, including duplicates. + * + * Example: + * $route->count(); // 3 + * count($route); // 3 + * EnumComposite::of()->count(); // 0 + */ final public function count(): int { return count($this->unwrap()); } - /** @return ArrayIterator */ + /** + * Iterates over the retained native cases with zero-based integer keys, in input order. + * Changes to the returned iterator do not change the composite. + * + * Example: + * foreach ($route as $index => $case) { + * echo $index . ': ' . $case->name . PHP_EOL; + * } + * // 0: Japan + * // 1: France + * // 2: Japan + * + * @return ArrayIterator + */ final public function getIterator(): ArrayIterator { return new ArrayIterator($this->unwrap()); } - /** @throws OutOfBoundsException If the zero-based index does not exist. */ + /** + * 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. */ + /** + * Checks whether the exact native case occurs at least once. + * + * Example: + * $route->has(Country::Japan); // true + * $route->has(OrderStatus::Paid); // false + */ final public function has(UnitEnum $case): bool { return in_array($case, $this->unwrap(), true); } - /** Checks that every requested occurrence exists; repeated targets require repeated cases. */ + /** + * Checks that every requested occurrence exists, regardless of order. + * Repeated targets require repeated cases. No targets returns true. + * + * Example: + * $route->hasAll(Country::France, Country::Japan); // true + * $route->hasAll(Country::Japan, Country::Japan); // true + * $pair->hasAll(Country::Japan, Country::Japan); // false + * $route->hasAll(); // true + */ final public function hasAll(UnitEnum ...$cases): bool { $available = self::frequencies($this->unwrap()); @@ -129,7 +221,14 @@ final public function hasAll(UnitEnum ...$cases): bool { return true; } - /** Checks that at least one requested native case exists. No targets returns false. */ + /** + * Checks that at least one requested native case exists. No targets returns false. + * + * Example: + * $route->hasAny(OrderStatus::Paid, Country::Japan); // true + * $route->hasAny(OrderStatus::Paid, UserRole::Admin); // false + * $route->hasAny(); // false + */ final public function hasAny(UnitEnum ...$cases): bool { $retained = $this->unwrap(); @@ -142,12 +241,28 @@ final public function hasAny(UnitEnum ...$cases): bool { return false; } - /** Compares the retained sequence, including order and multiplicity, independently of policy. */ + /** + * Compares the retained sequence, including order and multiplicity, independently of policy. + * + * Example: + * $pair->equalsExactly(EnumComposite::of(Country::Japan, Country::France)); // true + * $pair->equalsExactly($reverse); // false + * $pair->equalsExactly($route); // false + */ final public function equalsExactly(self $other): bool { return $this->unwrap() === $other->unwrap(); } - /** Compares the retained case multiplicities, ignoring order and comparison policy. */ + /** + * Compares the retained case multiplicities, ignoring order and comparison policy. + * + * Example: + * $pair->equalsIgnoringOrder($reverse); // true + * $route->equalsIgnoringOrder($pair); // false (different occurrence counts) + * $route->equalsIgnoringOrder( + * EnumComposite::of(Country::France, Country::Japan, Country::Japan), + * ); // true + */ final public function equalsIgnoringOrder(self $other): bool { // Integer identity keys and integer counts; map insertion order is irrelevant. return self::frequencies($this->unwrap()) == self::frequencies($other->unwrap()); @@ -156,6 +271,15 @@ final public function equalsIgnoringOrder(self $other): bool { /** * Compares composites with the same order policy according to that policy. * Different order policies are unequal; construction history, subclass and extra state are ignored. + * + * Example: + * $pair->equals($reverse); // false + * $unordered = EnumComposite::as(CompositeOrder::Insensitive); + * $a = $unordered->of(Country::Japan, Country::France); + * $b = $unordered->of(Country::France, Country::Japan); + * $a->equals($b); // true + * $a->equals($pair); // false (different order policies) + * $a->equalsExactly($pair); // true (same retained sequence) */ final public function equals(self $other): bool { $order = $this->order(); diff --git a/src/EnumCompositeBuilder.php b/src/EnumCompositeBuilder.php index 4c318bf..095e7ab 100644 --- a/src/EnumCompositeBuilder.php +++ b/src/EnumCompositeBuilder.php @@ -16,7 +16,20 @@ */ public function __construct(private Closure $factory) {} - /** Creates a standard composite using the selected policies. */ + /** + * 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): + * $factory = EnumComposite::as( + * CompositeOrder::Insensitive, + * CompositeDuplicates::Remove, + * ); + * $a = $factory->of(Country::Japan, Country::Japan); + * $b = $factory->of(Country::France, Country::Japan); + * $a->unwrap(); // [Country::Japan] + * $b->unwrap(); // [Country::France, Country::Japan] + */ public function of(UnitEnum ...$cases): EnumComposite { return ($this->factory)(array_values($cases)); } From 7d41cddb1951ff2e3637f18d0a3fc5a141b6076a Mon Sep 17 00:00:00 2001 From: Kangin Kim Date: Thu, 3 Dec 2026 03:02:19 +0900 Subject: [PATCH 04/13] Align multiline parameter variables and match arrows --- README.md | 6 +++--- examples/NativeExtension/Backed/Currency.php | 2 +- examples/NativeExtension/Collections/FilePermission.php | 2 +- examples/NativeExtension/Composite/EnumComposite.php | 6 +++--- src/EnumCollection.php | 2 +- src/EnumComposite.php | 6 +++--- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index e0c939f..42c7cde 100644 --- a/README.md +++ b/README.md @@ -103,7 +103,7 @@ final readonly class PermissionCheck extends EnumCase { public function __construct( FilePermission $permission, - private int $mask, + private int $mask, ) { parent::__construct($permission); } @@ -632,7 +632,7 @@ final readonly class OrderStatusPolicy extends EnumComposite { public function __construct( public OrderStatus $status, - public UserRole $role, + public UserRole $role, ) { parent::__construct( CompositeOrder::Insensitive, @@ -647,7 +647,7 @@ final readonly class OrderStatusPolicy extends EnumComposite { [OrderStatus::Pending, UserRole::Admin] => true, [OrderStatus::Pending, UserRole::Guest] => true, [OrderStatus::Paid, UserRole::Admin] => true, - default => false, + default => false, }; } } diff --git a/examples/NativeExtension/Backed/Currency.php b/examples/NativeExtension/Backed/Currency.php index 29fe3c7..a0d1c9e 100644 --- a/examples/NativeExtension/Backed/Currency.php +++ b/examples/NativeExtension/Backed/Currency.php @@ -31,7 +31,7 @@ public function symbol(): string { public function format(int|float $amount, bool $grouping = true): string { $decimals = match ($this->unwrap()) { - Currency::JPY => 0, + Currency::JPY => 0, Currency::USD, Currency::EUR => 2, }; diff --git a/examples/NativeExtension/Collections/FilePermission.php b/examples/NativeExtension/Collections/FilePermission.php index f719f7e..a8d1b6c 100644 --- a/examples/NativeExtension/Collections/FilePermission.php +++ b/examples/NativeExtension/Collections/FilePermission.php @@ -21,7 +21,7 @@ enum FilePermission: int { public function __construct( FilePermission $permission, - private int $mask, + private int $mask, ) { parent::__construct($permission); } diff --git a/examples/NativeExtension/Composite/EnumComposite.php b/examples/NativeExtension/Composite/EnumComposite.php index 9651d25..203d293 100644 --- a/examples/NativeExtension/Composite/EnumComposite.php +++ b/examples/NativeExtension/Composite/EnumComposite.php @@ -36,7 +36,7 @@ enum Requirement { public function __construct( public OrderStatus $status, - public UserRole $role, + public UserRole $role, ) { parent::__construct( CompositeOrder::Insensitive, @@ -51,7 +51,7 @@ public function canCancel(): bool { [OrderStatus::Pending, UserRole::Admin] => true, [OrderStatus::Pending, UserRole::Guest] => true, [OrderStatus::Paid, UserRole::Admin] => true, - default => false, + default => false, }; } } @@ -99,7 +99,7 @@ public function canCancel(): bool { $result = match ($policy->unwrap()) { [OrderStatus::Paid, UserRole::Admin] => 'refund', - default => 'deny', + default => 'deny', }; assert($result === 'refund'); diff --git a/src/EnumCollection.php b/src/EnumCollection.php index 7e2d449..616078e 100644 --- a/src/EnumCollection.php +++ b/src/EnumCollection.php @@ -48,7 +48,7 @@ * @throws InvalidArgumentException If the class is not a native enum. */ protected function __construct( - private string $enumClass, + private string $enumClass, private Closure $factory, ) { if (!enum_exists($enumClass)) { diff --git a/src/EnumComposite.php b/src/EnumComposite.php index 6c582ea..4938109 100644 --- a/src/EnumComposite.php +++ b/src/EnumComposite.php @@ -46,8 +46,8 @@ */ protected function __construct( private CompositeOrder $order, - CompositeDuplicates $duplicates, - UnitEnum ...$cases, + CompositeDuplicates $duplicates, + UnitEnum ...$cases, ) { $retained = []; @@ -100,7 +100,7 @@ final public static function of(UnitEnum ...$cases): self { * ->of(Country::Japan, Country::Japan); // throws InvalidArgumentException */ final public static function as( - CompositeOrder $order = CompositeOrder::Sensitive, + CompositeOrder $order = CompositeOrder::Sensitive, CompositeDuplicates $duplicates = CompositeDuplicates::Preserve, ): EnumCompositeBuilder { return new EnumCompositeBuilder( From 011e79db99c6adbba236145dd8ccddf6da78c6ee Mon Sep 17 00:00:00 2001 From: Kangin Kim Date: Thu, 3 Dec 2026 03:13:39 +0900 Subject: [PATCH 05/13] docs: establish EnumEx coding style and agent guidelines --- .gitattributes | 1 + AGENTS.md | 86 ++++++++++++++++++++++++++ docs/coding-style.md | 141 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 228 insertions(+) create mode 100644 AGENTS.md create mode 100644 docs/coding-style.md diff --git a/.gitattributes b/.gitattributes index e377f62..83a959e 100644 --- a/.gitattributes +++ b/.gitattributes @@ -8,3 +8,4 @@ /tests export-ignore /phpunit.xml export-ignore /docs export-ignore +/AGENTS.md export-ignore diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..f6bc960 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,86 @@ +# Agent Guidelines + +## Design Philosophy + +**Same enum, different behavior.** + +- Extend native enums through composition rather than replacing them. +- Preserve native enum identity and logical values. Keep identity, structural equality, presentation, behavior, and context distinct. +- Prefer native PHP features when sufficient; introduce abstractions only when they provide meaningful benefits. +- Respect class-based enums as an independent abstraction. + +## Architecture + +- Separate responsibilities and use composition, inheritance, and strategy according to the needs of each abstraction. +- Avoid unnecessary dependencies between abstractions. Use explicit construction contracts for extensible classes. +- Consult the [architecture decision records](docs/adr/README.md) before changing established design decisions. +- Distinguish accepted decisions from proposed or superseded designs. A proposed ADR is not an implementation request or an implemented specification. + +## Coding Style + +Follow [EnumEx Coding Style](docs/coding-style.md). Preserve intentional alignment and semantic whitespace; avoid blanket formatting changes. Use modern PHP features appropriate to the supported PHP versions. + +## Type Safety and Static Analysis + +- Prefer precise native types and PHPDoc generics where they express the actual contract. +- Preserve strict comparison and avoid unintended scalar coercion. +- Do not unnecessarily change natural PHP code or public APIs solely to accommodate analyzer limitations. +- Prefer narrowly scoped, justified annotations when analyzer-specific workarounds are necessary. Do not suppress unrelated diagnostics. + +See [Static Analysis](docs/static-analysis/README.md). + +## Documentation + +- Keep implementation, PHPDoc, README files, executable examples, and tests consistent. +- Include concrete usage examples in public API documentation where practical. +- Preserve the historical documentation of class-based enums. +- Record significant architectural decisions in ADRs, including context, alternatives, rationale, and status. + +## Testing and Validation + +- Follow the validation steps in [.github/workflows/ci.yml](.github/workflows/ci.yml). +- Run PHPUnit, executable examples with assertions enabled, relevant static-analysis checks, and distribution archive checks as applicable. +- Verify compatibility with all supported PHP versions (currently PHP 8.4 and 8.5). +- Never report checks as successful unless actually executed or verified. Distinguish failures, known pre-existing diagnostics, and checks not performed. + +## Public API Compatibility + +Treat released public APIs as compatibility commitments. Do not introduce breaking changes without explicit justification and maintainer approval. Avoid silently changing the meaning of existing operations or discarding caller-supplied information. + +## Security and Privacy + +Never expose confidential, sensitive, personal, or environment-specific information in the public repository or associated development activities. + +Do not publish: + +- Credentials, passwords, API tokens, access keys, private keys, or sensitive environment variable values. +- Personal information not explicitly intended for publication. +- Actual absolute local filesystem paths, home directory paths, local usernames, or machine-specific identifiers. +- Private hostnames, internal network addresses, or environment-specific configuration. +- Private repository contents, unpublished design documents, or internal handover notes. +- Unredacted logs, stack traces, screenshots, or diagnostic output containing sensitive information. + +Use repository-relative paths, fictional examples, and neutral placeholders such as `` and `` instead of actual environment-specific information. + +These restrictions apply to code, comments, documentation, tests, fixtures, commit messages, pull requests, issues, reviews, CI output, and published artifacts. Inspect the intended diff and public output before committing, pushing, or posting. Do not include secrets or private information in a report about a potential disclosure; notify the maintainer through an appropriate non-public channel without reproducing sensitive values. + +Do not rewrite published history or take destructive remediation actions without explicit authorization. + +## Development Workflow + +- Distinguish design consultation, agreed design decisions, and implementation requests. +- Inspect the current implementation, relevant ADRs, and branch state before making changes. +- Keep changes focused on the requested scope. Do not implement unrelated proposals. +- Evaluate review findings against the intended design rather than applying them mechanically. +- Commit, push, open or merge pull requests, publish releases, or modify repository settings only within the maintainer's authorization. Do not rewrite published tags or history without explicit authorization. + +### Independent Reviews + +When assigned to independently review a pull request: + +- Review the actual diff and surrounding implementation at the current PR head. Assess correctness, design contracts, compatibility, type safety, tests, documentation, and security as relevant. +- Verify independently rather than assuming the author's claims or existing CI results establish correctness. Record the reviewed commit and checks performed, including limitations. +- Report actionable findings with severity, repository-relative file and line references, a concrete explanation, and a reproduction or test where practical. Distinguish defects from suggestions and unresolved design questions. +- Do not modify the implementation, push fixes, or merge the PR unless separately authorized. +- **Post the review outcome as a comment on the target GitHub pull request after completing the review, even when no actionable findings are identified.** A chat-only report does not complete the review. Use a PR review or PR conversation comment, and include the overall conclusion, findings or absence of findings, verification results, and remaining risks. +- Follow the Security and Privacy rules when posting. If posting is unavailable, report that limitation and provide a sanitized comment draft; do not claim that it was posted. diff --git a/docs/coding-style.md b/docs/coding-style.md new file mode 100644 index 0000000..8a5fbcc --- /dev/null +++ b/docs/coding-style.md @@ -0,0 +1,141 @@ +# EnumEx Coding Style + +EnumEx uses a consistent PHP style that makes declarations and conceptual groups easy to scan. These conventions complement the architecture and type contracts; formatting must not change behavior. Apply them to source code, tests, executable examples, and current documentation snippets. Preserve historical documentation and intentionally recorded historical examples. + +## Basic Layout + +- Use four spaces for indentation, not tabs. +- Place opening braces on the same line as class, enum, trait, method, and control-structure declarations, following existing code. +- Preserve the established blank line immediately inside a class when appropriate. Do not add an unnecessary blank line immediately after an enum's opening brace. +- Use trailing commas in multiline parameter and argument lists where supported and appropriate. + +```php +final readonly class OrderStatusPolicy extends EnumComposite { + + public function __construct( + public OrderStatus $status, + public UserRole $role, + ) { + parent::__construct( + CompositeOrder::Insensitive, + CompositeDuplicates::Reject, + $status, + $role, + ); + } +} +``` + +## Declaration Alignment + +Align consecutive related declarations within the same conceptual group. Do not align unrelated groups across meaningful blank lines. + +Align the assignment operators of backed enum cases and constants, and the variable names of consecutive property declarations where appropriate. + +```php +enum FilePermission: int { + case READ = 0b000001; + case WRITE = 0b000010; + case EXECUTE = 0b000100; +} +``` + +Prefer binary literals for bit flags when they make bit positions easier to understand. Bit shifts remain appropriate when they express the intent more directly, such as powers of two for byte units. + +```php +private int $count; +private string $name; +``` + +Pure enum cases do not need artificial padding. + +```php +enum CompositeOrder { + case Sensitive; + case Insensitive; +} +``` + +## Multiline Parameter Alignment + +Align the starting position of the variable name (the dollar sign) in consecutive multiline parameter declarations, including promoted properties and variadic parameters. + +```php +protected function __construct( + private CompositeOrder $order, + CompositeDuplicates $duplicates, + UnitEnum ...$cases, +) { + // ... +} +``` + +```php +final public static function as( + CompositeOrder $order = CompositeOrder::Sensitive, + CompositeDuplicates $duplicates = CompositeDuplicates::Preserve, +): EnumCompositeBuilder { + // ... +} +``` + +Keep the variadic or reference marker attached to its variable. Do not add padding to ordinary argument expressions merely to align them. Alignment of default-value assignment operators in parameter declarations is not required. + +## Match Arm Alignment + +Align the `=>` operators within each related group of match arms, including `default`. Align nested match expressions independently. + +```php +return match ([$this->status, $this->role]) { + [OrderStatus::Pending, UserRole::Admin] => true, + [OrderStatus::Pending, UserRole::Guest] => true, + [OrderStatus::Paid, UserRole::Admin] => true, + default => false, +}; +``` + +```php +$decimals = match ($this->unwrap()) { + Currency::JPY => 0, + Currency::USD, Currency::EUR => 2, +}; +``` + +## Semantic Whitespace + +Use blank lines to separate operations and conceptual groups, not as an indiscriminate rule applied between all statements. + +```php +$presentation = new OrderStatusPresentation( + OrderStatus::Paid, + 'ja', +); + +$badge = new OrderStatusBadge($presentation); + +$badge->label(); +$badge->color(); +``` + +Preserve intentional spacing in existing code. Avoid unrelated formatting churn when changing behavior. + +## Types and PHPDoc + +Use precise native types, readonly where appropriate, and PHPDoc generics that express the actual type contract. Document important behavior, exceptions, and return shapes. For public operations, provide concrete examples in PHPDoc where practical, following the existing EnumCase and EnumCollection documentation style. + +```php +/** + * Returns the retained native cases as a zero-based list in input order. + * + * Example: + * $route->unwrap(); // [Country::Japan, Country::France, Country::Japan] + * + * @return list + */ +``` + +Keep example results consistent with the implementation and executable examples. Do not add misleading or redundant annotations solely for formatting consistency. + +## Formatting Tools + +These conventions are project-specific; they do not claim full PSR-12 compliance. Do not introduce or run blanket automated formatting that removes intentional alignment or semantic whitespace. If automated rules are introduced later, configure them to preserve these conventions and review their resulting diff. From 7d70d44b2f746639f2960bbf734e2a191d137b60 Mon Sep 17 00:00:00 2001 From: Kangin Kim Date: Thu, 3 Dec 2026 04:08:24 +0900 Subject: [PATCH 06/13] Reject unsupported composite serialization and verify type contracts --- .github/workflows/ci.yml | 29 +++++++++++ README.md | 6 ++- docs/adr/0010-composite-enum-cases.md | 10 ++++ docs/static-analysis/README.md | 13 +++++ docs/static-analysis/composite-negative.php | 19 +++++++ docs/static-analysis/composite-positive.php | 57 +++++++++++++++++++++ src/EnumComposite.php | 27 ++++++++++ tests/NativeExtension/EnumCompositeTest.php | 57 +++++++++++++++++++++ 8 files changed, 216 insertions(+), 2 deletions(-) create mode 100644 docs/static-analysis/composite-negative.php create mode 100644 docs/static-analysis/composite-positive.php diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ab56b84..7cf995b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -88,6 +88,35 @@ jobs: fi php docs/static-analysis/check-selection-report.php "$RUNNER_TEMP/selection-positive.json" + - name: Check composite type contracts + run: | + phpstan analyse --level=max --no-progress --autoload-file=vendor/autoload.php \ + src/EnumComposite.php src/EnumCompositeBuilder.php \ + examples/NativeExtension/Composite/EnumComposite.php docs/static-analysis/composite-positive.php + status=0 + phpstan analyse --level=max --no-progress --error-format=json --autoload-file=vendor/autoload.php \ + docs/static-analysis/composite-negative.php > "$RUNNER_TEMP/composite-negative.json" || status=$? + if [ "$status" -ne 1 ]; then + exit 1 + fi + php -r ' + $report = json_decode(file_get_contents($argv[1]), true, flags: JSON_THROW_ON_ERROR); + $lines = []; + foreach ($report["files"] as $file => $result) { + foreach ($result["messages"] as $message) { + echo $message["line"], ": ", $message["message"], PHP_EOL; + if (($message["identifier"] ?? null) !== "argument.type") { + exit(1); + } + $lines[] = $message["line"]; + } + } + sort($lines); + if ($report["totals"]["errors"] !== 0 || $lines !== [16, 17, 18, 19]) { + exit(1); + } + ' "$RUNNER_TEMP/composite-negative.json" + - name: Run PHPUnit run: vendor/bin/phpunit diff --git a/README.md b/README.md index 42c7cde..5a2d0ea 100644 --- a/README.md +++ b/README.md @@ -599,7 +599,7 @@ $route->at(1); // Country::France count($route); // 3 ``` -The default preserves input order and duplicates. Select other policies before supplying the cases: +The default is `CompositeOrder::Sensitive` + `CompositeDuplicates::Preserve`: order matters to `equals()`, and all occurrences are retained. Select other policies before supplying the cases: ```php $countries = EnumComposite::as( @@ -617,12 +617,14 @@ $countries->equalsIgnoringOrder( ); // true ``` -Both order policies preserve iteration order. Duplicate handling is a construction policy: Preserve retains occurrences, Remove retains the first occurrence of each case, and Reject throws InvalidArgumentException if a case is repeated. Duplicate detection uses native case identity, not names or backing values. +Both order policies preserve input order in storage and iteration. Duplicate handling is a construction policy: Preserve retains occurrences, Remove retains the first occurrence of each case, and Reject throws InvalidArgumentException if a case is repeated. Duplicate detection uses native case identity, not names or backing values. `equalsExactly()` compares the retained sequence; `equalsIgnoringOrder()` compares multiplicities without order. Both ignore the construction and comparison policies. `equals()` requires the same order policy on both operands and uses the corresponding comparison. Subclass and additional state do not affect these comparisons. Use `has()`, `hasAll()`, and `hasAny()` to check membership. Repeated targets in hasAll() require repeated occurrences. Empty and singleton composites are supported; hasAll() with no targets is true and hasAny() with no targets is false. `at()` throws OutOfBoundsException for a missing zero-based index. Named variadic keys are not retained. +Native PHP serialization and deserialization are not supported yet. Both `serialize()` and `unserialize()` throw `LogicException` for EnumComposite and its subclasses. Persist the required domain data explicitly and reconstruct the composite through its normal construction API instead. + ### Domain-specific composites A subclass can name the roles of its components and add behavior. For example, an order status and a user role can form a cancellation policy: diff --git a/docs/adr/0010-composite-enum-cases.md b/docs/adr/0010-composite-enum-cases.md index ad7d000..caa493a 100644 --- a/docs/adr/0010-composite-enum-cases.md +++ b/docs/adr/0010-composite-enum-cases.md @@ -300,3 +300,13 @@ The owner selected EnumComposite and requested implementation. The draft uses Co - The initial draft exposes UnitEnum types instead of promising heterogeneous tuple inference. Domain subclasses can provide typed properties. Type-based retrieval, convenience factories, wrapper input, table and lazy views are deferred. Tests and executable examples accompany the draft. Keep this ADR Proposed until the API is reviewed and accepted. + +## Native serialization boundary (review follow-up) + +Independent review found that PHP's default native object restoration bypasses the constructor and can populate the private array with sparse keys, non-enum elements or references. The readonly property and its PHPDoc list contract do not independently guarantee these invariants on restoration. + +The owner chose to defer native serialization support. Both __serialize() and __unserialize() are final and throw LogicException, including on subclasses. This closes the unsupported restoration path without introducing a persistence contract or silently altering the stored cases. Regression tests cover standard and derived objects, valid-looking legacy state, sparse and invalid lists, and referenced entries. + +Future persistence design should be driven by actual use cases. Explicit domain snapshots and JSON encoding are alternatives to native PHP serialization; the snapshot schema, validation and restoration contracts, subclass state, and versioning remain open. Do not redesign EnumCollection factories or the inheritance model merely to accommodate serialization. Existing EnumCase, EnumCollection and Class-based Enum behavior is outside this change. The builder remains a construction helper rather than a persisted value. + +The ADR remains Proposed pending acceptance of the reviewed implementation. diff --git a/docs/static-analysis/README.md b/docs/static-analysis/README.md index 8276174..7241fd7 100644 --- a/docs/static-analysis/README.md +++ b/docs/static-analysis/README.md @@ -38,3 +38,16 @@ Independent review of commit [5222d64](https://github.com/gachakra/php-enumex/co The annotation supplies a signature that PHPStan cannot independently verify for this expression. Keep it local to the example; do not weaken the generic contract or suppress unrelated diagnostics. The main README intentionally retains the unannotated PHP syntax. Recheck inference without the annotation when upgrading PHPStan, and remove the workaround once the signature and downstream wrapper type are inferred correctly. See also the [PHPStan first-class callable implementation inspected during the investigation](https://github.com/phpstan/phpstan-src/blob/d8b6eb084efdb3d40df6f93e34bd5affed6bcb43/src/Reflection/InitializerExprTypeResolver.php#L832-L866). + +## Composite type contracts + +The composite check analyses the implementation, executable example and positive consumer fixture together at maximum level: + +```sh +phpstan analyse --level=max --autoload-file=vendor/autoload.php \ + src/EnumComposite.php src/EnumCompositeBuilder.php \ + examples/NativeExtension/Composite/EnumComposite.php docs/static-analysis/composite-positive.php +phpstan analyse --level=max --autoload-file=vendor/autoload.php docs/static-analysis/composite-negative.php +``` + +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. diff --git a/docs/static-analysis/composite-negative.php b/docs/static-analysis/composite-negative.php new file mode 100644 index 0000000..d33bde4 --- /dev/null +++ b/docs/static-analysis/composite-negative.php @@ -0,0 +1,19 @@ +of('Paid'); +$composite->has('Paid'); +$composite->equals(Status::Paid); diff --git a/docs/static-analysis/composite-positive.php b/docs/static-analysis/composite-positive.php new file mode 100644 index 0000000..cb08f4b --- /dev/null +++ b/docs/static-analysis/composite-positive.php @@ -0,0 +1,57 @@ +of(Status::Paid, Role::Admin)); +assertType('Notonza\PhpEnumEx\EnumComposite', Policy::of(Status::Paid, Role::Admin)); +assertType('Notonza\PhpEnumEx\EnumComposite', Policy::as()->of(Status::Paid, Role::Admin)); + +assertType('list', $standard->unwrap()); +assertType('UnitEnum', $standard->at(0)); +assertType('ArrayIterator', $standard->getIterator()); +assertType('Notonza\PhpEnumEx\CompositeOrder', $standard->order()); + +foreach ($standard as $index => $case) { + assertType('int', $index); + assertType('UnitEnum', $case); +} + +assertType('EnumExStaticAnalysisComposite\Status', $custom->status); +assertType('EnumExStaticAnalysisComposite\Role', $custom->role); +assertType('bool', $custom->equals($standard)); diff --git a/src/EnumComposite.php b/src/EnumComposite.php index 4938109..7e7577d 100644 --- a/src/EnumComposite.php +++ b/src/EnumComposite.php @@ -294,6 +294,33 @@ final public function equals(self $other): bool { }; } + /** + * Native PHP serialization is not supported yet, including for subclasses. + * + * Example: + * serialize($route); // throws LogicException + * + * @return array + * @throws LogicException Always. + */ + final public function __serialize(): array { + throw new LogicException( + 'Serialization of EnumComposite is not supported YET', + ); + } + + /** + * Rejects native PHP restoration, which would bypass the construction contract. + * + * @param array $data + * @throws LogicException Always. + */ + final public function __unserialize(array $data): void { + throw new LogicException( + 'Deserialization of EnumComposite is not supported YET', + ); + } + /** * Enum cases are singleton objects. Their object IDs are unique while the input cases are alive. * diff --git a/tests/NativeExtension/EnumCompositeTest.php b/tests/NativeExtension/EnumCompositeTest.php index 2606b2e..d1daee2 100644 --- a/tests/NativeExtension/EnumCompositeTest.php +++ b/tests/NativeExtension/EnumCompositeTest.php @@ -184,6 +184,63 @@ public function testSubclassAndStandardFactories(): void { $this->assertSame(EnumComposite::class, CompositeRoute::as()->of($a, $b)::class); } + #[DataProvider('serializationTargets')] + public function testSerializationIsNotSupported(EnumComposite $composite): void { + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Serialization of EnumComposite is not supported YET'); + + serialize($composite); + } + + public static function serializationTargets(): iterable { + yield 'standard' => [EnumComposite::of(CompositeCountry::Japan)]; + yield 'empty' => [EnumComposite::of()]; + yield 'subclass' => [new CompositeRoute(CompositeCountry::Japan, CompositeCountry::France)]; + } + + #[DataProvider('restorationPayloads')] + public function testDeserializationIsNotSupported(string $payload): void { + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Deserialization of EnumComposite is not supported YET'); + + unserialize($payload); + } + + public static function restorationPayloads(): iterable { + $class = EnumComposite::class; + $orderKey = "\0" . $class . "\0order"; + $casesKey = "\0" . $class . "\0cases"; + + $payload = static fn (string $type, array $properties): string + => sprintf('O:%d:"%s":%s', strlen($type), $type, substr(serialize($properties), 2)); + + yield 'empty properties' => [$payload($class, [])]; + yield 'valid legacy state' => [$payload($class, [ + $orderKey => CompositeOrder::Sensitive, + $casesKey => [CompositeCountry::Japan], + ])]; + yield 'sparse list' => [$payload($class, [ + $orderKey => CompositeOrder::Sensitive, + $casesKey => [1 => CompositeCountry::Japan], + ])]; + yield 'invalid element' => [$payload($class, [ + $orderKey => CompositeOrder::Sensitive, + $casesKey => ['Japan'], + ])]; + + $shared = CompositeCountry::Japan; + yield 'referenced elements' => [$payload($class, [ + $orderKey => CompositeOrder::Sensitive, + $casesKey => [&$shared, &$shared], + ])]; + yield 'subclass' => [$payload(CompositeRoute::class, [ + $orderKey => CompositeOrder::Sensitive, + $casesKey => [CompositeCountry::Japan, CompositeCountry::France], + 'origin' => CompositeCountry::Japan, + 'destination' => CompositeCountry::France, + ])]; + } + public function testInvalidCaseType(): void { $this->expectException(TypeError::class); From 13d4e2ba3353f69f704fa422b7aebcb40df31161 Mon Sep 17 00:00:00 2001 From: Kangin Kim Date: Thu, 3 Dec 2026 04:16:24 +0900 Subject: [PATCH 07/13] Add runnable example of composing enum extensions --- .../Composition/OrderStatusBadge.php | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 examples/NativeExtension/Composition/OrderStatusBadge.php diff --git a/examples/NativeExtension/Composition/OrderStatusBadge.php b/examples/NativeExtension/Composition/OrderStatusBadge.php new file mode 100644 index 0000000..c437c3f --- /dev/null +++ b/examples/NativeExtension/Composition/OrderStatusBadge.php @@ -0,0 +1,59 @@ + */ +final readonly class OrderStatusBadge extends EnumCase { + + public function __construct( + private OrderStatusPresentation $presentation, + ) { + parent::__construct($presentation->unwrap()); + } + + public function label(): string { + return $this->presentation->label(); + } + + public function color(): string { + return match ($this->unwrap()) { + OrderStatus::Pending => 'gray', + OrderStatus::Paid => 'green', + OrderStatus::Shipped => 'blue', + OrderStatus::Cancelled => 'red', + }; + } +} + +$presentation = new OrderStatusPresentation(OrderStatus::Paid, 'ja'); +$english = new OrderStatusPresentation(OrderStatus::Paid, 'en'); + +$badge = new OrderStatusBadge($presentation); +$englishBadge = new OrderStatusBadge($english); + +assert($badge->label() === '支払い済み'); +assert($englishBadge->label() === 'Paid'); +assert($badge->color() === 'green'); +assert($englishBadge->color() === 'green'); +assert($badge->unwrap() === OrderStatus::Paid); +assert($badge->is($presentation)); +assert($badge->is(OrderStatus::Paid)); +assert($badge->is($englishBadge)); +assert($badge->label() !== $englishBadge->label()); + +$pending = new OrderStatusBadge(new OrderStatusPresentation(OrderStatus::Pending, 'ja')); +assert($pending->color() === 'gray'); +assert(!$badge->is($pending)); + +$shipped = new OrderStatusBadge(new OrderStatusPresentation(OrderStatus::Shipped, 'en')); +$cancelled = new OrderStatusBadge(new OrderStatusPresentation(OrderStatus::Cancelled, 'en')); +assert($shipped->color() === 'blue'); +assert($cancelled->color() === 'red'); From ae549a30639e211abbece55793fe0c90bba03d79 Mon Sep 17 00:00:00 2001 From: Kangin Kim Date: Thu, 3 Dec 2026 04:18:45 +0900 Subject: [PATCH 08/13] Reorganize README around use cases and native enum abstractions --- README.md | 314 ++++++++++++++---- ...documentation-and-extension-composition.md | 8 +- 2 files changed, 257 insertions(+), 65 deletions(-) diff --git a/README.md b/README.md index 5a2d0ea..e93b329 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,41 @@ EnumEx (pronounced "enum-E-X", or simply "enum-ex") stands for **Enum Extension**, bringing extra flexibility and expressiveness to PHP enums. -Native enum extensions, reusable enum traits, and [class-based enums](README-ClassBased.md) for PHP >= 8.4. +Native enum extensions, collections, composites, reusable enum traits, and [class-based enums](README-ClassBased.md) for PHP >= 8.4. + +## Table of contents + +- [Quick examples](#quick-examples) + - [Byte units: same enum, different formatting](#byte-units-same-enum-different-formatting) + - [File permissions: same enum, different context](#file-permissions-same-enum-different-context) +- [Requirements and installation](#requirements-and-installation) +- [Choosing an approach](#choosing-an-approach) +- [Working with enums regardless of their type](#working-with-enums-regardless-of-their-type) +- [Useful patterns](#useful-patterns) + - [1. Presentation and context-specific behavior](#1-presentation-and-context-specific-behavior) + - [2. Extend an enum from a third-party library](#2-extend-an-enum-from-a-third-party-library) + - [3. Share and specialize behavior through inheritance](#3-share-and-specialize-behavior-through-inheritance) + - [4. Strategy: vary behavior without changing the enum](#4-strategy-vary-behavior-without-changing-the-enum) + - [5. Reuse and combine existing behaviors](#5-reuse-and-combine-existing-behaviors) + - [6. Decisions based on combinations of enum cases](#6-decisions-based-on-combinations-of-enum-cases) +- [Native Enum Extensions](#native-enum-extensions) + - [Extension contract](#extension-contract) +- [Composing Enum Extensions](#composing-enum-extensions) +- [Native Enum Collections](#native-enum-collections) + - [Selection Operations](#selection-operations) +- [Native Enum Composites](#native-enum-composites) + - [Representing sequences of enum cases](#representing-sequences-of-enum-cases) + - [Order and duplicate policies](#order-and-duplicate-policies) + - [Structural equality](#structural-equality) + - [Membership and access](#membership-and-access) + - [Domain-specific composites](#domain-specific-composites) +- [Native Enum Traits](#native-enum-traits) + - [Working with bit flags](#working-with-bit-flags) + - [Combine library traits with your own traits](#combine-library-traits-with-your-own-traits) +- [Running the native enum examples](#running-the-native-enum-examples) +- [Running examples in Docker](#running-examples-in-docker) +- [Class-based Enums](#class-based-enums) +- [Background](#background) ## Quick examples @@ -161,7 +195,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 v2 release once published; until then use a checkout of the v2 development branch for these examples: +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: ```bash composer require notonza/php-enumex:^2.0 @@ -195,13 +229,26 @@ The `Internal` namespace is not a public API. | Native enum traits | Add common collection, comparison, and debugging operations to enums you own. | | Class-based `Enum` | Maintain existing integrations or model enum-like constant sets that can be extended or overridden through inheritance. | -## Native Enum Extensions +## Working with enums regardless of their type -Prefer native PHP enums for new domain types. Keep behavior intrinsic to the domain in the enum itself when appropriate. Use `EnumCase` when the behavior belongs outside that enum or needs a class-based extension mechanism. +EnumEx lets you work with both pure and backed enums through the same API, without having to distinguish between them. + +For example, given a pure Direction enum with North and a string-backed Currency enum with JPY = 'JPY': -### Useful patterns +```php +use Notonza\PhpEnumEx\EnumCase; -#### 1. Presentation and context-specific behavior +EnumCase::of(Direction::North)->value(); // 'North' +EnumCase::of(Currency::JPY)->value(); // 'JPY' +``` + +A pure case's logical value is its name; a backed case's logical value is its original int or string backing value. The default string conversion uses the logical value. EnumCollection and the EnumCollections trait share the logical-value, lookup, and selection contracts. Native operations such as from() and tryFrom() remain specific to backed enums; the original native type is preserved. + +## Useful patterns + +These examples are organized around application needs rather than library types. The following API sections explain how the underlying abstractions work. + +### 1. Presentation and context-specific behavior Keep presentation concerns out of the domain layer. An order status is a domain concept, but its display label, color, icon, and localization are presentation concerns. Adding them directly to the domain enum would couple it to the needs of the UI. An extension keeps those responsibilities separate without changing the original enum. @@ -273,7 +320,63 @@ $statuses->fromValue('Paid')->value(); // 'Paid' See [Presentation / OrderStatus](https://github.com/gachakra/php-enumex/blob/553c95e735aa88df371a59084cadb263815aba50/examples/NativeExtension/Presentation/OrderStatus.php). -#### 2. Extend an enum from a third-party library +#### Formatting monetary amounts + +Currency formatting is another presentation concern. A string-backed currency enum can retain its logical value while a wrapper supplies a display convention. + +```php +use Notonza\PhpEnumEx\EnumCase; + +enum Currency: string { + case JPY = 'JPY'; + case USD = 'USD'; + case EUR = 'EUR'; +} + +/** @extends EnumCase */ +final readonly class CurrencyFormatter extends EnumCase { + + public static function from(Currency $currency): self { + return new self($currency); + } + + public function symbol(): string { + return match ($this->unwrap()) { + Currency::JPY => '¥', + Currency::USD => '$', + Currency::EUR => '€', + }; + } + + public function format(int|float $amount, bool $grouping = true): string { + $decimals = match ($this->unwrap()) { + Currency::JPY => 0, + Currency::USD, Currency::EUR => 2, + }; + + return $this->symbol() . number_format($amount, $decimals, '.', $grouping ? ',' : ''); + } +} + +$currency = CurrencyFormatter::from(Currency::JPY); + +$currency->value(); // 'JPY' +$currency->symbol(); // '¥' +$currency->format(1234); // '¥1,234' +$currency->format(1234, grouping: false); // '¥1234' + +CurrencyFormatter::from(Currency::USD)->format(1234.5); // '$1,234.50' +CurrencyFormatter::from(Currency::USD)->format(1234.5, grouping: false); // '$1234.50' +CurrencyFormatter::from(Currency::EUR)->format(1234.5); // '€1,234.50' +``` + +The formatter applies the currency's usual number of decimal places with a fixed display convention. Digit grouping is enabled by default and can be disabled with `grouping: false`. It is not locale-aware and does not perform currency conversion. + +See [Backed / Currency](https://github.com/gachakra/php-enumex/blob/553c95e735aa88df371a59084cadb263815aba50/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. + +### 2. Extend an enum from a third-party library Suppose a vendor SDK exposes a `PaymentStatus` enum. Application-specific policies can be added without modifying the SDK or wrapping its values in a second enum definition. @@ -303,7 +406,7 @@ $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). -#### 3. Share and specialize behavior through inheritance +### 3. Share and specialize behavior through inheritance Native enums cannot inherit from other enums or classes. Extension classes can share implementation through an abstract parent and specialize it for distinct enum types. @@ -333,7 +436,7 @@ UserAccess::from(UserPermission::Admin)->canDeleteUser(); // true See [Inheritance / Permission](https://github.com/gachakra/php-enumex/blob/553c95e735aa88df371a59084cadb263815aba50/examples/NativeExtension/Inheritance/Permission.php). -#### 4. Strategy: vary behavior without changing the enum +### 4. Strategy: vary behavior without changing the enum Use a single native enum for weight categories and choose a strategy according to the destination. Each strategy receives the same type of enum case but supplies a different implementation. This example fixes the strategy constructor so the inherited factory can safely instantiate every subclass. If strategies require different constructor arguments, define factories in their concrete classes instead. @@ -456,61 +559,44 @@ All three approaches separate strategy selection from business logic. A factory 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). -#### 5. Backed enum cases +### 5. Reuse and combine existing behaviors -The same `EnumCase` class supports pure and backed enums. `value()` returns the original int/string backing value for backed enums and the case name for pure enums; string conversion uses that logical value by default. +Suppose a localized order-status label already exists, and a badge needs that label together with a badge-specific color. Rather than duplicating translation logic or inheriting from the presentation class, retain the existing presentation object and delegate its behavior. ```php -use Notonza\PhpEnumEx\EnumCase; +$presentation = new OrderStatusPresentation(OrderStatus::Paid, 'ja'); +$badge = new OrderStatusBadge($presentation); -enum Currency: string { - case JPY = 'JPY'; - case USD = 'USD'; - case EUR = 'EUR'; -} +$badge->label(); // '支払い済み' +$badge->color(); // 'green' +$badge->is($presentation); // true +``` -/** @extends EnumCase */ -final readonly class CurrencyFormatter extends EnumCase { +The existing extension is reused without changing native case identity. See [Composing Enum Extensions](#composing-enum-extensions) for the implementation. - public static function from(Currency $currency): self { - return new self($currency); - } +### 6. Decisions based on combinations of enum cases - public function symbol(): string { - return match ($this->unwrap()) { - Currency::JPY => '¥', - Currency::USD => '$', - Currency::EUR => '€', - }; - } - - public function format(int|float $amount, bool $grouping = true): string { - $decimals = match ($this->unwrap()) { - Currency::JPY => 0, - Currency::USD, Currency::EUR => 2, - }; - - return $this->symbol() . number_format($amount, $decimals, '.', $grouping ? ',' : ''); - } -} +Some business rules depend on several independent enumerated conditions. For example, a cancellation policy may depend on both order status and user role. The rules can be expressed as a decision table: -$currency = CurrencyFormatter::from(Currency::JPY); +| Order status | Admin | Guest | +| --- | --- | --- | +| Pending | Allowed | Allowed | +| Paid | Allowed | Denied | -$currency->value(); // 'JPY' -$currency->symbol(); // '¥' -$currency->format(1234); // '¥1,234' -$currency->format(1234, grouping: false); // '¥1234' +```php +$admin = new OrderStatusPolicy(OrderStatus::Paid, UserRole::Admin); +$guest = new OrderStatusPolicy(OrderStatus::Paid, UserRole::Guest); -CurrencyFormatter::from(Currency::USD)->format(1234.5); // '$1,234.50' -CurrencyFormatter::from(Currency::USD)->format(1234.5, grouping: false); // '$1234.50' -CurrencyFormatter::from(Currency::EUR)->format(1234.5); // '€1,234.50' +$admin->canCancel(); // true +$guest->canCancel(); // false +$admin->equals($guest); // false ``` -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. +A native enum method or a policy service is sufficient when only the predicate is needed. A composite is useful when the combination itself must also be carried, compared, or inspected as one value. EnumComposite represents one combination, not the decision table itself. See [Domain-specific composites](#domain-specific-composites) for the implementation. -See [Backed / Currency](https://github.com/gachakra/php-enumex/blob/553c95e735aa88df371a59084cadb263815aba50/examples/NativeExtension/Backed/Currency.php). +## Native Enum Extensions -The [byte unit example](#byte-units-same-enum-different-formatting) above uses the same extension mechanism with integer backing values. +Prefer native PHP enums for new domain types. Keep behavior intrinsic to the domain in the enum itself when appropriate. Use `EnumCase` when the behavior belongs outside that enum or needs a class-based extension mechanism. For a simple method that naturally belongs to an enum you control, prefer an ordinary native enum method. A stateless helper or service may also be simpler than a wrapper when object state, inheritance, and instance-style APIs are not needed. @@ -524,6 +610,51 @@ For a simple method that naturally belongs to an enum you control, prefer an ord - `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`. +## Composing Enum Extensions + +An EnumCase extension can retain another extension and reuse its behavior through delegation. This does not require any additional library API. Reuse the OrderStatus and OrderStatusPresentation definitions from the [presentation example](#1-presentation-and-context-specific-behavior). + +```php +/** @extends EnumCase */ +final readonly class OrderStatusBadge extends EnumCase { + + public function __construct( + private OrderStatusPresentation $presentation, + ) { + parent::__construct($presentation->unwrap()); + } + + public function label(): string { + return $this->presentation->label(); + } + + public function color(): string { + return match ($this->unwrap()) { + OrderStatus::Pending => 'gray', + OrderStatus::Paid => 'green', + }; + } +} + +$presentation = new OrderStatusPresentation(OrderStatus::Paid, 'ja'); + +$badge = new OrderStatusBadge($presentation); + +$badge->label(); // '支払い済み' +$badge->color(); // 'green' + +$badge->is($presentation); // true +$badge->is(OrderStatus::Paid); // true +``` + +The badge retains the presentation object, delegates its localized label and supplies its own color policy. The original native case remains the identity of both extensions. Additional context and wrapper class do not participate in is(). This is explicit composition and delegation, not an automatic wrapper-flattening mechanism. + +Rewrapping a case through unwrap() alone does not retain the previous wrapper. Use explicit composition when the existing extension's state or behavior must remain available. + +See [Composition / OrderStatusBadge](https://github.com/gachakra/php-enumex/blob/13d4e2ba3353f69f704fa422b7aebcb40df31161/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. + ## Native Enum Collections Use `EnumCollection` when you want collection operations on an enum without modifying its definition. The default collection creates standard `EnumCase` wrappers; custom factories preserve the concrete wrapper type in PHPDoc-aware static analysis. @@ -576,7 +707,11 @@ The same selection operations are available as static methods on the native coll ## Native Enum Composites -`EnumComposite` represents several native enum cases as one readonly value. Unlike an EnumCase wrapper's additional context, all retained cases participate in structural comparison. Cases may belong to different enum types or repeat the same type. +`EnumComposite` represents several native enum cases as one readonly value. Unlike an EnumCase wrapper's additional context, all retained cases participate in structural comparison. Cases may belong to different enum types or repeat the same type. A composite is not a collection of every case of one enum type. + +### Representing sequences of enum cases + +A travel route needs both the order and the repeated occurrence of a country: ```php use Notonza\PhpEnumEx\CompositeDuplicates; @@ -599,37 +734,86 @@ $route->at(1); // Country::France count($route); // 3 ``` +### Order and duplicate policies + The default is `CompositeOrder::Sensitive` + `CompositeDuplicates::Preserve`: order matters to `equals()`, and all occurrences are retained. Select other policies before supplying the cases: ```php -$countries = EnumComposite::as( +enum Requirement { + case IdentityVerification; + case AgeVerification; + case AddressVerification; +} + +$defaultRequirements = [ + Requirement::IdentityVerification, + Requirement::AgeVerification, +]; + +$regionalRequirements = [ + Requirement::IdentityVerification, + Requirement::AddressVerification, +]; + +$requirements = EnumComposite::as( CompositeOrder::Insensitive, CompositeDuplicates::Remove, )->of( - Country::Japan, - Country::France, - Country::Japan, + ...$defaultRequirements, + ...$regionalRequirements, ); -$countries->unwrap(); // [Country::Japan, Country::France] -$countries->equalsIgnoringOrder( - EnumComposite::of(Country::France, Country::Japan), -); // true +count($requirements); // 3 +$requirements->has(Requirement::AddressVerification); // true ``` -Both order policies preserve input order in storage and iteration. Duplicate handling is a construction policy: Preserve retains occurrences, Remove retains the first occurrence of each case, and Reject throws InvalidArgumentException if a case is repeated. Duplicate detection uses native case identity, not names or backing values. +When merging requirements, a repeated verification is needed only once, and the order does not affect comparison. Both order policies preserve input order in storage and iteration. Duplicate handling is a construction policy: Preserve retains occurrences, Remove retains the first occurrence of each case, and Reject throws InvalidArgumentException if a case is repeated. Duplicate detection uses native case identity, not names or backing values. + +| Order | Preserve | Remove | Reject | +| --- | --- | --- | --- | +| Sensitive | Sequence | Ordered unique sequence | Ordered unique sequence (validated) | +| Insensitive | Multiset | Set | Set (validated) | + +### Structural equality `equalsExactly()` compares the retained sequence; `equalsIgnoringOrder()` compares multiplicities without order. Both ignore the construction and comparison policies. `equals()` requires the same order policy on both operands and uses the corresponding comparison. Subclass and additional state do not affect these comparisons. +For example, the same countries in a different order have the same multiplicities but are not the same sequence: + +```php +$other = EnumComposite::of( + Country::France, + Country::Japan, + Country::Japan, +); + +$route->equalsExactly($other); // false +$route->equalsIgnoringOrder($other); // true +$route->equals($other); // false + +$unordered = EnumComposite::as(CompositeOrder::Insensitive); +$a = $unordered->of(...$route->unwrap()); +$b = $unordered->of(...$other->unwrap()); + +$a->equals($b); // true +``` + +### Membership and access + Use `has()`, `hasAll()`, and `hasAny()` to check membership. Repeated targets in hasAll() require repeated occurrences. Empty and singleton composites are supported; hasAll() with no targets is true and hasAny() with no targets is false. `at()` throws OutOfBoundsException for a missing zero-based index. Named variadic keys are not retained. Native PHP serialization and deserialization are not supported yet. Both `serialize()` and `unserialize()` throw `LogicException` for EnumComposite and its subclasses. Persist the required domain data explicitly and reconstruct the composite through its normal construction API instead. ### Domain-specific composites -A subclass can name the roles of its components and add behavior. For example, an order status and a user role can form a cancellation policy: +A subclass can name the roles of its components and add behavior. Continuing the [decision table example](#6-decisions-based-on-combinations-of-enum-cases), reuse OrderStatus from the presentation example and define UserRole: ```php +enum UserRole { + case Admin; + case Guest; +} + final readonly class OrderStatusPolicy extends EnumComposite { public function __construct( @@ -655,9 +839,9 @@ final readonly class OrderStatusPolicy extends EnumComposite { } ``` -Use the native cases directly in a match expression when order matters, or use the composite's comparison and membership methods for order-independent decisions. The standard of() and as()->of() factories always create a standard EnumComposite, not a subclass. +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/2c1ff6d5da130e94e021c403c30ba1ae7bc15150/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/13d4e2ba3353f69f704fa422b7aebcb40df31161/examples/NativeExtension/Composite/EnumComposite.php) for runnable examples, including typed subclasses, dynamic requirements and duplicate rejection. ## Native Enum Traits @@ -774,12 +958,14 @@ 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). -### Running the native enum examples +## Running the native enum examples The examples use directory-based `Examples\...` namespaces and are available in the linked source revision, not in the Composer dist archive. To run them, use a Git checkout of the corresponding version and run `composer install` first. Run each script independently with assertions enabled: ```bash php -d zend.assertions=1 examples/NativeExtension/Presentation/OrderStatus.php +php -d zend.assertions=1 examples/NativeExtension/Composition/OrderStatusBadge.php +php -d zend.assertions=1 examples/NativeExtension/Composite/EnumComposite.php php -d zend.assertions=1 examples/NativeExtension/External/PaymentStatus.php php -d zend.assertions=1 examples/NativeExtension/Inheritance/Permission.php php -d zend.assertions=1 examples/NativeExtension/Strategies/AirmailPostage.php diff --git a/docs/adr/0009-documentation-and-extension-composition.md b/docs/adr/0009-documentation-and-extension-composition.md index 7251b65..4f706a9 100644 --- a/docs/adr/0009-documentation-and-extension-composition.md +++ b/docs/adr/0009-documentation-and-extension-composition.md @@ -1,6 +1,6 @@ # ADR 0009: Explain common enum behavior and composition through useful examples -- Status: Proposed (documentation improvement; no library API change) +- Status: Proposed (documentation implemented in PR #17; pending review; no library API change in this ADR) - Date: 2026-12-03 - Related: ADR 0001, 0004, 0006, 0007, 0010 @@ -88,3 +88,9 @@ Do not present this simple predicate as a distinct new benefit merely because it - Verify PHP 8.4/8.5, assertions, static-analysis fixtures, sample links and distribution archive before merging the actual documentation/examples change. The fixed source-revision links currently work; use an existing revision for new sample links and plan tag-based links at an appropriate future release rather than moving v2.0.0. This record proposes documentation and sample changes only. It does not implement or publish them. + +## Documentation implementation candidate + +The owner requested separate top-level chapters for composing extensions and native enum composites, in that order, and a linked table of contents. Useful patterns is now a top-level use-case-oriented chapter, retaining the four existing patterns and adding reuse of behavior through delegation and decisions based on combinations of enum cases. These two patterns show the application need and link to the dedicated implementation chapters. A decision table describes the cancellation rule; EnumComposite represents a single combination rather than a table. + +Working with enums regardless of their type is a separate common-feature section. CurrencyFormatter remains in the presentation pattern with the original example and grouping behavior. The composite chapter explains routes, merged requirements, comparison policies, membership and typed domain subclasses. The runnable Composition/OrderStatusBadge.php example reuses the existing presentation definitions and asserts localized labels, badge colors and native case identity. No new EnumCase API is required. Historical documentation is unchanged. Keep this ADR Proposed until the documentation and sample have been reviewed. From e6cf23b108ef571c17604a77a4e2cc14e55122a8 Mon Sep 17 00:00:00 2001 From: Kangin Kim Date: Thu, 3 Dec 2026 04:31:25 +0900 Subject: [PATCH 09/13] Demonstrate composite construction policies in domain examples --- .../Composite/ConstructionPolicies.php | 180 ++++++++++++++++++ 1 file changed, 180 insertions(+) create mode 100644 examples/NativeExtension/Composite/ConstructionPolicies.php diff --git a/examples/NativeExtension/Composite/ConstructionPolicies.php b/examples/NativeExtension/Composite/ConstructionPolicies.php new file mode 100644 index 0000000..c8052b1 --- /dev/null +++ b/examples/NativeExtension/Composite/ConstructionPolicies.php @@ -0,0 +1,180 @@ +of(...$baseSteps, ...$additionalSteps); + +assert($workflow->unwrap() === [ + WorkflowStep::Prepare, + WorkflowStep::Validate, + WorkflowStep::Publish, +]); + +$reordered = $mergeWorkflow->of( + WorkflowStep::Prepare, + WorkflowStep::Publish, + WorkflowStep::Validate, +); + +assert(!$workflow->equals($reordered)); +assert($workflow->equalsIgnoringOrder($reordered)); + +// Sensitive + Reject: validate an explicitly configured workflow. +// Unlike merging, a repeated step here is a configuration error. + +$validateWorkflow = EnumComposite::as( + CompositeOrder::Sensitive, + CompositeDuplicates::Reject, +); + +$configured = $validateWorkflow->of( + WorkflowStep::Prepare, + WorkflowStep::Validate, + WorkflowStep::Publish, +); + +assert($configured->equals($workflow)); + +try { + $validateWorkflow->of( + WorkflowStep::Prepare, + WorkflowStep::Validate, + WorkflowStep::Prepare, + ); + throw new LogicException('Expected duplicate workflow step rejection'); +} catch (InvalidArgumentException) { + // Report the configuration error rather than silently removing a step. +} + +// The same immutable builder can still be used after rejected input. +assert($validateWorkflow->of(...$baseSteps)->equals(EnumComposite::of(...$baseSteps))); + +// Insensitive + Preserve: compare package contents, including quantities. + +$package = EnumComposite::as( + CompositeOrder::Insensitive, + CompositeDuplicates::Preserve, +); + +$expected = $package->of( + PackageItem::Charger, + PackageItem::Cable, + PackageItem::Cable, +); + +$packed = $package->of( + PackageItem::Cable, + PackageItem::Charger, + PackageItem::Cable, +); + +$missingCable = $package->of( + PackageItem::Charger, + PackageItem::Cable, +); + +assert($expected->equals($packed)); +assert(!$expected->equalsExactly($packed)); +assert(!$expected->equals($missingCable)); +assert($packed->hasAll(PackageItem::Cable, PackageItem::Cable)); +assert(!$packed->hasAll(PackageItem::Cable, PackageItem::Cable, PackageItem::Cable)); +assert(!$packed->has(PackageItem::Adapter)); +assert($packed->at(0) === PackageItem::Cable); + +// Insensitive + Reject: validate a set of configured notification channels. +// Channel order is not part of the configuration's meaning. + +$validateChannels = EnumComposite::as( + CompositeOrder::Insensitive, + CompositeDuplicates::Reject, +); + +$channels = $validateChannels->of( + NotificationChannel::Email, + NotificationChannel::Push, +); + +$sameChannels = $validateChannels->of( + NotificationChannel::Push, + NotificationChannel::Email, +); + +assert($channels->equals($sameChannels)); +assert(!$channels->equalsExactly($sameChannels)); +assert(!$channels->has(NotificationChannel::Sms)); + +try { + $validateChannels->of( + NotificationChannel::Email, + NotificationChannel::Push, + NotificationChannel::Email, + ); + throw new LogicException('Expected duplicate notification channel rejection'); +} catch (InvalidArgumentException) { + // Reject duplicate entries in the explicitly configured channel set. +} + +// Different construction policies can yield the same structural value. + +$mergedChannels = EnumComposite::as( + CompositeOrder::Insensitive, + CompositeDuplicates::Remove, +)->of( + NotificationChannel::Email, + NotificationChannel::Push, + NotificationChannel::Email, +); + +assert($channels->equals($mergedChannels)); + +// An identical sequence with a different order policy is not equal by equals(). +$orderedChannels = EnumComposite::of(...$channels->unwrap()); + +assert(!$channels->equals($orderedChannels)); +assert($channels->equalsExactly($orderedChannels)); +assert($channels->equalsIgnoringOrder($orderedChannels)); From 567951cf6b8a62f3ebbe29a261136bbac341ff5a Mon Sep 17 00:00:00 2001 From: Kangin Kim Date: Thu, 3 Dec 2026 04:31:50 +0900 Subject: [PATCH 10/13] Link composite policy examples from README --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index e93b329..dd71039 100644 --- a/README.md +++ b/README.md @@ -774,6 +774,8 @@ 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. + ### Structural equality `equalsExactly()` compares the retained sequence; `equalsIgnoringOrder()` compares multiplicities without order. Both ignore the construction and comparison policies. `equals()` requires the same order policy on both operands and uses the corresponding comparison. Subclass and additional state do not affect these comparisons. @@ -966,6 +968,7 @@ The examples use directory-based `Examples\...` namespaces and are available in php -d zend.assertions=1 examples/NativeExtension/Presentation/OrderStatus.php php -d zend.assertions=1 examples/NativeExtension/Composition/OrderStatusBadge.php php -d zend.assertions=1 examples/NativeExtension/Composite/EnumComposite.php +php -d zend.assertions=1 examples/NativeExtension/Composite/ConstructionPolicies.php php -d zend.assertions=1 examples/NativeExtension/External/PaymentStatus.php php -d zend.assertions=1 examples/NativeExtension/Inheritance/Permission.php php -d zend.assertions=1 examples/NativeExtension/Strategies/AirmailPostage.php From 1e3c7e2793dd2259049cefd304dff887767281e0 Mon Sep 17 00:00:00 2001 From: Kangin Kim Date: Thu, 3 Dec 2026 04:33:59 +0900 Subject: [PATCH 11/13] Clarify native enum interfaces in common API example --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index dd71039..ac773b2 100644 --- a/README.md +++ b/README.md @@ -231,15 +231,15 @@ The `Internal` namespace is not a public API. ## Working with enums regardless of their type -EnumEx lets you work with both pure and backed enums through the same API, without having to distinguish between them. +EnumEx lets you work with both pure enums (`UnitEnum` only) and backed enums (`BackedEnum`) through the same API, without having to distinguish between them. For example, given a pure Direction enum with North and a string-backed Currency enum with JPY = 'JPY': ```php use Notonza\PhpEnumEx\EnumCase; -EnumCase::of(Direction::North)->value(); // 'North' -EnumCase::of(Currency::JPY)->value(); // 'JPY' +EnumCase::of(Direction::North)->value(); // 'North' (UnitEnum only) +EnumCase::of(Currency::JPY)->value(); // 'JPY' (BackedEnum) ``` A pure case's logical value is its name; a backed case's logical value is its original int or string backing value. The default string conversion uses the logical value. EnumCollection and the EnumCollections trait share the logical-value, lookup, and selection contracts. Native operations such as from() and tryFrom() remain specific to backed enums; the original native type is preserved. From 41518b59be8917e9cb85ab3b53ca06c1473568a6 Mon Sep 17 00:00:00 2001 From: Kangin Kim Date: Thu, 3 Dec 2026 13:07:46 +0900 Subject: [PATCH 12/13] Add empty-state predicates to enum collections and composites --- README.md | 6 +++-- docs/adr/0010-composite-enum-cases.md | 4 +++ .../Collections/FilePermission.php | 10 ++++++++ .../Composite/EnumComposite.php | 9 +++++++ src/EnumCollection.php | 25 +++++++++++++++++++ src/EnumComposite.php | 22 ++++++++++++++++ tests/NativeCollection/EnumCollectionTest.php | 15 +++++++++-- tests/NativeExtension/EnumCompositeTest.php | 12 ++++++++- 8 files changed, 98 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index ac773b2..694acb4 100644 --- a/README.md +++ b/README.md @@ -663,6 +663,8 @@ Continuing the [presentation example](#1-presentation-and-context-specific-behav ```php $statuses->names(); // ['Pending', 'Paid'] +$statuses->isEmpty(); // false +$statuses->isNotEmpty(); // true $statuses->fromName('Paid')->unwrap(); // OrderStatus::Paid $japanese->tryFromName('Unknown'); // null @@ -676,7 +678,7 @@ foreach ($japanese as $name => $presentation) { - 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. - `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()`, `has()`, `hasValue()` and `listDebugOutput()` do not create wrappers. `valueToElement()` follows PHP array-key conversion rules and rejects duplicate resulting keys before invoking the factory. +- `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. - 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. ### Selection Operations @@ -802,7 +804,7 @@ $a->equals($b); // true ### Membership and access -Use `has()`, `hasAll()`, and `hasAny()` to check membership. Repeated targets in hasAll() require repeated occurrences. Empty and singleton composites are supported; hasAll() with no targets is true and hasAny() with no targets is false. `at()` throws OutOfBoundsException for a missing zero-based index. Named variadic keys are not retained. +Use `has()`, `hasAll()`, and `hasAny()` to check membership. Repeated targets in hasAll() require repeated occurrences. Empty and singleton composites are supported. `isEmpty()` and `isNotEmpty()` check whether the composite itself contains any cases. `hasAll()` with no targets is true and `hasAny()` with no targets is false, regardless of whether the composite is empty. `at()` throws OutOfBoundsException for a missing zero-based index. Named variadic keys are not retained. Native PHP serialization and deserialization are not supported yet. Both `serialize()` and `unserialize()` throw `LogicException` for EnumComposite and its subclasses. Persist the required domain data explicitly and reconstruct the composite through its normal construction API instead. diff --git a/docs/adr/0010-composite-enum-cases.md b/docs/adr/0010-composite-enum-cases.md index caa493a..4d1fb73 100644 --- a/docs/adr/0010-composite-enum-cases.md +++ b/docs/adr/0010-composite-enum-cases.md @@ -310,3 +310,7 @@ The owner chose to defer native serialization support. Both __serialize() and __ Future persistence design should be driven by actual use cases. Explicit domain snapshots and JSON encoding are alternatives to native PHP serialization; the snapshot schema, validation and restoration contracts, subclass state, and versioning remain open. Do not redesign EnumCollection factories or the inheritance model merely to accommodate serialization. Existing EnumCase, EnumCollection and Class-based Enum behavior is outside this change. The builder remains a construction helper rather than a persisted value. The ADR remains Proposed pending acceptance of the reviewed implementation. + +## Empty-state predicates (follow-up) + +The owner selected isEmpty() and isNotEmpty() for EnumComposite and EnumCollection. These are complementary predicates on the retained cases and declared native cases, respectively; the collection predicates do not invoke the wrapper factory. Membership is separate from emptiness: hasAny() with no targets is false and hasAll() with no targets is true, even when the composite itself is empty. Static counterparts on the native trait and class-based enum are outside this change. Future immutable operations that add cases may warrant retaining the duplicate policy; the update and equality contracts remain open. diff --git a/examples/NativeExtension/Collections/FilePermission.php b/examples/NativeExtension/Collections/FilePermission.php index a8d1b6c..8a4262d 100644 --- a/examples/NativeExtension/Collections/FilePermission.php +++ b/examples/NativeExtension/Collections/FilePermission.php @@ -9,6 +9,9 @@ use Notonza\PhpEnumEx\EnumCase; use Notonza\PhpEnumEx\EnumCollection; +enum NoPermission { +} + enum FilePermission: int { case READ = 1 << 0; @@ -37,6 +40,13 @@ public function isGranted(): bool { | FilePermission::WRITE->value; $permissions = EnumCollection::of(FilePermission::class); +assert(!$permissions->isEmpty()); +assert($permissions->isNotEmpty()); + +$empty = EnumCollection::of(NoPermission::class); +assert($empty->isEmpty()); +assert(!$empty->isNotEmpty()); + $checks = $permissions->wrapCasesAs( fn (FilePermission $case) => new PermissionCheck($case, $mask), diff --git a/examples/NativeExtension/Composite/EnumComposite.php b/examples/NativeExtension/Composite/EnumComposite.php index 203d293..7348daf 100644 --- a/examples/NativeExtension/Composite/EnumComposite.php +++ b/examples/NativeExtension/Composite/EnumComposite.php @@ -60,6 +60,15 @@ public function canCancel(): bool { assert($route->unwrap() === [Country::Japan, Country::France, Country::Japan]); assert(count($route) === 3); +assert(!$route->isEmpty()); +assert($route->isNotEmpty()); + +$empty = EnumComposite::of(); +assert($empty->isEmpty()); +assert(!$empty->isNotEmpty()); +assert(!$empty->hasAny()); +assert($empty->hasAll()); + assert($route->at(1) === Country::France); assert(iterator_to_array($route) === $route->unwrap()); assert($route->hasAll(Country::Japan, Country::Japan)); diff --git a/src/EnumCollection.php b/src/EnumCollection.php index 616078e..7d162dd 100644 --- a/src/EnumCollection.php +++ b/src/EnumCollection.php @@ -25,6 +25,7 @@ * * Examples below assume App\Currency is an int-backed enum with JPY = 392, USD = 840 and EUR = 978, * and App\Direction is a pure enum with North and South, in that declaration order. + * EmptyEnum is a native enum with no declared cases. * $currencies denotes EnumCollection::of(Currency::class); examples show default wrappers * unless stated otherwise. Wrapper expressions in result comments describe their contents, not object identity. * CurrencyPresentation is a custom EnumCase with a constructor accepting a case and locale. @@ -188,6 +189,30 @@ final public function count(): int { return count($this->cases()); } + /** + * Returns true when the native enum declares no cases. + * Does not invoke the wrapper factory. + * + * Example: + * $currencies->isEmpty(); // false + * EnumCollection::of(EmptyEnum::class)->isEmpty(); // true + */ + final public function isEmpty(): bool { + return $this->cases() === []; + } + + /** + * Returns true when the native enum declares at least one case. + * Does not invoke the wrapper factory. + * + * Example: + * $currencies->isNotEmpty(); // true + * EnumCollection::of(EmptyEnum::class)->isNotEmpty(); // false + */ + final public function isNotEmpty(): bool { + return !$this->isEmpty(); + } + /** * Checks whether the exact case name exists. Non-string inputs return false without coercion. * Does not invoke the wrapper factory. diff --git a/src/EnumComposite.php b/src/EnumComposite.php index 7e7577d..d0fdb58 100644 --- a/src/EnumComposite.php +++ b/src/EnumComposite.php @@ -154,6 +154,28 @@ 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. diff --git a/tests/NativeCollection/EnumCollectionTest.php b/tests/NativeCollection/EnumCollectionTest.php index 43398cc..b84c404 100644 --- a/tests/NativeCollection/EnumCollectionTest.php +++ b/tests/NativeCollection/EnumCollectionTest.php @@ -90,6 +90,8 @@ public function testCollectionAndTraitParity(string $enum): void { $this->assertSame($enum::names(), $collection->names()); $this->assertSame($enum::values(), $collection->values()); $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())); @@ -147,6 +149,8 @@ public function testWrapCasesAsIsImmutableAndLazy(): void { $this->assertNotSame($ja, $en); $this->assertSame(0, $calls); $this->assertSame($base->names(), $ja->names()); + $this->assertFalse($ja->isEmpty()); + $this->assertTrue($ja->isNotEmpty()); $this->assertSame(0, $calls); $this->assertSame(EnumCase::class, $base->fromName('Paid')::class); $this->assertSame('en:Paid', (string) $en->fromName('Paid')); @@ -378,11 +382,18 @@ public function testUnknownNameThrows(): void { EnumCollection::of(PureStatus::class)->fromName('unknown'); } - public function testMissingParentConstructor(): void { + #[DataProvider('metadataOperations')] + public function testMissingParentConstructor(string $method): void { $broken = new readonly class extends EnumCollection { public function __construct() {} }; $this->expectException(LogicException::class); - $broken->count(); + $broken->$method(); + } + + public static function metadataOperations(): iterable { + yield ['count']; + yield ['isEmpty']; + yield ['isNotEmpty']; } } diff --git a/tests/NativeExtension/EnumCompositeTest.php b/tests/NativeExtension/EnumCompositeTest.php index d1daee2..9110695 100644 --- a/tests/NativeExtension/EnumCompositeTest.php +++ b/tests/NativeExtension/EnumCompositeTest.php @@ -147,13 +147,21 @@ public function testEmptySingletonAndNamedVariadicKeys(): void { $this->assertSame([], $empty->unwrap()); $this->assertCount(0, $empty); + $this->assertTrue($empty->isEmpty()); + $this->assertFalse($empty->isNotEmpty()); + $this->assertFalse($empty->hasAny($a)); $this->assertTrue($empty->hasAll()); $this->assertFalse($empty->hasAny()); $this->assertFalse($empty->has($a)); $this->assertFalse($empty->hasAll($a)); $this->assertTrue($empty->equals(EnumComposite::of())); $this->assertFalse($empty->equalsIgnoringOrder(EnumComposite::of($a))); - $this->assertSame([$a], EnumComposite::of($a)->unwrap()); + $singleton = EnumComposite::of($a); + $this->assertSame([$a], $singleton->unwrap()); + $this->assertFalse($singleton->isEmpty()); + $this->assertTrue($singleton->isNotEmpty()); + $this->assertFalse($singleton->hasAny()); + $this->assertTrue($singleton->hasAll()); $this->assertSame([$a], EnumComposite::of(order: $a)->unwrap()); $this->assertSame([$a], EnumComposite::as()->of(duplicates: $a)->unwrap()); } @@ -264,6 +272,8 @@ public static function operations(): iterable { yield ['unwrap', []]; yield ['order', []]; yield ['count', []]; + yield ['isEmpty', []]; + yield ['isNotEmpty', []]; yield ['getIterator', []]; yield ['at', [0]]; yield ['has', [CompositeCountry::Japan]]; From 30c8d24120136249b9a12098f470fe8d1bf3f837 Mon Sep 17 00:00:00 2001 From: Kangin Kim Date: Thu, 3 Dec 2026 13:25:35 +0900 Subject: [PATCH 13/13] Resolve composite review findings and document compatibility boundaries --- README.md | 3 ++- docs/adr/0010-composite-enum-cases.md | 10 +++++++++- docs/static-analysis/README.md | 2 ++ src/EnumComposite.php | 10 ++++++---- 4 files changed, 19 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 694acb4..06be68d 100644 --- a/README.md +++ b/README.md @@ -680,6 +680,7 @@ foreach ($japanese as $name => $presentation) { - `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. - 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. ### Selection Operations @@ -806,7 +807,7 @@ $a->equals($b); // true Use `has()`, `hasAll()`, and `hasAny()` to check membership. Repeated targets in hasAll() require repeated occurrences. Empty and singleton composites are supported. `isEmpty()` and `isNotEmpty()` check whether the composite itself contains any cases. `hasAll()` with no targets is true and `hasAny()` with no targets is false, regardless of whether the composite is empty. `at()` throws OutOfBoundsException for a missing zero-based index. Named variadic keys are not retained. -Native PHP serialization and deserialization are not supported yet. Both `serialize()` and `unserialize()` throw `LogicException` for EnumComposite and its subclasses. Persist the required domain data explicitly and reconstruct the composite through its normal construction API instead. +Native PHP serialization and deserialization are not supported yet. The final `__serialize()` and `__unserialize()` hooks throw `LogicException` for serialization and ordinary object-format restoration of EnumComposite and its subclasses. Subclasses implementing the legacy `Serializable` interface are outside the supported serialization contract: PHP can dispatch legacy `C` records directly to their `unserialize()` method, bypassing the inherited hook. Do not use this interface to persist composites. Persist the required domain data explicitly and reconstruct the composite through its normal construction API instead. ### Domain-specific composites diff --git a/docs/adr/0010-composite-enum-cases.md b/docs/adr/0010-composite-enum-cases.md index 4d1fb73..3a82547 100644 --- a/docs/adr/0010-composite-enum-cases.md +++ b/docs/adr/0010-composite-enum-cases.md @@ -305,7 +305,7 @@ Tests and executable examples accompany the draft. Keep this ADR Proposed until Independent review found that PHP's default native object restoration bypasses the constructor and can populate the private array with sparse keys, non-enum elements or references. The readonly property and its PHPDoc list contract do not independently guarantee these invariants on restoration. -The owner chose to defer native serialization support. Both __serialize() and __unserialize() are final and throw LogicException, including on subclasses. This closes the unsupported restoration path without introducing a persistence contract or silently altering the stored cases. Regression tests cover standard and derived objects, valid-looking legacy state, sparse and invalid lists, and referenced entries. +The owner chose to defer native serialization support. Both __serialize() and __unserialize() are final and throw LogicException, including on subclasses. This closes the ordinary object-format restoration path without introducing a persistence contract or silently altering the stored cases. Regression tests cover standard and derived objects, valid-looking pre-hook object state, sparse and invalid lists, and referenced entries. Future persistence design should be driven by actual use cases. Explicit domain snapshots and JSON encoding are alternatives to native PHP serialization; the snapshot schema, validation and restoration contracts, subclass state, and versioning remain open. Do not redesign EnumCollection factories or the inheritance model merely to accommodate serialization. Existing EnumCase, EnumCollection and Class-based Enum behavior is outside this change. The builder remains a construction helper rather than a persisted value. @@ -314,3 +314,11 @@ The ADR remains Proposed pending acceptance of the reviewed implementation. ## Empty-state predicates (follow-up) The owner selected isEmpty() and isNotEmpty() for EnumComposite and EnumCollection. These are complementary predicates on the retained cases and declared native cases, respectively; the collection predicates do not invoke the wrapper factory. Membership is separate from emptiness: hasAny() with no targets is false and hasAll() with no targets is true, even when the composite itself is empty. Static counterparts on the native trait and class-based enum are outside this change. Future immutable operations that add cases may warrant retaining the duplicate policy; the update and equality contracts remain open. + +## Independent re-review follow-up + +- PHPStan 2.3.7 recognizes the possibility of uninitialized properties when custom serialization hooks are present, even when those hooks always throw. The two now-unused local ignores in unwrap() are removed. The isset() guard, LogicException contract, missing-parent runtime coverage and Composite CI analysis scope remain unchanged. +- The owner approved retaining the final EnumCollection emptiness predicates despite the potential collision with methods declared in downstream subclasses of v2.0.0. This is a real backward-compatibility risk, not a defect in the predicates themselves. Document the migration requirement and account for the incompatibility when selecting the release version; the version is not decided here. No static counterparts are added in this change. +- A subclass that explicitly implements PHP's legacy Serializable interface can restore a legacy C record through its own unserialize() method without invoking the inherited final __unserialize() hook. The owner chose to leave that legacy path outside the supported contract rather than add final public serialize()/unserialize() methods solely to prohibit it. The README and PHPDoc distinguish ordinary object-format rejection from unsupported legacy subclass behavior. No guarantee is made that arbitrary subclass-defined restoration mechanisms are blocked. The existing regression tests continue to cover the supported rejection boundary. + +The ADR remains Proposed pending final review and acceptance. diff --git a/docs/static-analysis/README.md b/docs/static-analysis/README.md index 7241fd7..a325e19 100644 --- a/docs/static-analysis/README.md +++ b/docs/static-analysis/README.md @@ -51,3 +51,5 @@ 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. diff --git a/src/EnumComposite.php b/src/EnumComposite.php index d0fdb58..b8f9e0a 100644 --- a/src/EnumComposite.php +++ b/src/EnumComposite.php @@ -119,8 +119,7 @@ final public static function as( * @return list * @throws LogicException If a subclass did not call the parent constructor. */ - final public function unwrap(): array { // @phpstan-ignore throws.unusedType (Subclasses may omit the parent constructor.) - // @phpstan-ignore isset.initializedProperty (Subclasses may omit the parent constructor.) + final public function unwrap(): array { if (!isset($this->cases)) { throw new LogicException(static::class . ' must call parent::__construct() with native enum cases'); } @@ -317,7 +316,9 @@ final public function equals(self $other): bool { } /** - * Native PHP serialization is not supported yet, including for subclasses. + * Native PHP object serialization is not supported yet. + * The inherited magic hooks reject serialization and object-format restoration. + * Subclasses implementing the legacy Serializable interface are outside this contract. * * Example: * serialize($route); // throws LogicException @@ -332,7 +333,8 @@ final public function __serialize(): array { } /** - * Rejects native PHP restoration, which would bypass the construction contract. + * Rejects native PHP object-format restoration, which would bypass the construction contract. + * Legacy Serializable restoration is outside the supported contract. * * @param array $data * @throws LogicException Always.