From e2b32ed10f53039106450224b5be33c8a2d5bc75 Mon Sep 17 00:00:00 2001 From: Tomasz Kryszan Date: Wed, 4 Sep 2024 09:40:17 +0200 Subject: [PATCH] IBX-8597: Added BaseSortClauseProcessor https://github.com/ibexa/rest/pull/117 --- src/bundle/Resources/config/services.yml | 5 ++ .../SortClause/BaseSortClauseProcessor.php | 58 +++++++++++++++++++ .../SortClauseProcessorInterface.php | 24 ++++++++ 3 files changed, 87 insertions(+) create mode 100644 src/contracts/Input/Parser/Query/SortClause/BaseSortClauseProcessor.php create mode 100644 src/contracts/Input/Parser/Query/SortClause/SortClauseProcessorInterface.php diff --git a/src/bundle/Resources/config/services.yml b/src/bundle/Resources/config/services.yml index 63cf0e13..5bdf9716 100644 --- a/src/bundle/Resources/config/services.yml +++ b/src/bundle/Resources/config/services.yml @@ -397,3 +397,8 @@ services: abstract: true arguments: $parsingDispatcher: '@Ibexa\Contracts\Rest\Input\ParsingDispatcher' + + Ibexa\Contracts\Rest\Input\Parser\Query\SortClause\BaseSortClauseProcessor: + abstract: true + arguments: + $parsingDispatcher: '@Ibexa\Contracts\Rest\Input\ParsingDispatcher' diff --git a/src/contracts/Input/Parser/Query/SortClause/BaseSortClauseProcessor.php b/src/contracts/Input/Parser/Query/SortClause/BaseSortClauseProcessor.php new file mode 100644 index 00000000..4405b139 --- /dev/null +++ b/src/contracts/Input/Parser/Query/SortClause/BaseSortClauseProcessor.php @@ -0,0 +1,58 @@ +parsingDispatcher = $parsingDispatcher; + } + + final public function processSortClauses(array $sortClauseData): iterable + { + if (empty($sortClauseData)) { + yield from []; + } + + foreach ($sortClauseData as $sortClauseName => $direction) { + $mediaType = $this->getSortClauseMediaType($sortClauseName); + + try { + yield $this->parsingDispatcher->parse([$sortClauseName => $direction], $mediaType); + } catch (Exceptions\Parser $e) { + throw new Exceptions\Parser($this->getParserInvalidSortClauseMessage($sortClauseName), 0, $e); + } + } + } + + abstract protected function getMediaTypePrefix(): string; + + abstract protected function getParserInvalidSortClauseMessage(string $sortClauseName): string; + + private function getSortClauseMediaType(string $sortClauseName): string + { + $mediaTypePrefix = $this->getMediaTypePrefix(); + if ('.' !== substr($mediaTypePrefix, strlen($mediaTypePrefix) - 1)) { + $mediaTypePrefix .= '.'; + } + + return $mediaTypePrefix . $sortClauseName; + } +} diff --git a/src/contracts/Input/Parser/Query/SortClause/SortClauseProcessorInterface.php b/src/contracts/Input/Parser/Query/SortClause/SortClauseProcessorInterface.php new file mode 100644 index 00000000..ac8ef713 --- /dev/null +++ b/src/contracts/Input/Parser/Query/SortClause/SortClauseProcessorInterface.php @@ -0,0 +1,24 @@ + $sortClauseData + * + * @return iterable + */ + public function processSortClauses(array $sortClauseData): iterable; +}