Closed
Description
Description
Hi, currently the normalization process looks like this:
- getting a supported normalizer
- call normalization
- if the result is not an empty iterable recursively call normalize again with the array
If I have a custom normalizer, it usually looks like this:
https://symfony.com/doc/current/serializer/custom_normalizer.html#creating-a-new-normalizer
// src/Serializer/TopicNormalizer.php
namespace App\Serializer;
use App\Entity\Topic;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
class TopicNormalizer implements NormalizerInterface
{
private $router;
private $normalizer;
public function __construct(UrlGeneratorInterface $router, ObjectNormalizer $normalizer)
{
$this->router = $router;
$this->normalizer = $normalizer;
}
public function normalize($topic, string $format = null, array $context = [])
{
$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 = [])
{
return $data instanceof Topic;
}
}
The custom normalizer calls an inner normalizer to be able to use ObjectNormalizer and returns an array.
Because the return value is an array the Serializer will iterate on it, but at this point we already done that when we called
$data = $this->normalizer->normalize($topic, $format, $context);
in our custom normalizer.
Maybe we could improve performance if we could skip the iteration and return the array as is. Like adding a value to the context which the serializer could check.
What do you think? Am I missing something?
Example
No response