I cannot override the default handlers in the jms serializer package.
I would like to change the serialization method Symfony\Component\Validator\ConstraintViolationList, so I wrote my own handler. And mark it correctly as described in the documentation (and in various stackoverflow answers).
However, my handler is still overridden by the default handler for the ConstraintViolationList that comes with the JMS Serializer package.
I correctly tagged the handler service. In fact, my handler service is detected and used correctly when I comment on ms_serializer.constraint_violation_handlera service definition fromvendor/jms/serializer-bundle/JMS/SerializerBundle/Resources/config/services.xml
How can I stop the default handler from overriding my user?
I even tried to override the parameter jms_serializer.constraint_violation_handler.classfrom my own package, but still no luck.
Here is my Handler class:
<?php
namespace Coanda\Bridge\JMSSerializer\Handler;
use JMS\Serializer\Context;
use JMS\Serializer\GraphNavigator;
use JMS\Serializer\Handler\SubscribingHandlerInterface;
use JMS\Serializer\JsonSerializationVisitor;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
class ConstraintViolationHandler implements SubscribingHandlerInterface
{
public static function getSubscribingMethods()
{
$methods = [];
$methods[] = [
'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
'type' => ConstraintViolationList::class,
'format' => 'json',
'method' => 'serializeListToJson'
];
return $methods;
}
public function serializeListToJson(
JsonSerializationVisitor $visitor,
ConstraintViolationList $list,
array $type,
Context $context
) {
$violations = [];
foreach ($list as $item) {
$violations[$item->getPropertyPath()][] = $item->getMessage();
}
if (null === $visitor->getRoot()) {
$visitor->setRoot($violations);
}
return $violations;
}
}
I registered it in my services.xml
<service id="coanda.serializer.constraint_violation_handler"
class="Coanda\Bridge\JMSSerializer\Handler\ConstraintViolationHandler">
<tag name="jms_serializer.subscribing_handler"
type="Symfony\Component\Validator\ConstraintViolationList"
direction="serialization" format="json" method="serializeListToJson" />
</service>
source
share