You are here

protected function FormatterJsonApi::addHateoas in RESTful 7.2

Add HATEOAS links to list of item.

Parameters

array $data: The data array after initial massaging.

ResourceInterface $resource: The resource to use.

string $path: The resource path.

1 call to FormatterJsonApi::addHateoas()
FormatterJsonApi::prepare in src/Plugin/formatter/FormatterJsonApi.php
Massages the raw data to create a structured array to pass to the renderer.

File

src/Plugin/formatter/FormatterJsonApi.php, line 182
Contains \Drupal\restful\Plugin\formatter\FormatterJsonApi.

Class

FormatterJsonApi
Class FormatterJsonApi @package Drupal\restful\Plugin\formatter

Namespace

Drupal\restful\Plugin\formatter

Code

protected function addHateoas(array &$data, ResourceInterface $resource = NULL, $path = NULL) {
  $top_level = empty($resource);
  $resource = $resource ?: $this
    ->getResource();
  $path = isset($path) ? $path : $resource
    ->getPath();
  if (!$resource) {
    return;
  }
  $request = $resource
    ->getRequest();
  if (!isset($data['links'])) {
    $data['links'] = array();
  }
  $input = $original_input = $request
    ->getParsedInput();
  unset($input['page']);
  unset($input['range']);
  unset($original_input['page']);
  unset($original_input['range']);
  $input['page'] = $request
    ->getPagerInput();
  $original_input['page'] = $request
    ->getPagerInput();

  // Get self link.
  $options = $top_level ? array(
    'query' => $input,
  ) : array();
  $data['links']['self'] = $resource
    ->versionedUrl($path, $options);
  $page = $input['page']['number'];

  // We know that there are more pages if the total count is bigger than the
  // number of items of the current request plus the number of items in
  // previous pages.
  $items_per_page = $this
    ->calculateItemsPerPage($resource);
  if (isset($data['meta']['count']) && $data['meta']['count'] > $items_per_page) {
    $num_pages = ceil($data['meta']['count'] / $items_per_page);
    unset($input['page']['number']);
    $data['links']['first'] = $resource
      ->getUrl(array(
      'query' => $input,
    ), FALSE);
    if ($page > 1) {
      $input = $original_input;
      $input['page']['number'] = $page - 1;
      $data['links']['previous'] = $resource
        ->getUrl(array(
        'query' => $input,
      ), FALSE);
    }
    if ($num_pages > 1) {
      $input = $original_input;
      $input['page']['number'] = $num_pages;
      $data['links']['last'] = $resource
        ->getUrl(array(
        'query' => $input,
      ), FALSE);
      if ($page != $num_pages) {
        $input = $original_input;
        $input['page']['number'] = $page + 1;
        $data['links']['next'] = $resource
          ->getUrl(array(
          'query' => $input,
        ), FALSE);
      }
    }
  }
}