Commit 9286310
committed
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 normalizer1 file changed
+7
-7
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
12 | 12 | | |
13 | 13 | | |
14 | 14 | | |
15 | | - | |
16 | | - | |
| 15 | + | |
| 16 | + | |
17 | 17 | | |
18 | 18 | | |
19 | 19 | | |
20 | 20 | | |
21 | 21 | | |
22 | 22 | | |
23 | 23 | | |
| 24 | + | |
24 | 25 | | |
25 | | - | |
26 | | - | |
27 | 26 | | |
28 | 27 | | |
29 | | - | |
| 28 | + | |
30 | 29 | | |
31 | | - | |
32 | | - | |
33 | 30 | | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
34 | 34 | | |
35 | 35 | | |
36 | 36 | | |
| |||
0 commit comments