xDaizu
xDaizu

Reputation: 1061

JMS Serializer: Exclusion Policy of associated entity ignored

Using Symfony2's JMS Serializer I got 2 classes.

This is the class Person:

use JMS\Serializer\Annotation as Serializer;

/**
 * @ORM\Entity(...)
 * @ORM\Table(...)
 * @Serializer\ExclusionPolicy("none")
 */
class Person
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /** @ORM\Column(type="string", nullable=true) */
    private $firstname;
    /**
     * 
     * @ORM\OneToOne(targetEntity="Acme\UserBundle\Entity\FOSUser", cascade={"persist"})
     */
    private $fosuser;
}

And FOSUser:

use FOS\UserBundle\Model\User as BaseUser;
use JMS\Serializer\Annotation as Serializer;

/**
 * Acme\UserBundle\Entity\FOSUser
 *
 * @ORM\Entity(repositoryClass="Acme\UserBundle\Entity\FOSUserRepository")
 * @Serializer\ExclusionPolicy("all")
 */
class FOSUser extends BaseUser
{

    /**
     * @Serializer\Expose
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", nullable=true)
     * */
    protected $fullname;

    /**
     * @ORM\ManyToMany(targetEntity="Educa\UserBundle\Entity\RoleGroup")
     * @Serializer\Exclude
     */
    protected $groups;
}

Then I call:

$serializedResponse = $serializer->serialize( $persons, 'json', SerializationContext::create()->enableMaxDepthChecks() );

What I expect to get is every person serialized and, in it's fosuser field, only the FOSUser's id exposed.

Nevertheless, it exposes every field (e.g. $groups) in the FOSUser object, which contradicts its ExclusionPolicy.

NOTE: Any ADDED field in FOSUser (e.g. "$fullname", which doesn't exist in BaseUser) does get hidden by the annotations @Serializer\Exclude and/or @Serializer\ExclusionPolicy("all")

NOTE2: If I add the @Serializer\Exclude tag to an OVERRIDING field in FOSUser (e.g. $groups) it doesn't hide it.

Upvotes: 1

Views: 2850

Answers (1)

Zandor
Zandor

Reputation: 46

config.yml

jms_serializer:
   metadata:    
    directories:
        FOSUserBundle:
            namespace_prefix: "FOS\\UserBundle"
            path: "@AcmeBundle/Resources/config/serializer"

then in /src/AcmeBundle/Resources/config/serializer/Model.User.yml

FOS\UserBundle\Model\User:
    exclusion_policy: ALL
    properties:
       id:
          expose: true

Upvotes: 2

Related Questions