willdurand / BazingaHateoasBundle

Integration of the Hateoas library into Symfony.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

The links are lost when the serialization groups are used

GuillaumeDoury opened this issue · comments

The links are lost when the serialization groups are used :

    /**
     * @FOSRest\View(serializerGroups={"default"})
     */
    public function cgetAction(){

        /** @var Product[] $products */
        $products = $this->get("api_product.product_service")->getAll();

        return $products;
    }

The links are lost due to the ExclusionManager which skip these links, the workaround which works in my projetc is to not skip these relations when exclusion is nullable

// \Hateoas\Serializer\ExclusionManager.php

    private function shouldSkip($object, Exclusion $exclusion = null, SerializationContext $context)
    {
        // Do not skip links when exclusion is null
        if (is_null($exclusion)) {
            return false;
        }

        if (null !== $exclusion
            && null !== $exclusion->getExcludeIf()
            && $this->expressionEvaluator->evaluate($exclusion->getExcludeIf(), $object)
        ) {
            return true;
        }

        if (!$context->getExclusionStrategy()) {
            return false;
        }

        $propertyMetadata = new RelationPropertyMetadata($exclusion);

        return $context->getExclusionStrategy()->shouldSkipProperty($propertyMetadata, $context);
    }

But I do not have enough global understanding to know if it's a good or a bad workaround. Do you have any idea how this problem can be resolved properly ?

Just had the same problem with Symfony2 bundle,
But without using FosRESTBundle.

I just forgot to set up the exclusion property...

use Hateoas\Configuration\Annotation as Hateoas;

/**
 * @Hateoas\Relation(
 *      "get",
 *      href = @Hateoas\Route(
 *          "any_route_name",
 *          parameters = {
 *              "id" = "expr(object.getId())"
 *          }
 *      ),
 *      exclusion = @Hateoas\Exclusion(groups = {"list", "detail"})
 *  )
 */
class AnyEntity
{
}

Now, this relation will be serialized for the groups "list" and "detail".
(Not sure about this, but is it the behaviour we expect from an exclusion policy ?)

Great, indeed, it makes sense, i missed this part, thanks.