Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JMSSerializerBundle configuration Metadata #536

Closed
doums opened this issue Dec 6, 2016 · 21 comments
Closed

JMSSerializerBundle configuration Metadata #536

doums opened this issue Dec 6, 2016 · 21 comments
Labels

Comments

@doums
Copy link

doums commented Dec 6, 2016

Symfony 3.1.7 + FOSRestBundle latest version + JMSSerializerBundle latest version

my files :

controller path : /src/PM/ApiBundle/Controller/ArticlesController.php
entity path : /src/PM/PlatformBundle/Entity/Article.php
config file path : /src/PM/PlatformBundle/Resources/config/serializer/Entity.Article.yml

app/config/config.yml

    # JMSSerializer Configuration
    jms_serializer:
        metadata:
            cache: file
            debug: "%kernel.debug%"
            file_cache:
                dir: "%kernel.cache_dir%/serializer"
            #auto_detection: true      I tried this, also doesn't work
            directories:
                PMBundle:
                    namespace_prefix: "PM\\PlatformBundle"
                    path: "@PMPlatformBundle/Resources/config/serializer"
        handlers:
            datetime:
                default_format: "c"
                default_timezone: "UTC"

controller

    <?php
    
    namespace PM\ApiBundle\Controller;
    
    ...
    use FOS\RestBundle\Controller\FOSRestController;
    use FOS\RestBundle\Controller\Annotations as Rest;
    use FOS\RestBundle\View\View;
    use JMS\Serializer\SerializationContext;
    use JMS\Serializer\SerializerBuilder;
    
    
    class ArticlesController extends FOSRestController
    {
        /**
         * @ApiDoc(
         *  section="articles",
         *  resource=true,
         *  description="Get articles published"
         * )
         * @Rest\View()
         * @Rest\Get("/articles")
         */
        public function getArticlesAction(Request $request)
        {
            $serializer = SerializerBuilder::create()->build();
            $articles = $this->getDoctrine()
                ->getManager()
                ->getRepository('PMPlatformBundle:Article')
                ->findAllDateDesc();
            /* @var $articles Article[] */
    
            return $serializer->serialize($articles, 'json', SerializationContext::create()->setGroups(array('article')));
        }

entity

    <?php
    
    namespace PM\PlatformBundle\Entity;
    
    use Doctrine\Common\Collections\ArrayCollection;
    use Doctrine\ORM\Mapping as ORM;
    use Gedmo\Mapping\Annotation as Gedmo;
    use Symfony\Component\Validator\Constraints as Assert;
    use PM\PlatformBundle\Repository\ArticleRepository;
    use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
    use PM\UserBundle\Entity\User;
    
    
    /**
     * Article
     *
     * @ORM\Table(name="article")
     * @ORM\Entity(repositoryClass="PM\PlatformBundle\Repository\ArticleRepository")
     * @UniqueEntity(fields="title", repositoryMethod="findByTitle", message="Un article existe déjà avec ce titre !")
     */
    class Article
    {
        /**
         * @ORM\ManyToMany(targetEntity="PM\UserBundle\Entity\User", inversedBy="liked")
         */
        private $likers;
        ...

config

    PM\PlatformBundle\Entity\Article:
        exclusion_policy: none
        properties:
            likers:
                exclude: true
            likeCount:
                groups: ['article']
            media:
                exclude: true
            comments:
                groups: ['article']
            id:
                groups: ['article']
            title:
                groups: ['article']
            description:
                groups: ['article']
            author:
                exclude: true
            date:
                groups: ['article']
            lastUpate:
                groups: ['article']
            tags:
                groups: ['article']
            slug:
                groups: ['article']

But the rules of this configuration file are not applied because I get this response :

    {
    	"0": {},
    	"1": {},
    	"2": {}
    }

What's wrong ?

Nota: When I use the Groups annotations (directly in the entity) the serializer works perfectly.

@sanderfreshheads
Copy link

@doums Did you ever got it working? I have a similar problem.

@mathieumuller
Copy link

@doums @sanderfreshheads same problem too with the yaml metadata file, it seems the node properties is not working at all... Did you found something?

@ghost
Copy link

ghost commented Jan 4, 2018

Hello,

we detect the same issue on Symfony4, we try to put the configuration of jms directly in the framework.yaml file with this configuration and also in the jms configuration file but with the same result.

jms_serializer:
    visitors:
        xml:
            format_output: '%kernel.debug%'
    metadata:
        directories:
            configuration-database:
                namespace_prefix: "App\\Entity"
                path: "%kernel.root_dir%/../src/Resources/serializer"

JMS don't recognize where to find the yaml entity configuration.

If there isn't any solution where could we start to find a soluton on this issue?

One more thing, all works if I use notation with @ but we don't like this method, we would like to have the configuration file separatly.

Thank you, regards

@paulpascal
Copy link

@acando14 same problem too with the yaml metadata file ! I have create a new jms_serializer.yaml in config/package/ and I am getting even when i put the content(same as yours) in famework.yaml

`There is no extension able to load the configuration for jms_serializer'

Have you got something?
Best regards

@ghost
Copy link

ghost commented Jan 5, 2018

@paulpascal well I don't have this error, i receive, when I try to run my tests JMS\Serializer\Exception\RuntimeException : You must define a type for App\Entity\Database::$projectName.

Where Database is an entity of my project, and projectName a field of the class.

If you want you could use the notations like this

use JMS\Serializer\Annotation\SerializedName;
use JMS\Serializer\Annotation\Type;

class Database
{
    /**
     * @var  string
     * @SerializedName("project_name")
     * @Type("string")
     */
    protected $projectName;
    /**
     * @var  string
     * @SerializedName("database")
     * @Type("string")
     */
    protected $database;
    /**
     * @var  string
     * @SerializedName("host")
     * @Type("string")
     */
    protected $host;
    /**
     * @var  integer
     * @SerializedName("port")
     * @Type("integer")
     */
    protected $port;

and so on....

@goetas
Copy link
Collaborator

goetas commented Jan 5, 2018

@paulpascal

`There is no extension able to load the configuration for jms_serializer'

check if the bundle is loaded in bundles.php or in AppKernel.php

@acando14
If you are using symfony 4, attention that %kernel.root_dir% is changed, probably you need

path: "%kernel.root_dir%/Resources/serializer"

@paulpascal
Copy link

@goetas
Thanks it works! the bundle was not loaded in bundles.php

@leevigraham
Copy link

JMS Serializer looks for .yml files not .yaml if anyone else gets caught.

@ghost
Copy link

ghost commented Jan 11, 2018

@goetas
Yes I know, the new %kernel.root_dir% now is in the src folder, i have a Resources folder inside it with my yml .
But the bundle can't handle it, do you try to use it with symfony 4?

@leevigraham
Yes, I know... I try with 2 formats, but no one works...

Does someone use yml/jms/symfony4 ?

@goetas
Copy link
Collaborator

goetas commented Jan 11, 2018

if %kernel.root_dir% is src, the should be path: "%kernel.root_dir%/Resources/serializer" not path: "%kernel.root_dir%/../Resources/serializer" as you wrote before

@ghost
Copy link

ghost commented Jan 11, 2018

@goetas
in the first post I write

path: "%kernel.root_dir%/../src/Resources/serializer"

it is a bad practise but it is the same of

path: "%kernel.root_dir%/Resources/serializer"

Well I know that is a very bed path 😅 ... sorry...

@samarties
Copy link

samarties commented Jan 31, 2018

I had a similar issue with metadata directories not being registered in Symfony 4. To fix I had to remove the double backslash on the 'namespace_prefix' entries.

namespace_prefix: "PM\\PlatformBundle" should be namespace_prefix: "PM\PlatformBundle"

@onatus
Copy link

onatus commented Mar 15, 2018

What if serializer does not load yml file from bundles Resources?
I have entity in MyBundle\Entity\SubDir\SomeEntity ,
also, I've put serializer yml config file to MyBundle/Resources/config/serializer/Entity.SubDir.SomeEntity.yml .
Jms serializer configs:
jms_serializer:
metadata:
auto_detection: true
directories:
MyBundle:
namespace_prefix: 'MyBundle'
path: "@MyBundle/Resources/config/serializer"

Also, I've tried to change namespace_prefix: used 'Some\Namespace' and ''Some\\Namespace''
Any result.
serialize yml for entity:
MyBundle\Entity\SubDir\SomeEntity:
exclusion_policy: ALL
properties:
name:
expose: true

Additional info: Symfony 3.3, MyBundle is in vendor dir and jms serializer configuration in config/packages/framework.yaml (we use symfony 4 dir structure), I've tried to clear cache with command and manually - no result, got object with all fields.
Bundle loaded in bundles.php, in controller I use $this->get('jms_serializer')
Maybe I've made some stupid mistake, can someone tell me?

@leevigraham
Copy link

@onatus: #536 (comment)

@onatus
Copy link

onatus commented Mar 15, 2018

@leevigraham do you mean that I should use .yml for serialization config file? Because for those files I've used .yml not .yaml

@goetas
Copy link
Collaborator

goetas commented Apr 17, 2018

for some debug strategy, have a look how we found the solution for #650

@silentiumtempus
Copy link

silentiumtempus commented Jun 8, 2018

Same here, Symfony 3.4 + FOSUserBundle.
It just doesn't recognize metadata file

Exception:
You must define a type for FOS\UserBundle\Model\User::$username.

Contents of jms_serializer.yaml

jms_serializer:
    visitors:
        xml:
            format_output: '%kernel.debug%'
    metadata:
      #auto_detection: false
      directories:
        serializer:
          namespace_prefix: 'FOS\\UserBundle'
          path: '%kernel.root_dir%/Resources'

file path from site root: \src\Resources\serializer\Model.User.yml

Contents:

FOS\UserBundle\Model\User:
  properties:
    id:
      type: integer
    username:
      type: string
    usernameCanonical:
      type: string
    email:
      type: string
    emailCanonical:
      type: string
    enabled:
      type: boolean
    salt:
      type: string
    password:
      type: string
    plainPassword:
      type: string

@domagoj03
Copy link

Where does JMS Serializer look for .yml files by default for default Symfony 4 directory structure where all entities are stored in src/Entity directory?

@goetas
Copy link
Collaborator

goetas commented Aug 13, 2018

@domagoj03 There is no default directory, you have to configure it using the jms_serializer.metadata.directories config option.

@sela
Copy link

sela commented Oct 12, 2018

I try something similar to change the serializer of ExceptionHandler. So far in vain. The idea is to overwrite the default by FOS Rest, but I couldn't find how to do it with Symfony 4.

@goetas
Copy link
Collaborator

goetas commented Oct 14, 2018

Please refer to this commit for the updated documentation 6f45a52.

This is a common issue and always was just a typo in the path, namespace (good YAML escaping rules...) or file extension.

If no attempts allowed to find the typo, as ultimate resource, just print the value of $path in AbstractFileDriver.php and everything will be more clear.

If this line gets never invoked, most probably you did not clear the cache in between of config changes, so please clear the cache.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests