|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace GoodPhp\Serialization\Serializer\Registry\Cache; |
| 4 | + |
| 5 | +use Ds\Map; |
| 6 | +use GoodPhp\Reflection\Reflection\Attributes\ArrayAttributes; |
| 7 | +use GoodPhp\Reflection\Reflection\Attributes\Attributes; |
| 8 | +use GoodPhp\Reflection\Type\Type; |
| 9 | +use GoodPhp\Serialization\Serializer; |
| 10 | +use GoodPhp\Serialization\Serializer\Registry\TypeAdapterRegistry; |
| 11 | +use GoodPhp\Serialization\TypeAdapter\TypeAdapter; |
| 12 | +use GoodPhp\Serialization\TypeAdapter\TypeAdapterFactory; |
| 13 | +use Illuminate\Support\Arr; |
| 14 | + |
| 15 | +final class MemoizingTypeAdapterRegistry implements TypeAdapterRegistry |
| 16 | +{ |
| 17 | + /** @var array<class-string, array<>> */ |
| 18 | + private array $resolved = []; |
| 19 | + |
| 20 | + public function __construct( |
| 21 | + private readonly TypeAdapterRegistry $delegate, |
| 22 | + ) { |
| 23 | + } |
| 24 | + |
| 25 | + public function forType(string $typeAdapterType, Serializer $serializer, Type $type, Attributes $attributes = new ArrayAttributes(), TypeAdapterFactory $skipPast = null): TypeAdapter |
| 26 | + { |
| 27 | + $this->resolved[$typeAdapterType][(string) $type] ??= new \WeakMap(); |
| 28 | + |
| 29 | + $matchingFactories = $this->resolved[$typeAdapterType][(string) $type][$skipPast ?? $serializer] ??= []; |
| 30 | + |
| 31 | + $attributesFactoryPair = Arr::first($matchingFactories, fn (array $pair) => $attributes->allEqual($pair[0])); |
| 32 | + |
| 33 | + if ($attributesFactoryPair) { |
| 34 | + return $attributesFactoryPair[1]; |
| 35 | + } |
| 36 | + |
| 37 | + $factory = $this->delegate->forType($typeAdapterType, $serializer, $type, $attributes, $skipPast); |
| 38 | + |
| 39 | + $this->resolved[$typeAdapterType][(string) $type][$skipPast ?? $serializer][] = [$attributes, $factory]; |
| 40 | + |
| 41 | + return $factory; |
| 42 | + } |
| 43 | +} |
0 commit comments