You are here

public function LinkManager::getPagerLinks in JSON:API 8

Get the pager links for a given request object.

Parameters

\Symfony\Component\HttpFoundation\Request $request: The request object.

array $link_context: An associative array with extra data to build the links.

Return value

string[] An array of URLs, with:

  • a 'next' key if it is not the last page;
  • 'prev' and 'first' keys if it's not the first page.

Throws

\Symfony\Component\HttpKernel\Exception\BadRequestHttpException When the offset and size are invalid.

File

src/LinkManager/LinkManager.php, line 106

Class

LinkManager
Class to generate links and queries for entities.

Namespace

Drupal\jsonapi\LinkManager

Code

public function getPagerLinks(Request $request, array $link_context = []) {
  if (!empty($link_context['total_count']) && !($total = (int) $link_context['total_count'])) {
    return [];
  }
  $params = $request
    ->get('_json_api_params');
  if ($page_param = $params[OffsetPage::KEY_NAME]) {

    /* @var \Drupal\jsonapi\Query\OffsetPage $page_param */
    $offset = $page_param
      ->getOffset();
    $size = $page_param
      ->getSize();
  }
  else {

    // Apply the defaults.
    $offset = OffsetPage::DEFAULT_OFFSET;
    $size = OffsetPage::SIZE_MAX;
  }
  if ($size <= 0) {
    throw new BadRequestHttpException(sprintf('The page size needs to be a positive integer.'));
  }
  $query = (array) $request->query
    ->getIterator();
  $links = [];

  // Check if this is not the last page.
  if ($link_context['has_next_page']) {
    $links['next'] = $this
      ->getRequestLink($request, $this
      ->getPagerQueries('next', $offset, $size, $query));
    if (!empty($total)) {
      $links['last'] = $this
        ->getRequestLink($request, $this
        ->getPagerQueries('last', $offset, $size, $query, $total));
    }
  }

  // Check if this is not the first page.
  if ($offset > 0) {
    $links['first'] = $this
      ->getRequestLink($request, $this
      ->getPagerQueries('first', $offset, $size, $query));
    $links['prev'] = $this
      ->getRequestLink($request, $this
      ->getPagerQueries('prev', $offset, $size, $query));
  }
  return $links;
}