/**
* Retrieves a paginated set of results using the Pager service.
*
* This method calculates the proper limit and offset for paginated queries based on several sources:
* - A GET parameter (`?page=2`) to select the current page.
* - An optional GET parameter (`?perPage=n`) to dynamically adjust the number of items per page.
* - Direct method parameters to override default values if necessary.
*
* Additionally, the maximum allowed items per page can be configured per model via the
* `$perPageMaxLimit` property.
*
* @param int|null $perPage The desired number of items per page. Or use the GET parameter.
* @param string $group Identifier for the pagination set; useful when multiple paginations are in use.
* @param int|null $page Optional page number (useful when provided via an alternative mechanism).
* @param int $segment Optional URI segment index to extract the page number if applicable.
*
* @return array|null Returns the paginated result set, or null if no records are found.
*/
public function paginateApi(?int $perPage = null, string $group = 'default', ?int $page = null, int $segment = 0)
{
// Retrieve the shared Pager service, which might be used by several models.
$pager = service('pager');
// If a specific URI segment is provided, update the Pager accordingly.
if ($segment !== 0) {
$pager->setSegment($segment, $group);
}
// Check if the GET parameter 'perPage' is provided and use it if $perPage is not already defined.
$request = service('request');
$perPageFromQuery = $request->getGet('perPage');
if ($perPageFromQuery !== null && !$perPage) {
$perPage = (int) $perPageFromQuery;
// Enforce security limits for the number of items per page (adjust the min/max values as needed).
$minPerPage = 1;
$maxPerPage = $this->perPageMaxLimit ?: $perPage;
$perPage = max($minPerPage, min($perPage, $maxPerPage));
}
// Determine the current page: use the provided $page if valid, otherwise retrieve it from the Pager.
$page = $page >= 1 ? $page : $pager->getCurrentPage($group);
// Store the pagination settings in the Pager, making them accessible in the views.
$this->pager = $pager->store($group, $page, $perPage, $this->countAllResults(false), $segment);
$perPage = $this->pager->getPerPage($group);
$offset = ($pager->getCurrentPage($group) - 1) * $perPage;
// Return the paginated results.
return $this->findAll($perPage, $offset);
}