diff --git a/src/Serializer/Normalizer/AggregateIdNormalizer.php b/src/Serializer/Normalizer/AggregateIdNormalizer.php new file mode 100644 index 000000000..58ee87171 --- /dev/null +++ b/src/Serializer/Normalizer/AggregateIdNormalizer.php @@ -0,0 +1,52 @@ + */ + private readonly string $aggregateIdClass, + ) { + } + + public function normalize(mixed $value): string|null + { + if ($value === null) { + return null; + } + + if (!$value instanceof AggregateRootId) { + throw InvalidArgument::withWrongType($this->aggregateIdClass, $value); + } + + return $value->toString(); + } + + public function denormalize(mixed $value): AggregateRootId|null + { + if ($value === null) { + return null; + } + + if (!is_string($value)) { + throw InvalidArgument::withWrongType('string', $value); + } + + $class = $this->aggregateIdClass; + + return $class::fromString($value); + } +} diff --git a/tests/Unit/Serializer/Normalizer/AggregateIdNormalizerTest.php b/tests/Unit/Serializer/Normalizer/AggregateIdNormalizerTest.php new file mode 100644 index 000000000..40d2165df --- /dev/null +++ b/tests/Unit/Serializer/Normalizer/AggregateIdNormalizerTest.php @@ -0,0 +1,61 @@ +assertEquals(null, $normalizer->normalize(null)); + } + + public function testDenormalizeWithNull(): void + { + $normalizer = new AggregateIdNormalizer(BasicAggregateRootId::class); + $this->assertEquals(null, $normalizer->denormalize(null)); + } + + public function testNormalizeWithInvalidArgument(): void + { + $this->expectException(InvalidArgument::class); + $this->expectExceptionMessage('type "Patchlevel\EventSourcing\Aggregate\BasicAggregateRootId" was expected but "string" was passed.'); + + $normalizer = new AggregateIdNormalizer(BasicAggregateRootId::class); + $normalizer->normalize('foo'); + } + + public function testDenormalizeWithInvalidArgument(): void + { + $this->expectException(InvalidUuidStringException::class); + + $normalizer = new AggregateIdNormalizer(UuidAggregateRootId::class); + $normalizer->denormalize('foo'); + } + + public function testNormalizeWithValue(): void + { + $normalizer = new AggregateIdNormalizer(BasicAggregateRootId::class); + $this->assertEquals('foo', $normalizer->normalize(new BasicAggregateRootId('foo'))); + } + + public function testDenormalizeWithValue(): void + { + $normalizer = new AggregateIdNormalizer(BasicAggregateRootId::class); + $this->assertEquals(new BasicAggregateRootId('foo'), $normalizer->denormalize('foo')); + } +}