Custom Handler on JMSSerializerBundle Ignored

I am trying to use a special handler for the JMS Serializer Bundle

class CustomHandler implements SubscribingHandlerInterface { public static function getSubscribingMethods() { return array( array( 'direction' => GraphNavigator::DIRECTION_SERIALIZATION, 'format' => 'json', 'type' => 'integer', 'method' => 'serializeIntToJson', ), ); } public function serializeIntToJson(JsonSerializationVisitor $visitor, $int, array $type, Context $context) { die("GIVE ME SOMETHING"); } } 

It does nothing and does not die. This is how I register the handler

 $serializer = SerializerBuilder::create() ->configureHandlers(function(HandlerRegistry $registry) { $registry->registerSubscribingHandler(new MyHandler()); }) ->addDefaultHandlers() ->build(); $json = $serializer->serialize($obj, 'json'); 

My handler is never called, and I cannot manipulate serialization data.

+6
source share
2 answers

I have this one that works

  $serializer = SerializerBuilder::create() ->configureListeners(function(EventDispatcher $dispatcher) { $dispatcher->addSubscriber(new ProjectSubscriber($this->container)); $dispatcher->addSubscriber(new UserSubscriber($this->container)); }) ->addDefaultListeners() ->addMetadataDir(realpath($this->get('kernel')->getRootDir()."/../") . '/src/Jake/NameOfBundle/Resources/config/serializer') ->build(); return $serializer->serialize($project, 'json'); 

$project is my essence.

You can skip this line if you do not have serializer configurations.

 ->addMetadataDir(realpath($this->get('kernel')->getRootDir()."/../") . '/src/Jake/NameOfBundle/Resources/config/serializer') 

I think my main problem was this ->addDefaultListeners() .

In config.yml I have

 jms_serializer: metadata: auto_detection: true directories: NameOfBundle: namespace_prefix: "" path: "@JakeNameOfBundle/Resources/config/serializer" 

I have nothing to create a JMS service.

+2
source

You need to create a service for this handler:

 custom_jms_handler: class: MyBundle\Serializer\CustomHandler tags: - { name: jms_serializer.subscribing_handler } 

Then make sure you are using the registered JMS serializer service

 $json = $this->get('jms_serializer')->serialize($obj, 'json'); 
+4
source

Source: https://habr.com/ru/post/979590/


All Articles