Search code examples
phpsymfonyserializationxml-deserialization

How to deserialize an array of complex objects with Symfony Serializer?


how can I deserialize this XML

<Outer>
   <simpleProperty1>A</simpleProperty1>
   <simpleProperty2>B</simpleProperty2>
   <Inner>
      <simpleProperty3>C</simpleProperty3>
      <simpleProperty4>D</simpleProperty4>
   </Inner>
   <Inner>
      <simpleProperty3>E</simpleProperty3>
      <simpleProperty4>F</simpleProperty4>
   </Inner>
</Outer>

into some PHP classes:

class Outer 
{
   /** @var string */
   private $simpleProperty1;
   /** @var string */
   private $simpleProperty2;
   /** @var Inner[] */
   private $inners;

   [insert getters and setters here]
}

class Inner 
{
   /** @var string */
   private $simpleProperty3;
   /** @var string */
   private $simpleProperty4;

   [insert getters and setters here]
}

using the Symfony Serializer?

The outer object and its simple properties are filled, but instead of the inner object I get an associative array containing two more associative arrays that contain the simpleProperty3 and simpleProperty4.


Solution

  • I was able to solve it with a custom PropertyExtractor that points the serializer to the correct type:

    $encoders = [new XmlEncoder('response', LIBXML_NOERROR)];
    $normalizers = [
        new ArrayDenormalizer(),
        new ObjectNormalizer(null, null, null, 
          new class implements PropertyTypeExtractorInterface
            {
              private $reflectionExtractor;
    
              public function __construct()
              {
                  $this->reflectionExtractor = new ReflectionExtractor();
              }
    
              public function getTypes($class, $property, array $context = array())
              {
                  if (is_a($class, Outer::class, true) && 'Inner' === $property) {
                    return [
                      new Type(Type::BUILTIN_TYPE_OBJECT, true, Inner::class . "[]")
                    ];
                  }
                  return $this->reflectionExtractor->getTypes($class, $property, $context);
              }
            })
        ];
    $this->serializer = new Serializer($normalizers, $encoders);