четверг, 27 января 2022 г.

[hateoas] [jms] how to set custom serialization group

 The issue is using Hateoas + JmsSerializerBundle with custom serialization groups don't respond with embedded with needed fields, for me they respond only with {}. The workaround is make \JMS\Serializer\Exclusion\DisjunctExclusionStrategy::shouldSkipProperty() to return with false.

You can make it with custom class, which implements ExclusionStrategyInterface before all standard Strategies in Context like this:

$view->getContext()->addExclusionStrategy(new CustomDisjunctStrategy([]));

That's it, after it it should work (but without links). If you use Sylius bundles, you can use it in overriden ViewHandler like this:

<?php

namespace App\Serializer;


use FOS\RestBundle\View\View;

use FOS\RestBundle\View\ViewHandler as RestViewHandler;

use Sylius\Bundle\ResourceBundle\Controller\RequestConfiguration;

use Sylius\Bundle\ResourceBundle\Controller\ViewHandlerInterface;

use Symfony\Component\HttpFoundation\Response;


final class ViewHandler implements ViewHandlerInterface

{

    /** @var RestViewHandler */

    private $restViewHandler;


    public function __construct(RestViewHandler $restViewHandler)

    {

        $this->restViewHandler = $restViewHandler;

    }


    /**

     * {@inheritdoc}

     */

    public function handle(RequestConfiguration $requestConfiguration, View $view): Response

    {

        if (!$requestConfiguration->isHtmlRequest()) {

            if ($requestConfiguration->getSerializationGroups()) {

                $groups = $requestConfiguration->getSerializationGroups();

                $view->getContext()->addExclusionStrategy(new CustomDisjunctStrategy([]));

            } else {

                $groups = [];

            }

            $this->restViewHandler->setExclusionStrategyGroups($groups);


            if ($version = $requestConfiguration->getSerializationVersion()) {

                $this->restViewHandler->setExclusionStrategyVersion($version);

            }


            $view->getContext()->enableMaxDepth();

        }


        return $this->restViewHandler->handle($view);

    }

}



# services.yaml:

sylius.resource_controller.view_handler:

        class: App\Serializer\ViewHandler

        arguments:

            - "@fos_rest.view_handler"

Комментариев нет:

Отправить комментарий