我正在尝试添加我自己的规范化器,因为我需要将一些原始值转换(非规范化)到它的相关实体。这就是我所做的:
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]);
当代码到达此方法时:
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,然后执行此函数:
public function supportsDenormalization($data, $type, $format = null)
{
return class_exists($type);
}
这正是我得到错误归一化器导致以下错误的地方:
注意:未初始化的字符串偏移量:0 in vendor/symfony/symfony/src/Symfony/Component/Inflector/Inflector.php 第 179 行
更新:
我已经尝试过这种其他方式,结果与之前完全相同,意味着相同的错误消息:
$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]);
我在这里缺少什么?