使用自定义规范化程序修改类属性

时间:2018-03-26 11:00:33

标签: php symfony api-platform.com

我有一个包含2个属性的实体,namephoto。从数据库中读取name属性,但我必须在photo属性中填入一些其他信息。

我已按照文档中的 Writing a Custom Nomalizer 教程进行操作,并制作了自定义规范化器:

<?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);
    }
}

photo属性未填充所需信息。

经过一些调试后,我发现supportsNormalization方法执行了两次(对于每个数据库元素)。如果我打印$data变量,我第一次获得实体name属性,第二次获得photo属性null属性。我从来没有得到整个Style实体。然后,supportsNormalitzation方法始终返回false

如何获取完整的Style实体并修改其属性?

谢谢!

1 个答案:

答案 0 :(得分:0)

尝试将此添加到您的supportsNormalization方法中:

public function supportsNormalization($data, $format = null)
{
    return
        $this->normalizer->supportsNormalization($data, $format)
        && is_object($data) && $data instanceof Style::class
        ;
}