You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
minor #19532 [Serializer] Fix recursive custom normalizer (mtarld)
This PR was merged into the 7.0 branch.
Discussion
----------
[Serializer] Fix recursive custom normalizer
As mentioned in the following issue: symfony/symfony#53708, the example showing how to create a custom normalizer leads to an infinite recursion.
I could have been fixed like that:
```diff
class TopicNormalizer implements NormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;
+ private const ALREADY_CALLED = self::class.'_already_called';
+
public function __construct(
private UrlGeneratorInterface $router,
) {
}
public function normalize($topic, string $format = null, array $context = []): array
{
+ $context[self::ALREADY_CALLED] = true;
+
$data = $this->normalizer->normalize($topic, $format, $context);
// Here, add, edit, or delete some data:
$data['href']['self'] = $this->router->generate('topic_show', [
'id' => $topic->getId(),
], UrlGeneratorInterface::ABSOLUTE_URL);
return $data;
}
public function supportsNormalization($data, string $format = null, array $context = []): bool
{
+ if ($context[self::ALREADY_CALLED] ?? false) {
+ return false;
+ }
+
return $data instanceof Topic;
}
public function getSupportedTypes(?string $format): array
{
return [
- Topic::class => true,
+ Topic::class => false,
];
}
}
```
But this will prevent the normalizer to be cacheable (because it depends on the context).
Instead, I dropped the use of `NormalizerAwareInterface` and `NormalizerAwareTrait` and used an explicit constructor injection instead.
WDYT?
Commits
-------
56c8b4d [Serializer] Fix recursive custom normalizer
0 commit comments