2323namespace App \Serializer ;
2424
2525use App \Entity \Base \AbstractStructuralDBElement ;
26+ use App \Serializer \APIPlatform \SkippableItemNormalizer ;
2627use Symfony \Component \DependencyInjection \Attribute \Autowire ;
2728use Symfony \Component \Serializer \Normalizer \NormalizerAwareInterface ;
2829use Symfony \Component \Serializer \Normalizer \NormalizerAwareTrait ;
@@ -36,22 +37,34 @@ class StructuralElementNormalizer implements NormalizerInterface, NormalizerAwar
3637{
3738 use NormalizerAwareTrait;
3839
40+ public const ALREADY_CALLED = 'STRUCTURAL_ELEMENT_NORMALIZER_ALREADY_CALLED ' ;
41+
3942 public function supportsNormalization ($ data , ?string $ format = null , array $ context = []): bool
4043 {
4144 //Only normalize if we are doing a file export operation
4245 if (!($ context ['partdb_export ' ] ?? false )) {
4346 return false ;
4447 }
4548
49+ if (isset ($ context [self ::ALREADY_CALLED ]) && in_array ($ data , $ context [self ::ALREADY_CALLED ], true )) {
50+ //If we already handled this object, skip it
51+ return false ;
52+ }
53+
4654 return $ data instanceof AbstractStructuralDBElement;
4755 }
4856
49- public function normalize ($ object , ?string $ format = null , array $ context = []): \ArrayObject |bool |float |int |string
57+ public function normalize ($ object , ?string $ format = null , array $ context = []): \ArrayObject |bool |float |int |string | array
5058 {
5159 if (!$ object instanceof AbstractStructuralDBElement) {
5260 throw new \InvalidArgumentException ('This normalizer only supports AbstractStructural objects! ' );
5361 }
5462
63+ //Avoid infinite recursion by checking if we already handled this object
64+ $ context [self ::ALREADY_CALLED ] = $ context [self ::ALREADY_CALLED ] ?? [];
65+ $ context [SkippableItemNormalizer::DISABLE_ITEM_NORMALIZER ] = true ;
66+ $ context [self ::ALREADY_CALLED ][] = $ object ;
67+
5568 $ data = $ this ->normalizer ->normalize ($ object , $ format , $ context );
5669
5770 //If the data is not an array, we can't do anything with it
@@ -75,7 +88,8 @@ public function normalize($object, ?string $format = null, array $context = []):
7588 public function getSupportedTypes (?string $ format ): array
7689 {
7790 return [
78- AbstractStructuralDBElement::class => true ,
91+ //We cannot cache the result, as it depends on the context
92+ AbstractStructuralDBElement::class => false ,
7993 ];
8094 }
8195}
0 commit comments