Skip to content

Add EnumComposite for structured native enum values - #17

Merged
gachakra merged 13 commits into
mainfrom
feature/enum-composite
Dec 3, 2026
Merged

gachakra merged 13 commits into
mainfrom
feature/enum-composite

Conversation

@gachakra

@gachakra gachakra commented Dec 2, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Introduce an independent readonly EnumComposite, with CompositeOrder and CompositeDuplicates and an immutable as()->of() factory.
  • Preserve native case identity; provide ordered/multiset comparisons, policy-based equality, indexed access, iteration and membership.
  • Add tests for all six policy combinations and edge cases, a runnable example, README documentation and an ADR 0010 implementation follow-up.

Review decisions

  • Default: Sensitive + Preserve; both order policies retain input order. Remove keeps the first occurrence; Reject throws InvalidArgumentException.
  • equals() requires matching order policies; explicit comparisons ignore policy and subclass state. Duplicate handling is construction-only.
  • Empty/singleton values allowed; named variadic keys discarded; hasAll() is multiplicity-aware; missing index throws OutOfBoundsException.
  • Initial access type is UnitEnum, without a heterogeneous generic inference promise; typed domain subclasses are supported. Type-based access and convenience factories are deferred.

Additional reviewed changes

  • Add isEmpty() and isNotEmpty() to EnumComposite and EnumCollection; collection predicates do not invoke wrapper factories.
  • Reject ordinary PHP object serialization and restoration through final magic hooks. Legacy subclass implementations of Serializable are outside the supported contract.
  • Reorganize the README and add executable extension-composition and composite policy examples.

Compatibility and release boundary

  • The new final EnumCollection predicates can conflict with downstream subclass methods. Rename conflicting methods before upgrading. The maintainer approved retaining these APIs; under SemVer this change requires a new major release if shipped unchanged.
  • Merging does not create a release or tag. Release version selection remains a separate maintainer decision.

Verification

gachakra commented Dec 2, 2026

Copy link
Copy Markdown
Owner Author

Independent review of 011e79db99c6adbba236145dd8ccddf6da78c6ee

I recommend resolving the native deserialization contract before accepting ADR 0010 or merging the draft. The independent composite abstraction and the standard factory and equality contracts held in the runtime checks.

Runtime defect

  • [P2] Preserve the list and readonly invariants during deserialization. PHP's native unserialize() can populate $cases directly. Its native array type and the isset() guard allow invalid element types, sparse keys, and referenced entries through. On PHP 8.4 and 8.5, restoring a snapshot with $cases = [1 => Country::Japan] yielded a count of one and an OutOfBoundsException from at(0). A snapshot containing a string returned that string from unwrap() and triggered a TypeError from at(0). A snapshot sharing an element reference with another restored slot changed the composite when that slot was reassigned. Decide explicitly whether to support native serialization. If supported, validate the order and case list on restoration, copy entries by value, and define how subclass state is restored. If deferred, reject native serialization and deserialization explicitly. Add regression coverage for the chosen contract. src/EnumComposite.php:29–30 · src/EnumComposite.php:119–128

Design and optional improvements

  • Order sensitivity governs comparison, while duplicate handling governs input. Sensitive + Preserve is a lossless default. Different order policies define separate equality classes. The explicit sequence and multiset comparisons can span those classes. The identical retained value from Remove, Reject, or Preserve has the same structural meaning. Cross-subclass equality deliberately compares the composite cases and order policy, even when business behavior depends on extra state.
  • The protected constructor gives domain subclasses an explicit contract, and both standard factories consistently return the base class. The builder from as() remained reusable after a rejected build. Its @internal constructor still accepts arbitrary closures at runtime. A direct caller can supply a closure that returns an uninitialized subclass, so the factory guarantees belong to the as() path. Keep the closure constructor outside the documented application API. src/EnumCompositeBuilder.php:10–17
  • [P3, CI coverage] The PHPStan jobs target collection and selection fixtures. Add a focused analysis step for the composite source and a consumer fixture so future changes exercise the list<UnitEnum> contract, iterator types, base-class factory returns, and the two local ignores. The current signatures and ignores passed independent checks. .github/workflows/ci.yml:59–89
  • Optional documentation improvement. Name Sensitive + Preserve in the README and state explicitly that Sensitive makes order significant to equals(). Both policies retain input order in storage and iteration. README.md:602–622

