3
votes

I have a simple problem but I have no idea how to solve it.

I have a project in Symfony2 with FOSRestBundle + JMSSerializerBundle. In my entities, I've got some datetime fields, and the user should be able to define the format of the datetime retrieved by the API, as you can see :

Input to define the datetime format

My problem is that I don't know how to tell JMSSerializerBundle to use the user-defined format for my datetime fields. Currently I have this :

/**
 * @var \DateTime
 *
 * @ORM\Column(name="custom_date", type="datetime")
 * @Serializer\Type("DateTime<Y-m-d>")
 * @Serializer\Expose
 */
protected $custom_date;

The only way I found is to use the VirtualProperty method from JMSSerializerBundle, but it means that my entity must have a relation with the user. Something like that :

/**
 * @Serializer\VirtualProperty
 * @Serializer\Type("string")
 * @Serializer\SerializedName("custom_date")
 */
public function getVPCustomDate() {
    $format = $this->user->getSetting('date_format');
    return $this->custom_date->format($format);
}

But it wouldn't make sense to do it that way, so I hope you have some alternatives!

Thanks for your time and your help.

1

1 Answers

3
votes

Ok, so I kept searching, and it was really simple (I just had to look in the documentation actually...).

You can create handlers in JMSSerializerBundle for specific type/value.

I added a custom handler for serializing datetime object :

namespace CoreBundle\EventListener;

use Symfony\Component\Security\Core\SecurityContext;
use JMS\Serializer\Handler\SubscribingHandlerInterface;
use JMS\Serializer\GraphNavigator;
use JMS\Serializer\JsonSerializationVisitor;
use JMS\Serializer\Context;

class SerializerHandler implements SubscribingHandlerInterface
{
    private $user;

    public function __construct(SecurityContext $context)
    {
        $this->user = null;

        if (!is_null($context->getToken()) && !is_null($context->getToken()->getUser())) {
            $this->user = $context->getToken()->getUser();
        }
    }

    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)
    {
        if (
            !is_null($this->user) &&
            !is_null($this->user->getClient()) &&
            !is_null($setting = $this->user->getClient()->getSingleSetting('date_format'))
        ) {
            return $date->format($setting->getValue());
        }

        return $date->format('Y-m-d H:i:s');
    }
}

And added it in the services.yml :

core.handler.serializer:
    class: CoreBundle\EventListener\SerializerHandler
    arguments:
        - "@security.context"
    tags:
        - { name: jms_serializer.subscribing_handler }

And that's it. Just simple as that. For more information, you can read about handlers here : http://jmsyst.com/libs/serializer/master/handlers