Created
August 14, 2017 09:32
-
-
Save Nek-/13537f65d6186c59f6a43ca8470f2907 to your computer and use it in GitHub Desktop.
How to use timestampable entities with api-platform / symfony serializer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace AppBundle\Entity\Doctrine; | |
interface DoctrineExtensionTimestampableInterface | |
{ | |
/** | |
* @return \DateTime | |
*/ | |
public function getCreatedAt(); | |
/** | |
* @return \DateTime | |
*/ | |
public function getUpdatedAt(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
services: | |
app.serializer.normalizer.timestampable: | |
public: false | |
class: AppBundle\Serializer\Normalizer\TimestampableNormalizer | |
arguments: | |
- '@api_platform.serializer.normalizer.item' | |
tags: | |
- { name: serializer.normalizer } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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