Verification on PHP 8.4.28 and 8.5.13

  • Composer 2.11.3 strict validation, clean lockfile installation, platform requirements, strict PSR-4 autoloading, and linting of 62 PHP files passed. PHPUnit 13.4.8 passed 332 tests and 1,415 assertions per version. All 23 executable examples and the README composite snippets passed with assertions enabled.
  • PHPStan 2.3.7 at maximum level passed the existing fixture checks, composite source, composite example, and positive consumer fixture. The negative consumer fixture produced the four expected argument diagnostics. Full-source analysis matched the base's 16 existing diagnostics. Removing the two local ignores in a scratch copy on PHP 8.5 produced exactly throws.unusedType and isset.initializedProperty, while runtime probes confirmed that subclasses can omit parent initialization.
  • Independent runtime checks covered all six construction policies and 36,100 ordered operand pairs per PHP version, including the equality laws, same-name and same-backing-value cases, named variadics, multiplicity, subclass state, membership, and invalid construction paths. Ordinary serialization round trips, iterator and array copy isolation, and missing parent construction also behaved as tested. The malformed restoration cases reproduced the defect above.
  • The Git archive and both Composer archives matched the 23-file distribution allowlist. The existing source and example edits outside the composite were whitespace-only. Review of the added lines found no credential markers, unintended personal details, absolute local paths, or private host references.

Remaining verification and risk

The exact GitHub-hosted runner, analyzers other than PHPStan, and large-input performance remain unverified. The native restoration path remains the outstanding runtime risk. Eligibility for PHP native serialization should be settled while the API is still proposed.

gachakra commented Dec 3, 2026

Copy link
Copy Markdown
Owner Author

Independent re-review of 41518b59be8917e9cb85ab3b53ca06c1473568a6

Merge recommendation — hold this head. Both hosted PHP jobs fail the new Composite PHPStan check. Before release, resolve the compatibility impact of the new final methods on the existing extensible collection, and bring the subclass deserialization behavior in line with the documented contract.

Findings

  1. [P1, CI failure] Remove the two stale PHPStan ignores and keep the runtime guard. PHPStan 2.3.7 reports ignore.unmatchedIdentifier for throws.unusedType and isset.initializedProperty on both PHP versions. I reproduced this with source alone, with each consumer independently, in the exact CI scope, and with a subclass that omits parent construction. The behavior changed when the serialization hooks were added. PHPStan's MutatingScope::classHasCustomSerialization() detects the presence of either hook and stops carrying constructor-established property initialization into other methods. The heuristic operates even when the hook always throws, so PHPStan now sees the guard and its exception as reachable. In disposable copies, either hook alone kept both underlying diagnostics absent. Removing both hooks restored both diagnostics with the same analysis scope. Removing only the two ignore comments made the CI positive check pass and left the full-source result at the base's 16 known diagnostics. Keep isset(), the @throws LogicException contract, the existing runtime test for missing parent initialization, and the CI analysis scope. src/EnumComposite.php:119–125 · .github/workflows/ci.yml:91–95 · Hosted CI run

  2. [P2, backward compatibility] The new final EnumCollection predicates can stop existing subclass declarations from loading. On both PHP versions, a downstream readonly subclass with its own compatible public function isEmpty(): bool or isNotEmpty(): bool loaded on v2.0.0 and failed at class declaration on this head. Each name independently triggers the fatal error. Preserve the existing extension contract by deferring the instance methods to an approved breaking release or choosing a compatible API placement. Dropping final would permit compatible signatures, while other existing signatures could still conflict. The predicates themselves correctly inspect declared cases without invoking the wrapper factory. src/EnumCollection.php:192–214

  3. [P2, runtime contract] A subclass can still opt into legacy PHP restoration through Serializable. The final magic hooks close the original object-format restoration defect. I confirmed rejection for the base class and ordinary subclasses, including valid-looking state, sparse keys, non-enum elements, and shared references. On both supported PHP versions, a readonly subclass implementing Serializable also restored successfully from a legacy C record. PHP dispatches that format to Serializable::unserialize() and bypasses the inherited __unserialize() hook. This condition requires a subclass that opts into the legacy interface. If the subclass-wide prohibition is the contract, cover that entry point too. An isolated prototype with inherited final legacy serialize() and unserialize(string $data) methods that throw rejected this route on both PHP versions. Add a regression test for the selected boundary. src/EnumComposite.php:319–344 · README.md:807–809 · PHP RFC on legacy Serializable dispatch

Previous review and design checks

  • The ordinary native restoration defect is addressed, subject to the legacy subclass route above. Independent checks confirmed the existing serialization outcomes for EnumCase, EnumCollection and Class-based Enum. The new Composite positive and negative fixtures address the earlier coverage gap in scope. The positive check is blocked by the stale ignores, and the negative fixture independently returned exactly the four expected argument diagnostics. The README now names Sensitive + Preserve explicitly.
  • The six policies, strict case identity, multiplicity-aware comparisons, equality across duplicate-construction histories, standard factory returns, readonly behavior and missing-parent guard held across 36,100 operand pairs per PHP version and targeted runtime probes. The complementary emptiness predicates and the vacuous hasAll()/hasAny() semantics also held. The native trait and class-based empty-state API surfaces were unchanged.
  • The README organizes the patterns by use case, demonstrates existing EnumCase behavior reuse through delegation, and keeps a composite value distinct from the decision table. The pure/backed logical-value examples match the implementation. An optional clarification is to state explicitly that BackedEnum extends UnitEnum. The new examples collectively demonstrate all six policy combinations with appropriate use cases. The historical Class-based README is unchanged. README.md:232–245 · PHP BackedEnum manual

