From 26ec4205403e924a9d0be4522575a78b295ef9a1 Mon Sep 17 00:00:00 2001 From: Maik Rosenthal Date: Wed, 24 May 2023 11:32:30 +0200 Subject: [PATCH] added fields exclusion strategy --- .../Exclusion/FieldsExclusionStrategy.php | 36 +++++++++++++++++++ .../Controller/SnippetController.php | 13 ++++++- 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 src/Sulu/Bundle/CoreBundle/Serializer/Exclusion/FieldsExclusionStrategy.php diff --git a/src/Sulu/Bundle/CoreBundle/Serializer/Exclusion/FieldsExclusionStrategy.php b/src/Sulu/Bundle/CoreBundle/Serializer/Exclusion/FieldsExclusionStrategy.php new file mode 100644 index 0000000000..18aceb7914 --- /dev/null +++ b/src/Sulu/Bundle/CoreBundle/Serializer/Exclusion/FieldsExclusionStrategy.php @@ -0,0 +1,36 @@ + */ + private array $requestedFields; + + /** @param array $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); + } +} diff --git a/src/Sulu/Bundle/SnippetBundle/Controller/SnippetController.php b/src/Sulu/Bundle/SnippetBundle/Controller/SnippetController.php index 205c179143..d76dabd133 100644 --- a/src/Sulu/Bundle/SnippetBundle/Controller/SnippetController.php +++ b/src/Sulu/Bundle/SnippetBundle/Controller/SnippetController.php @@ -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; @@ -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); } /**