Skip to content

Instantly share code, notes, and snippets.

@benlac
Forked from Epskampie/EntityNormalizer.php
Created April 13, 2020 21:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benlac/c9efc733ee16ebd0d438119bcccb92b9 to your computer and use it in GitHub Desktop.
Save benlac/c9efc733ee16ebd0d438119bcccb92b9 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]
@patrick-suffren
Copy link

patrick-suffren commented Dec 30, 2023

Symfony 6.3+ compatibility

Implementing the getSupportedTypes method is necessary to make this class compatible with Symfony 6.3 and above.
Additionally, if you're using the default services. Yaml configuration, registration as a service is done automatically!

<?php 
declare (strict_types = 1);

namespace App\Normalizer;

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;

/**
 * Entity normalizer
 *  @see  : https://gist.github.com/benlac/c9efc733ee16ebd0d438119bcccb92b9
 */
class EntityNormalizer implements DenormalizerInterface 
{
    public function __construct(
        protected EntityManagerInterface $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);
    }

    /**
     * @inheritDoc
     */
    public function getSupportedTypes(?string $format): array
    {
        return [
            'object' => true,             // support any classes or interfaces
            '*' => true,                 // Supports any other types
        ];
    }
}

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