phpsymfony4jmsserializerbundle

JMS Serializer does not load metadata config in Symfony 4


I have configured JMS Serializer like this:

jms_serializer:
    visitors:
        xml_serialization:
            format_output: '%kernel.debug%'
    metadata:
        auto_detection: true
        directories:
            App:
                namespace_prefix: "App\\Entity"
                path: "%kernel.root_dir%/serializer"

This is how metadata config in src/serializer/SystemUser.yml looks like for entity SystemUser:

App\Entity\Api\Auth\SystemUser:
    exclusion_policy: ALL
    properties:
        id:
            expose: true
        password:
            expose: false
        username:
            expose: true
        email:
            expose: true
        last_login:
            expose: true

I specifically used .yml extension because it is mentioned in the documentation that .yml extension must be used here:

https://jmsyst.com/bundles/JMSSerializerBundle/2.x/configuration#defining-metadata

I have entity in src/Entity/Api/Auth/SystemUser.php that looks like this:

<?php

namespace App\Entity\Api\Auth;

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

/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 */
class SystemUser extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    public function __construct()
    {
        parent::__construct();
        // your own logic
    }
}

But whatever property I exclude in SystemUser.yml file the output does not changes. It displays all properties.

I am using latest Symfony 4.3


Solution

  • Your file src/serializer/SystemUser.yml has a wrong name. With namespace_prefix: "App\Entity" and your SystemUser.php namespace it should be Api.Auth.SystemUser.yml

    This is because your User extends of BaseUser. You need do this:

    jms_serializer.yaml

    jms_serializer:
        metadata:
            auto_detection: true
            directories:
                App:
                    namespace_prefix: 'App\Entity'
                    path: '%kernel.root_dir%/serializer'
                FOSUB:
                    namespace_prefix: 'FOS\UserBundle'
                    path: '%kernel.root_dir%/serializer'
    

    src/serializer/Model.User.yml

    FOS\UserBundle\Model\User:
        exclusion_policy: ALL
        properties:
            id:
                exclude: false
            username:
                exclude: false