ObjectNormalizer会覆盖RelationshipNormalizer导致代码崩溃,为什么?
问题描述:
我想添加我自己的规范化器,因为我需要将一些原始值转换(反规格化)到它的相关实体。这是我做了什么:ObjectNormalizer会覆盖RelationshipNormalizer导致代码崩溃,为什么?
namespace MMI\IntegrationBundle\Serializer\Normalizer;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class RelationshipNormalizer implements NormalizerInterface, DenormalizerInterface
{
public function normalize($object, $format = null, array $context = [])
{
// @TODO implement this method
}
public function supportsNormalization($data, $format = null): bool
{
return $data instanceof \AgreementType;
}
public function denormalize($data, $class, $format = null, array $context = [])
{
// @TODO implement this method
}
public function supportsDenormalization($data, $type, $format = null): bool
{
$supportedTypes = [
\AgreementType::class => true
];
return isset($supportedTypes[$type]);
}
}
这是我如何使用它从控制器:
$propertyNameConverter = new PropertyNameConverter();
$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer(
null,
$propertyNameConverter,
null,
new ReflectionExtractor()
);
$serializer = new Serializer([
new DateTimeNormalizer(),
new RelationshipNormalizer(),
$normalizer,
new ArrayDenormalizer(),
], [$encoder]);
当代码达到this method:
private function getNormalizer($data, $format, array $context)
{
foreach ($this->normalizers as $normalizer) {
if ($normalizer instanceof NormalizerInterface && $normalizer->supportsNormalization($data, $format, $context)) {
return $normalizer;
}
}
}
使用的Xdebug和IDE我可以看到条件$data instanceof \AgreementType
是如何完成的,但是代码再次尝试检查Normalizer,然后执行this function:
public function supportsDenormalization($data, $type, $format = null)
{
return class_exists($type);
}
而这正是我得到错误的正规化引起以下错误:
Notice: Uninitialized string offset: 0 in vendor/symfony/symfony/src/Symfony/Component/Inflector/Inflector.php at line 179
UPDATE:
我曾经尝试这样做其他方式的结果是完全一样的含义之前同样的错误信息:
$callback = function ($value) {
$value = $this->em->getRepository('QuoteBundle:' . $this->table_mapping[$this->entity])->find($value);
return $value;
};
$entityNormalizer = new GetSetMethodNormalizer();
$entityNormalizer->setCallbacks([
'agreementType' => $callback,
]);
$serializer = new Serializer([
new DateTimeNormalizer(),
$normalizer,
$entityNormalizer,
new ArrayDenormalizer(),
], [$encoder]);
我失踪 这里?
答
在Slack的#symfony-devs频道上获得一些帮助后,我发现该命令很重要。这里是我的问题的解决方案(比较下面的代码段和OP上的代码段,你会看到区别):
$normalizer = new ObjectNormalizer(
null,
$propertyNameConverter,
null,
new ReflectionExtractor()
);
// Notice how ObjectNormalizer() is the last normalizer
$serializer = new Serializer([
new ArrayDenormalizer(),
new DateTimeNormalizer(),
new RelationshipNormalizer($em),
$normalizer,
], [$encoder]);