phprestserializationsymfonyfosrestbundle

Groups Annotations don't works


Symfony 3.1.7 + FOSRestBundle latest version

<?php
namespace PM\ApiBundle\Controller;

...
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\View\View;

class ArticlesController extends FOSRestController
{
    /**
     * @ApiDoc(
     *  section="articles",
     *  resource=true,
     *  description="Get articles published"
     * )
     * @Rest\View(serializerGroups={"article"})
     * @Rest\Get("/articles")
     */
    public function getArticlesAction(Request $request)
    {
        $articles = $this->getDoctrine()
            ->getManager()
            ->getRepository('PMPlatformBundle:Article')
            ->findAllDateDesc();
        /* @var $articles Article[] */
        return $articles;
    }

Then in my Article entity I added this annotation @Groups({"article"}) with the right use statement.

Whit default serializer I get :

[
    [],
    []
]

Whit JMS serializer (bundle) I get :

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

(I have two articles in db) it seems like the "article" group is not recognized. When I use the default serializer whithout this annotations I get a circular error.

What's wrong ?

[EDIT] Same behavior with

/**
 * @ApiDoc(
 *  section="articles",
 *  resource=true,
 *  description="Get articles published"
 * )
 * @Rest\View()
 * @Rest\Get("/articles")
 */
public function getArticlesAction(Request $request)
{
    $context = new Context();
    $context->addGroup('article');

    $articles = $this->getDoctrine()
        ->getManager()
        ->getRepository('PMPlatformBundle:Article')
        ->findAllDateDesc();
    /* @var $articles Article[] */
    $view = $this->view($articles, 200);
    $view->setContext($context);

    return $view;
} 

The response still empty.


Solution

  • Ok I fixed it using JMS serializer like this :

    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')));
        }
    

    Now the groups annotations works fine.