Skip to content

Commit

Permalink
Add support to limit the number of results in listAll()
Browse files Browse the repository at this point in the history
  • Loading branch information
cundd committed Jan 8, 2019
1 parent b1a0ed4 commit a4da600
Showing 1 changed file with 36 additions and 5 deletions.
41 changes: 36 additions & 5 deletions Classes/Handler/CrudHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
use Cundd\Rest\ResponseFactoryInterface;
use Cundd\Rest\Router\Route;
use Cundd\Rest\Router\RouterInterface;
use Traversable;
use LimitIterator;

/**
* Handler for default CRUD requests
Expand Down Expand Up @@ -152,11 +152,12 @@ public function listAll(RestRequestInterface $request)
$dataProvider = $this->getDataProvider();

$allModels = $dataProvider->fetchAllModels($request->getResourceType());
if (!is_array($allModels) && $allModels instanceof Traversable) {
$allModels = iterator_to_array($allModels);
}

return $this->prepareResult($request, array_map([$dataProvider, 'getModelData'], $allModels), false);
return $this->prepareResult(
$request,
array_map([$dataProvider, 'getModelData'], $this->sliceResults($allModels)),
false
);
}

public function countAll(RestRequestInterface $request)
Expand Down Expand Up @@ -226,4 +227,34 @@ protected function getAddRootObjectForCollection()
{
return (bool)$this->objectManager->getConfigurationProvider()->getSetting('addRootObjectForCollection');
}

/**
* @param iterable|array $models
* @return array|LimitIterator
*/
protected function sliceResults($models)
{
$limit = $this->getListLimit();
if (is_array($models)) {
return array_slice($models, 0, $limit, true);
}
if ($models instanceof \IteratorAggregate) {
$models = $models->getIterator();
}
if ($models instanceof \Iterator) {
return iterator_to_array(new LimitIterator($models, 0, $limit));
}

return $models;
}

/**
* Specifies the maximum number of models that should be output in `listAll()`
*
* @return int
*/
protected function getListLimit(): int
{
return PHP_INT_MAX;
}
}

0 comments on commit a4da600

Please sign in to comment.