Add TransformerRegistry for global type-based casters and serializers#110
Merged
Conversation
Introduces PhpCollective\Dto\Transformer\TransformerRegistry so that casters (array -> object) and serializers (object -> array/scalar) can be registered once per type and apply automatically to every DTO field whose declared type matches, instead of repeating per-field factory / serialize metadata across many fields. Lookups match the exact type first, then walk parent classes and interfaces. Per-field factory and serialize always win over the registry. When any entry is registered, generated DTOs fall back from the optimized fast path to the reflective path so the registry is always consulted. Includes tests covering caster hit, serializer hit, factory precedence, inheritance matching, removal/clear, and backslash normalization, plus an updated Custom Casters guide and runtime API reference.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #110 +/- ##
============================================
+ Coverage 82.66% 82.80% +0.13%
- Complexity 1500 1530 +30
============================================
Files 42 43 +1
Lines 3703 3756 +53
============================================
+ Hits 3061 3110 +49
- Misses 642 646 +4 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Introduces
PhpCollective\Dto\Transformer\TransformerRegistryso that casters (array → object) and serializers (object → array/scalar) can be registered once per type and apply automatically to every DTO field whose declared type matches.Today, transforming a common value object like
DateTimeImmutable,Money, or a framework-specificDateTimewrapper requires repeatingfactory="..."/serialize="..."on every field of that type across every DTO schema. This PR adds a global registry so the mapping is declared once during bootstrap.Every DTO field declared as
\DateTimeImmutable(and every output of a\DateTimeInterface) is now transformed automatically.Behaviour
Precedence —
fromArray:serialize: 'FromArrayToArray'/'array'per fieldfactory(wins over registry)TransformerRegistry::findCaster()← newnew $type($value))Precedence —
toArray:toArray()serialize(wins over registry)TransformerRegistry::findSerializer()← newExplicit schema configuration always wins — the registry only fills in the
createWithConstructorfallback on input and the pass-through branch on output.Inheritance matching: exact class-name match first, then the first registered parent class or interface that
is_a/instanceofmatches. Register the most specific type you care about; interfaces act as a convenient catch-all (e.g. register once forDateTimeInterfaceto cover bothDateTimeandDateTimeImmutable).Fast-path interaction: when any entry is registered, generated DTOs bypass the
HAS_FAST_PATHoptimisation (setFromArrayFast/toArrayFast) and fall back to the reflective path, guaranteeing the registry is consulted. The check is a cheap$casters !== [] || $serializers !== []. No entries registered → zero overhead, fast path is unchanged.API
addCaster(string \$type, callable \$caster)addSerializer(string \$type, callable \$serializer)removeCaster(string \$type)removeSerializer(string \$type)hasCaster(string \$type): boolhasSerializer(string \$type): boolfindCaster(string \$type): ?callablefindSerializer(object \$value): ?callablehasAny(): boolclear()Changes
src/Transformer/TransformerRegistry.php— new class.src/Dto/Dto.php— hook caster intosetFromArraybefore thecreateWithConstructorfallback, hook serializer into_toArrayInternalas an else-branch after the per-fieldserializeand enum checks, and gate theHAS_FAST_PATHshortcut on!TransformerRegistry::hasAny().tests/Dto/DtoTest.php— 7 new tests covering caster hit, serializer hit, factory precedence, inheritance matching (negative + positive), remove/clear, and leading-backslash normalisation.tearDown()also clears the registry.docs/guide/custom-casters.md— new "Global Type-Based Transformers" section with precedence rules, inheritance behaviour, CakePHP/Laravel bootstrap examples, testing guidance, and API reference.docs/guide/runtime-api.md— added aTransformerRegistrysection and updated the "Resetting Global Runtime State" snippet.Full DtoTest suite: 137/137 passing, CS clean. PHPStan errors are unchanged (pre-existing
JsonSchemaoptional dependency), unrelated to this PR.