Skip to content

Commit

Permalink
added fields exclusion strategy
Browse files Browse the repository at this point in the history
  • Loading branch information
maikrosenthal authored and mamazu committed Aug 15, 2023
1 parent a68e0de commit 26ec420
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

declare(strict_types=1);

namespace Sulu\Bundle\CoreBundle\Serializer\Exclusion;

use JMS\Serializer\Context;
use JMS\Serializer\Exclusion\ExclusionStrategyInterface;
use JMS\Serializer\Metadata\ClassMetadata;
use JMS\Serializer\Metadata\PropertyMetadata;

class FieldsExclusionStrategy implements ExclusionStrategyInterface
{
/** @var array<int, string> */
private array $requestedFields;

/** @param array<int, string> $requestedFields */
public function __construct(array $requestedFields)
{
$this->requestedFields = $requestedFields;
}

public function shouldSkipClass(ClassMetadata $metadata, Context $navigatorContext): bool
{
return false;
}

public function shouldSkipProperty(PropertyMetadata $property, Context $navigatorContext): bool
{
if (count($this->requestedFields) === 0) {
return false;
}

return !in_array($property->serializedName, $this->requestedFields, true);
}
}
13 changes: 12 additions & 1 deletion src/Sulu/Bundle/SnippetBundle/Controller/SnippetController.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@

namespace Sulu\Bundle\SnippetBundle\Controller;

use FOS\RestBundle\Context\Context;
use FOS\RestBundle\View\View;
use FOS\RestBundle\View\ViewHandler;
use HandcraftedInTheAlps\RestRoutingBundle\Routing\ClassResourceInterface;
use PHPCR\NodeInterface;
use Sulu\Bundle\CoreBundle\Serializer\Exclusion\FieldsExclusionStrategy;
use Sulu\Bundle\PageBundle\Document\PageDocument;
use Sulu\Bundle\SnippetBundle\Document\SnippetDocument;
use Sulu\Bundle\SnippetBundle\Snippet\DefaultSnippetManagerInterface;
Expand Down Expand Up @@ -204,7 +206,16 @@ public function cgetAction(Request $request)
$total
);

return $this->viewHandler->handle(View::create($data));
$view = View::create($data);

$requestedFields = $this->listRestHelper->getFields() ?? [];
if (count($requestedFields) > 0) {
$context = new Context();
$context->addExclusionStrategy(new FieldsExclusionStrategy($requestedFields));
$view->setContext($context);
}

return $this->viewHandler->handle($view);
}

/**
Expand Down

0 comments on commit 26ec420

Please sign in to comment.