Verification and remaining risk

  • On PHP 8.4.28 and 8.5.13, Composer strict validation, clean lockfile installation, platform requirements, strict PSR-4 autoloading and lint of 64 PHP files passed. PHPUnit 13.4.8 passed 345 tests and 1,458 assertions per version. All 25 executable examples passed with assertions enabled. All 31 README PHP blocks ran in 15 grouped fixtures with omitted application definitions supplied from the linked examples or as stated in the README. Local anchors, relative links and all 15 pinned example links resolved.
  • PHPStan 2.3.7 maximum-level collection and selection checks passed against their expected baselines. The exact committed Composite positive command failed on the two unmatched ignores. The scratch verification above confirms the proposed static-analysis fix without changing the runtime behavior.
  • Git and both Composer archives matched the 23-file distribution allowlist. I checked formatting against the project guide and ran git diff --check. Review of the added diff found no credential markers, unintended personal details, local absolute paths or private host references.
  • The hosted workflow stopped before PHPUnit, examples and archive validation. Those steps were verified locally. Alternate analyzers, large-input performance and the prevalence of method-name collisions in downstream projects remain unverified.

gachakra commented Dec 3, 2026

Copy link
Copy Markdown
Owner Author

Independent re-review of 30c8d24120136249b9a12098f470fe8d1bf3f837

Merge recommendation — ready to merge as work for a breaking release. I found no new implementation defect. The retained EnumCollection subclass incompatibility still prevents a backward-compatible 2.x release of this head. The release version remains an explicit maintainer decision.

Prior findings

  • P1, CI failure — resolved. The two unused PHPStan ignores are gone. The initialization guard, its LogicException contract, and CI analysis scope are intact. PHPStan 2.3.7 passed the exact source-plus-example-plus-consumer command on both PHP versions. The negative fixture reported exactly its four intended argument-type diagnostics. Full-source analysis had the same 16 pre-existing diagnostics as the base after accounting for shifted lines in EnumCollection. src/EnumComposite.php:119–127 · Hosted CI
  • P2, legacy deserialization — addressed by clarifying the supported contract. I confirmed that serialization and ordinary PHP object-format restoration reject standard and derived composites, including sparse keys, invalid elements, and shared references. A subclass that implements Serializable can still restore its own legacy C record on both PHP versions. The README, PHPDoc, and ADR now describe that path consistently as outside the supported contract. Existing EnumCase, EnumCollection and Class-based Enum serialization behavior matched the previous review. README.md:810 · src/EnumComposite.php:318–346
  • P2, EnumCollection subclass compatibility — retained and documented. I reran separate fixtures for the two method names against v2.0.0 and this head. A compatible downstream method for either name loads on v2.0.0 and fails at class declaration with the new final method. ADR 0010 records maintainer approval to retain the methods, and the README gives a migration instruction. If the implementation ships unchanged under SemVer, use a new major version and include the migration note in the release notes. A 2.x tag would remain eligible for Composer consumers on ^2.0.0. src/EnumCollection.php:192–214 · README.md:683 · ADR 0010:321–322 · Semantic Versioning · Composer version constraints

Optional follow-up before release handoff. Update the PR summary's statement that existing runtime APIs are unchanged to disclose the EnumCollection subclass impact.

Verification

  • The complete hosted CI matrix passed. In independent containers on PHP 8.4.28 and 8.5.13, Composer validation, platform requirements, strict PSR-4 autoloading, lint of 64 PHP files, PHPUnit 345 tests and 1,458 assertions per version, all 25 assertion-enabled examples, and 31 README PHP blocks grouped into 15 fixtures passed. The local Composer run reused the lockfile-matched vendor tree, while the hosted workflow ran dependency installation on fresh runners.
  • Independent runtime checks covered all six policies, 36,100 ordered operand pairs per version, factory and subclass behavior, empty-state and membership contracts, readonly behavior, and both serialization paths discussed above. The Git and Composer archives matched the 23-file allowlist. README internal and pinned example links resolved. The diff passed whitespace checks, and the added lines showed no credential, personal-data, local-path, or private-network markers.
  • The release version, prevalence of downstream method collisions, analyzers other than PHPStan, and large-input performance remain unverified.

@gachakra
gachakra marked this pull request as ready for review December 3, 2026 04:38
@gachakra
gachakra merged commit e0169a6 into main Dec 3, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant