You are here

public function RestfulFormatterHalJson::prepare in RESTful 7

Massages the raw data to create a structured array to pass to the renderer.

Parameters

array $data: The raw data to return.

Return value

array The data prepared to be rendered.

Overrides RestfulFormatterInterface::prepare

File

plugins/formatter/hal_json/RestfulFormatterHalJson.class.php, line 20
Contains RestfulFormatterHalJson.

Class

RestfulFormatterHalJson
@file Contains RestfulFormatterHalJson.

Code

public function prepare(array $data) {

  // If we're returning an error then set the content type to
  // 'application/problem+json; charset=utf-8'.
  if (!empty($data['status']) && floor($data['status'] / 100) != 2) {
    $this->contentType = 'application/problem+json; charset=utf-8';
    return $data;
  }

  // Here we get the data after calling the backend storage for the resources.
  $curies_resource = $this
    ->withCurie($this->handler
    ->getResourceName());
  $output = array();
  foreach ($data as &$row) {
    if (is_array($row)) {
      $row = $this
        ->prepareRow($row, $output);
    }
  }
  $output[$curies_resource] = $data;
  if (!empty($this->handler)) {
    if (method_exists($this->handler, 'getTotalCount') && method_exists($this->handler, 'isListRequest') && $this->handler
      ->isListRequest()) {

      // Get total number of items for the current request w/out pagination.
      $output['count'] = $this->handler
        ->getTotalCount();
    }
    if (method_exists($this->handler, 'additionalHateoas')) {
      $output = array_merge($output, $this->handler
        ->additionalHateoas());
    }

    // Add HATEOAS to the output.
    $this
      ->addHateoas($output);
  }

  // Cosmetic sorting to send the hateoas properties to the end of the output.
  uksort($output, function ($a, $b) {
    if ($a[0] == '_' && $b[0] == '_' || $a[0] != '_' && $b[0] != '_') {
      return strcmp($a, $b);
    }
    return $a[0] == '_' ? 1 : -1;
  });
  return $output;
}