Skip to content

Instantly share code, notes, and snippets.

@adamwojs
Last active June 2, 2020 13:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamwojs/c2d0e355457a0a2b91c0d1c5b4d7d351 to your computer and use it in GitHub Desktop.
Save adamwojs/c2d0e355457a0a2b91c0d1c5b4d7d351 to your computer and use it in GitHub Desktop.
SearchResultBatchIterator
<?php
/**
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*/
declare(strict_types=1);
namespace eZ\Publish\API\Repository\Values\Content\Search;
use eZ\Publish\API\Repository\SearchService;
use eZ\Publish\API\Repository\Values\Content\LocationQuery;
use eZ\Publish\Core\Base\Exceptions\InvalidArgumentException;
use IteratorAggregate;
use Traversable;
class SearchResultBatchIterator implements IteratorAggregate
{
public const DEFAULT_BATCH_SIZE = 25;
/** @var \eZ\Publish\API\Repository\SearchService */
private $searchService;
/** @var \eZ\Publish\API\Repository\Values\Content\LocationQuery */
private $query;
/** @var array */
private $languagesFilter;
/** @var int */
private $batchSize;
public function __construct(SearchService $searchService, LocationQuery $query, array $languagesFilter = [])
{
$this->searchService = $searchService;
$this->query = $query;
$this->languagesFilter = $languagesFilter;
$this->batchSize = self::DEFAULT_BATCH_SIZE;
}
public function getIterator(): Traversable
{
$query = clone $this->query;
$query->limit = $this->batchSize;
do {
$results = $this->searchService->findLocations($query, $this->languagesFilter);
foreach ($results->searchHits as $searchHit) {
yield $searchHit;
}
$query->offset += $query->limit;
} while($query->offset < $results->totalCount);
}
public function getQuery(): LocationQuery
{
return $this->query;
}
public function getBatchSize(): int
{
return $this->batchSize;
}
public function setBatchSize(int $batchSize): void
{
if ($batchSize < 1) {
throw new InvalidArgumentException('$batchSize', 'value must be greater or equal to 1');
}
$this->batchSize = $batchSize;
}
}
<?php
$searchService = $this->reporsitory->getSearchService();
$query = new LocationQuery([
'filter' => new ParentLocationId(2)
]);
$iterator = new SearchResultBatchIterator($searchService, $query);
$iterator->setBatchSize(3);
foreach ($iterator as $location) {
$output->writeln("Location ID = " . $location->valueObject->id);
}
@bdunogier
Copy link

bdunogier commented Jan 14, 2020

How would you use that iterator ?

Thank you for usage.php :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment