You are here

protected function FormatterJson::addHateoas in RESTful 7.2

Add HATEOAS links to list of item.

Parameters

array $data: The data array after initial massaging.

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

File

src/Plugin/formatter/FormatterJson.php, line 149
Contains \Drupal\restful\Plugin\formatter\FormatterJson.

Class

FormatterJson
Class FormatterHalJson.

Namespace

Drupal\restful\Plugin\formatter

Code

protected function addHateoas(array &$data) {
  if (!($resource = $this
    ->getResource())) {
    return;
  }
  $request = $resource
    ->getRequest();

  // Get self link.
  $data['self'] = array(
    'title' => 'Self',
    'href' => $resource
      ->versionedUrl($resource
      ->getPath()),
  );
  $input = $request
    ->getParsedInput();
  unset($input['page']);
  unset($input['range']);
  $input['page'] = $request
    ->getPagerInput();
  $page = $input['page']['number'];
  if ($page > 1) {
    $query = $input;
    $query['page']['number'] = $page - 1;
    $data['previous'] = array(
      'title' => 'Previous',
      'href' => $resource
        ->versionedUrl('', array(
        'query' => $query,
      ), TRUE),
    );
  }

  // 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);
  $previous_items = ($page - 1) * $items_per_page;
  if (isset($data['count']) && $data['count'] > count($data['data']) + $previous_items) {
    $query = $input;
    $query['page']['number'] = $page + 1;
    $data['next'] = array(
      'title' => 'Next',
      'href' => $resource
        ->versionedUrl('', array(
        'query' => $query,
      ), TRUE),
    );
  }
}