diff --git a/spec/API/QueryFieldServiceSpec.php b/spec/API/QueryFieldServiceSpec.php index 5f4244a..791b02e 100644 --- a/spec/API/QueryFieldServiceSpec.php +++ b/spec/API/QueryFieldServiceSpec.php @@ -7,6 +7,7 @@ namespace spec\EzSystems\EzPlatformQueryFieldType\API; use eZ\Publish\API\Repository\LocationService; +use eZ\Publish\API\Repository\Values\Content\Query as ApiContentQuery; use EzSystems\EzPlatformQueryFieldType\API\QueryFieldService; use eZ\Publish\API\Repository\ContentTypeService; use eZ\Publish\API\Repository\SearchService; @@ -81,6 +82,32 @@ function it_counts_items_from_a_query_field_for_a_given_content_item() $this->countContentItems($this->getContent(), self::FIELD_DEFINITION_IDENTIFIER)->shouldBe($this->totalCount); } + function it_deducts_any_offset_when_counting_results(QueryType $queryType, SearchService $searchService) + { + $query = new ApiContentQuery(); + $query->offset = 5; + + $searchResult = new SearchResult(['searchHits' => [], 'totalCount' => 7]); + + $searchService->findContent($query)->willReturn($searchResult); + $queryType->getQuery(Argument::any())->willReturn($query); + + $this->countContentItems($this->getContent(), self::FIELD_DEFINITION_IDENTIFIER)->shouldBe(2); + } + + function it_returns_zero_if_offset_is_bigger_than_count(QueryType $queryType, SearchService $searchService) + { + $query = new ApiContentQuery(); + $query->offset = 8; + + $searchResult = new SearchResult(['searchHits' => [], 'totalCount' => 5]); + + $searchService->findContent($query)->willReturn($searchResult); + $queryType->getQuery(Argument::any())->willReturn($query); + + $this->countContentItems($this->getContent(), self::FIELD_DEFINITION_IDENTIFIER)->shouldBe(0); + } + /** * @return \eZ\Publish\Core\Repository\Values\Content\Content */ diff --git a/src/API/QueryFieldService.php b/src/API/QueryFieldService.php index 954faba..fb456b3 100644 --- a/src/API/QueryFieldService.php +++ b/src/API/QueryFieldService.php @@ -73,13 +73,15 @@ public function countContentItems(Content $content, string $fieldDefinitionIdent $query = $this->prepareQuery($content, $fieldDefinitionIdentifier); $query->limit = 0; - return $this->searchService->findContent($query)->totalCount; + $count = $this->searchService->findContent($query)->totalCount - $query->offset; + + return $count < 0 ? 0 : $count; } public function loadContentItemsSlice(Content $content, string $fieldDefinitionIdentifier, int $offset, int $limit): iterable { $query = $this->prepareQuery($content, $fieldDefinitionIdentifier); - $query->offset = $offset; + $query->offset += $offset; $query->limit = $limit; return array_map(