Skip to content

Instantly share code, notes, and snippets.

@Epskampie
Last active October 14, 2022 12:24
Show Gist options
  • Save Epskampie/5230f201d22d76bbd6b0db6f07692ba7 to your computer and use it in GitHub Desktop.
Save Epskampie/5230f201d22d76bbd6b0db6f07692ba7 to your computer and use it in GitHub Desktop.
Automatically deserialize doctrine entities when using Symfony Serializer
<?php declare (strict_types = 1);
namespace App\Normalizer;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
/**
* Entity normalizer
*/
class EntityNormalizer implements DenormalizerInterface
{
/** @var EntityManagerInterface **/
protected $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
/**
* @inheritDoc
*/
public function supportsDenormalization($data, $type, $format = null)
{
return strpos($type, 'App\\Entity\\') === 0 && (is_numeric($data));
}
/**
* @inheritDoc
*/
public function denormalize($data, $class, $format = null, array $context = [])
{
return $this->em->find($class, $data);
}
}
services:
App\Normalizer\EntityNormalizer:
public: false
autowire: true
autoconfigure: true
tags: [serializer.normalizer]
@carlospauluk
Copy link

Thanks!!! Works great!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment