php - Use custom normalizer to modify class properties
I have an entity with 2 properties,name
andphoto
. Thename
property is read from the database but I have to fill thephoto
property with some other information.
I have followed the Writing a Custom Nomalizer tutorial from the docs and I have made my custom normalizer:
<?php
namespace App\Serializer;
use App\Entity\Style;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Vich\UploaderBundle\Templating\Helper\UploaderHelper;
final class StyleNormalizer implements NormalizerInterface, DenormalizerInterface
{
private $normalizer;
private $uploaderHelper;
public function __construct(NormalizerInterface $normalizer, UploaderHelper $uploaderHelper)
{
if (!$normalizer instanceof DenormalizerInterface) {
throw new \InvalidArgumentException('The normalizer must implement the DenormalizerInterface');
}
$this->normalizer = $normalizer;
$this->uploaderHelper = $uploaderHelper;
}
public function denormalize($data, $class, $format = null, array $context = [])
{
return $this->normalizer->denormalize($data, $class, $format, $context);
}
public function supportsDenormalization($data, $type, $format = null)
{
return $this->normalizer->supportsDenormalization($data, $type, $format);
}
public function normalize($object, $format = null, array $context = [])
{
if ($object instanceof Style) {
$object->setPhoto('http://api-platform.com');
}
return $this->normalizer->normalize($object, $format, $context);
}
public function supportsNormalization($data, $format = null)
{
return $this->normalizer->supportsNormalization($data, $format);
}
}
But thephoto
property is not filled with the required information.
After a little bit of debug I have found that thesupportsNormalization
method is executed two times (for each database element). If I print the$data
variable, I got the entityname
property the first time and thephoto
property withnull
value the second time. I never got the entireStyle
entity. Then thesupportsNormalitzation
method always returnsfalse
.
How can I get the fullStyle
entity and modify its properties?
Thanks!
Answer
Solution:
Try to add this to your
supportsNormalization
methods :