Skip to content

Instantly share code, notes, and snippets.

@Nek-
Created August 14, 2017 09:32
Show Gist options
  • Save Nek-/13537f65d6186c59f6a43ca8470f2907 to your computer and use it in GitHub Desktop.
Save Nek-/13537f65d6186c59f6a43ca8470f2907 to your computer and use it in GitHub Desktop.
How to use timestampable entities with api-platform / symfony serializer
<?php
namespace AppBundle\Entity\Doctrine;
interface DoctrineExtensionTimestampableInterface
{
/**
* @return \DateTime
*/
public function getCreatedAt();
/**
* @return \DateTime
*/
public function getUpdatedAt();
}
services:
app.serializer.normalizer.timestampable:
public: false
class: AppBundle\Serializer\Normalizer\TimestampableNormalizer
arguments:
- '@api_platform.serializer.normalizer.item'
tags:
- { name: serializer.normalizer }
<?php
namespace AppBundle\Serializer\Normalizer;
use AppBundle\Entity\Doctrine\DoctrineExtensionTimestampableInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class TimestampableNormalizer implements NormalizerInterface
{
/**
* @var NormalizerInterface
*/
private $normalizer;
public function __construct(NormalizerInterface $normalizer)
{
$this->normalizer = $normalizer;
}
/**
* @param DoctrineExtensionTimestampableInterface $object
* @param string $format
* @param array $context
* @return array
*/
public function normalize($object, $format = null, array $context = array())
{
$normalized = $this->normalizer->normalize($object);
$normalized['createdAt'] = $object->getCreatedAt();
$normalized['updatedAt'] = $object->getUpdatedAt();
return $normalized;
}
public function supportsNormalization($data, $format = null)
{
return $data instanceof DoctrineExtensionTimestampableInterface;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment