Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JMS serialize bundle @exclude annotation not working

Tags:

php

symfony

My entity FosUserBundle

namespace AppBundle\Entity;

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

use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
use FOS\UserBundle\Model\Group;

/**
 * User
 *
 * @ORM\Table(name="user")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
 * @ExclusionPolicy("all")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     * @Exclude
     */
    protected $id;

    /**
     * @ORM\Column(type="integer")
     */
    private $balance = 0;

But if I try serialize App\Entity\User object:

$this->get('jms_serializer')->serialize($user, 'json');

It returned me ID field!

 {
  "id": 1,
  "username": "admin",
  "username_canonical": "admin",
  "email": "admin",
  "email_canonical": "admin",
  "enabled": true,
  "salt": "o12yxgxp3vkk0w4sck80408w8s8o84s",
  "password": "$2y$13$o12yxgxp3vkk0w4sck804uSVjSMSB1W0qwEjunGTHomBqqoGvkW9G",
  "last_login": "2016-02-28T17:28:19+0300",
  "locked": false,
  "expired": false,
  "roles": [
    "ROLE_ADMIN"
  ],
  "credentials_expired": false
}
like image 431
Rohan Warwar Avatar asked Feb 08 '23 15:02

Rohan Warwar


1 Answers

Because of FOSUserBundle serializer rules, your exclusion strategies will not work.

To make your exclusion used, you need to tell JMSSerializer to squash the FOSUB serialisation.

In your config.yml, add the following:

jms_serializer:
    metadata:
        auto_detection: true # Don't forget this line
        directories:
            FOSUB:
                namespace_prefix: FOS\UserBundle
                path: %kernel.root_dir%/serializer/FOSUB

Then, create the file app/serializer/FOSUB/Model.User.yml and paste the following into:

FOS\UserBundle\Model\User:
    exclusion_policy: ALL

Now, all inherited properties are excluded, you can expose what you want.

Adapt it to your need if you want keep some properties, or redefine them in your entity.

See the corresponding issue #78.

Update

For your not working @Expose annotation, add the auto_detection like in my previous example.

If this doesn't solve the problem, use the @Groups annotation and do something like this :

use JMS\Serializer\Annotation\Groups;

/**
 * @ORM\Column(type="integer")
 * @JMS\Groups({"user"})
 */
private $balance = 0;

Change your controller like this:

use JMS\Serializer\SerializationContext;

$context = SerializationContext::create()->setGroups(array('user'));
$serializer->serialize($user, 'json', $context);

And it should works.

Keep in mind that this problem exists only because your User entity extends a class that already have serializer rules.

like image 77
chalasr Avatar answered Feb 10 '23 10:02

chalasr