Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DateTime custom handler not working #631

Closed
redayoub opened this issue Jan 2, 2018 · 4 comments
Closed

DateTime custom handler not working #631

redayoub opened this issue Jan 2, 2018 · 4 comments

Comments

@redayoub
Copy link

redayoub commented Jan 2, 2018

I'm trying to add a custom handler for DateTime but it's not working. I've tested with other classes and it works.

I'm using the same exact code from the doc.

<?php

namespace AppBundle\Service;

use JMS\Serializer\Handler\SubscribingHandlerInterface;
use JMS\Serializer\GraphNavigator;
use JMS\Serializer\JsonSerializationVisitor;
use JMS\Serializer\Context;

class MyHandler implements SubscribingHandlerInterface
{
    public static function getSubscribingMethods()
    {
        return array(
            array(
                'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
                'format' => 'json',
                'type' => 'DateTime',
                'method' => 'serializeDateTimeToJson',
            ),
        );
    }

    public function serializeDateTimeToJson(JsonSerializationVisitor $visitor, \DateTime $date, array $type, Context $context)
    {
        return $date->format($type['params'][0]);
    }
}
my_handler:
  class: AppBundle\Service\MyHandler
  tags:
    - { name: jms_serializer.handler, type: DateTime, format: json } 
$date = new \DateTime;
$json = $this->get('jms_serializer')->serialize($date, 'json');
@goetas
Copy link
Collaborator

goetas commented Jan 2, 2018

make sure the original date time handler is not enabled

@redayoub
Copy link
Author

redayoub commented Jan 2, 2018

how can I do that, please?

@goetas
Copy link
Collaborator

goetas commented Mar 7, 2018

register your my_handler with higher priority than the jms_serializer.datetime_handler service

@goetas goetas closed this as completed Mar 7, 2018
@piotr-cz
Copy link

Try adding "priority" => -1 like so:

public static function getSubscribingMethods()
{
    return [
        [
            'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
            'format' => 'json',
            'type' => 'DateTime',
            'method' => 'serializeDateTimeToJson',
            'priority' => -1,
        ],
    ];
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants