File tree Expand file tree Collapse file tree 2 files changed +67
-0
lines changed
Expand file tree Collapse file tree 2 files changed +67
-0
lines changed Original file line number Diff line number Diff line change 1+ <?php
2+
3+ declare (strict_types=1 );
4+
5+ namespace Patchlevel \Hydrator \Guesser ;
6+
7+ use Patchlevel \Hydrator \Normalizer \Normalizer ;
8+ use Symfony \Component \TypeInfo \Type \ObjectType ;
9+
10+ use function array_key_exists ;
11+
12+ final readonly class MappedGuesser implements Guesser
13+ {
14+ /** @param array<class-string, class-string<Normalizer>> $map */
15+ public function __construct (private array $ map )
16+ {
17+ }
18+
19+ /**
20+ * @param ObjectType<T> $type
21+ *
22+ * @template T
23+ */
24+ public function guess (ObjectType $ type ): Normalizer |null
25+ {
26+ $ className = $ type ->getClassName ();
27+ if (! array_key_exists ($ className , $ this ->map )) {
28+ return null ;
29+ }
30+
31+ $ normalizerType = $ this ->map [$ className ];
32+
33+ return new $ normalizerType ();
34+ }
35+ }
Original file line number Diff line number Diff line change 1+ <?php
2+
3+ declare (strict_types=1 );
4+
5+ namespace Patchlevel \Hydrator \Tests \Unit \Guesser ;
6+
7+ use Patchlevel \Hydrator \Guesser \MappedGuesser ;
8+ use Patchlevel \Hydrator \Tests \Unit \Fixture \Email ;
9+ use Patchlevel \Hydrator \Tests \Unit \Fixture \EmailNormalizer ;
10+ use PHPUnit \Framework \TestCase ;
11+ use Symfony \Component \TypeInfo \Type \ObjectType ;
12+
13+ final class MappedGuesserTest extends TestCase
14+ {
15+ public function testTheNormalizerIsNullWhenTheTypeHasNotBeenMapped (): void
16+ {
17+ $ guesser = new MappedGuesser ([]);
18+
19+ self ::assertNull ($ guesser ->guess (new ObjectType (Email::class)));
20+ }
21+
22+ public function testTheNormalizerIsOfTheExpectedType (): void
23+ {
24+ $ guesser = new MappedGuesser ([
25+ Email::class => EmailNormalizer::class,
26+ ]);
27+
28+ $ normalizer = $ guesser ->guess (new ObjectType (Email::class));
29+
30+ self ::assertInstanceOf (EmailNormalizer::class, $ normalizer );
31+ }
32+ }
You can’t perform that action at this time.
0 commit comments