Question

I’m developing an application that inherits abstract classes. These abstract classes have their own mapping for the serializer as shown in the example bellow

Hezten\CoreBundle\Model\Enroled:
    exclusion_policy: ALL

And the abstract class:

<?php

namespace Hezten\CoreBundle\Model;

abstract class Enroled implements EnroledInterface
{
    protected $student;

    protected $subject;

    //Some functions...

}

The class that inherits the previous class looks as follows

<?php

namespace XXX\XXXBundle\Entity;

use JMS\Serializer\Annotation\SerializedName;
use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Exclude;

use Doctrine\ORM\Mapping as ORM;

use Hezten\CoreBundle\Model\Enroled as BaseEnroled;

/** 
 * @ORM\Entity 
 * @ExclusionPolicy("NONE")
 */
class Enroled extends BaseEnroled
{
    /** @ORM\Id  
     *  @ORM\ManyToOne(targetEntity="XXX\XXXBundle\Entity\Student", inversedBy="enroled")
     * @Exclude
     */
    protected $student;

    /** @ORM\Id  
     *  @ORM\ManyToOne(targetEntity="XXX\XXXBundle\Entity\Subject", inversedBy="enroled")
     *  @Exclude
     */
    protected $subject;

    /** @ORM\Column(type="boolean") */
    private $field0;

    /** @ORM\Column(type="boolean") 
     */
    private $field1;

    /** @ORM\Column(type="boolean") */
    private $field2;
 }

The error thrown says this:

Warning: json_encode() [<a href='function.json-encode'>function.json-encode</a>]: recursion detected in C:\xampp\htdocs\Project\vendor\jms\serializer\src\JMS\Serializer\JsonSerializationVisitor.php line 29

For sure, I'm doing something wrong as no entities are exposed, just three fields of "Enroled" entity according to the mappings but I have no clue. I spent a couple of days trying to figure out what's the mistake without success.

What is the proper way to do the mapping of inhertied properties?

Update

Code used to serialize JSON using FOSRestBundle:

    $students = $this->get('hezten_core.manager.enroled')->findEnroledBySubject($subject);

    $view = View::create()
    ->setStatusCode(200)
    ->setFormat('json')
    ->setData($students);

    return $this->get('fos_rest.view_handler')->handle($view);
Was it helpful?

Solution

Finally the API is working... I had to override the metadata of the classes I was inheriting adding the following lines to the config.yml

jms_serializer:
    metadata:
        directories:
            HeztenCoreBundle:
                namespace_prefix: "Hezten\\CoreBundle"
                path: "%kernel.root_dir%/serializer/HeztenCoreBundle"

In the path that is selected above I added one yml file for each Model setting exclusion policy to ALL:

Hezten\CoreBundle\Model\Enroled:
    exclusion_policy: ALL

And I used annotations on the entities that were inheriting those models to expose required info.

I don't know if this is the best approach but works well for me

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top