I'm currently trying to serialize a pretty complex object to return it as a response in json with the Symfony Serializer. I got the following object:
/**
* @Doctrine\Entity
* @Doctrine\Table(name="Fichiers")
*/
class Fichier{
/**
* @Doctrine\Column(name="id", type="integer")
* @Doctrine\Id
* @Doctrine\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @Doctrine\OneToOne(targetEntity="Utilisateur")
* @Doctrine\JoinColumn(name="idProprietaire", referencedColumnName="id", nullable=true)
*/
protected $proprietaire;
/**
* @Doctrine\OneToOne(targetEntity="Fichier")
* @Doctrine\JoinColumn(name="idParent", referencedColumnName="id")
*/
protected $parent;
/**
* @Doctrine\Column(name="estDossier", type="boolean")
* @Assert\NotBlank()
*/
protected $estDossier;
/**
* @Doctrine\Column(name="nom", type="string", length=250)
* @Assert\NotBlank()
*/
protected $nom;
/**
* @Doctrine\ManyToMany(targetEntity="Groupe")
* @Doctrine\JoinTable(name="Fichiers_Groupes",
* joinColumns={@Doctrine\JoinColumn(name="idFichier", referencedColumnName="id")},
* inverseJoinColumns={@Doctrine\JoinColumn(name="idGroupe", referencedColumnName="id")}
* )
*/
protected $groupes;
/**
* @Doctrine\Column(name="extension", type="string", length=10)
*/
protected $extension;
/**
* @Doctrine\Column(name="dateCreation", type="datetime")
*/
protected $dateCreation;
/**
* @Doctrine\Column(name="dateModification", type="datetime")
*/
protected $dateModification;
/**
* @Doctrine\Column(name="taille", type="integer")
*/
protected $taille;
And here's my controller code:
$fichier = $this->getDoctrine()->getRepository(Fichier::class)->find($idFichier);
$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer();
$normalizer->setCircularReferenceHandler(function ($object) {
return $object->getId();
});
$serializer = new Serializer(array($normalizer), array($encoder));
$jsonContent = $serializer->serialize($fichier, 'json');
I get the following error:
The property path should not be empty.
After some testing, I found out that if I manually set the null properties of my object, I wouldn't get this error, but another one where it fails at converting it in string. After making this function:
public function __toString()
{
return strval( $this->getId() );
}
I get this error, considering id = 4:
Notice: Undefined variable: 4
Is there any way so that the normalizer handles the null properties and/or to fix this error?