From 0c1658be869dcd86c28eb89522d0a52b557d5c0c Mon Sep 17 00:00:00 2001 From: George Steel Date: Tue, 10 Feb 2026 22:31:15 +0000 Subject: [PATCH] Introduce a `Mapped Guesser` There's currently no easy way to avoid adding attributes in order to configure which normalizers to use for which types. This `MappedGuesser` is a trivial Guesser implementation allowing users to specify a map of `Type::class => Normalizer::class` as an alternative to adding attributes to targets --- src/Guesser/MappedGuesser.php | 35 ++++++++++++++++++++++++ tests/Unit/Guesser/MappedGuesserTest.php | 32 ++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 src/Guesser/MappedGuesser.php create mode 100644 tests/Unit/Guesser/MappedGuesserTest.php diff --git a/src/Guesser/MappedGuesser.php b/src/Guesser/MappedGuesser.php new file mode 100644 index 0000000..a36875e --- /dev/null +++ b/src/Guesser/MappedGuesser.php @@ -0,0 +1,35 @@ +> $map */ + public function __construct(private array $map) + { + } + + /** + * @param ObjectType $type + * + * @template T + */ + public function guess(ObjectType $type): Normalizer|null + { + $className = $type->getClassName(); + if (! array_key_exists($className, $this->map)) { + return null; + } + + $normalizerType = $this->map[$className]; + + return new $normalizerType(); + } +} diff --git a/tests/Unit/Guesser/MappedGuesserTest.php b/tests/Unit/Guesser/MappedGuesserTest.php new file mode 100644 index 0000000..42b6f7a --- /dev/null +++ b/tests/Unit/Guesser/MappedGuesserTest.php @@ -0,0 +1,32 @@ +guess(new ObjectType(Email::class))); + } + + public function testTheNormalizerIsOfTheExpectedType(): void + { + $guesser = new MappedGuesser([ + Email::class => EmailNormalizer::class, + ]); + + $normalizer = $guesser->guess(new ObjectType(Email::class)); + + self::assertInstanceOf(EmailNormalizer::class, $normalizer); + } +}