Skip to content

Instantly share code, notes, and snippets.

@DzeryCZ
Created August 6, 2018 16:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DzeryCZ/7d6c68eacbdc181d767b5999b182d675 to your computer and use it in GitHub Desktop.
Save DzeryCZ/7d6c68eacbdc181d767b5999b182d675 to your computer and use it in GitHub Desktop.
Symfony + FOS Rest + JMS serializer - Serialization handler

Symfony + FOS Rest + JMS serializer - Serialization handler

During building an API service, I encountered with a problem, that I did not want to serve everything as Doctrine Entity object and also, not everything can be converted to json (E.g. Darsyn\IP\Version\Multi)

This issues can be solved by converting one format (used in Doctrine Entity) to wanted format (used in REST API response) We can achieve this via JMS Handlers

To use it you can simply create a Symfony controller

class SalesOrderController extends FOSRestController
{
    public function listAction(): Response
    {
        $allEntities = $this->myRepository->findAll();
        // Let's say one entity is holding info about creation date in \DateTime format, but we want to show it as timestamp.
        $view = $this->view($allEntities, Response::HTTP_OK);

        return $this->handleView($view);
    }
}

And then create and register JMS handler (code below)

<?php
declare(strict_types=1);
namespace MyApp\Infrastructure\Handler;
use JMS\Serializer\Handler\SubscribingHandlerInterface;
use JMS\Serializer\GraphNavigator;
use JMS\Serializer\JsonSerializationVisitor;
use JMS\Serializer\Context;
class DateTimeHandler implements SubscribingHandlerInterface
{
/**
* @return array
*/
public static function getSubscribingMethods()
{
return array(
array(
'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
'format' => 'json',
'type' => \DateTime::class,
'method' => 'serializeDateTimeToJson',
),
);
}
/**
* @param JsonSerializationVisitor $visitor
* @param \DateTime $ipAddress
* @param array $type
* @param Context $context
*
* @return string
*
* @throws \Darsyn\IP\Exception\IpException
* @throws \Darsyn\IP\Exception\WrongVersionException
*/
public function serializeIpAddressToJson(JsonSerializationVisitor $visitor, \DateTime $dateTime, array $type, Context $context)
{
return $dateTime->getTimestamp;
}
}
services:
# Json Serialize handler
MyApp\Infrastructure\Handler\DateTimeHandler:
class: 'MyApp\Infrastructure\Handler\DateTimeHandler'
tags:
- { name: jms_serializer.subscribing_handler }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment