public function FormatterHalJson::prepare in RESTful 7.2
Massages the raw data to create a structured array to pass to the renderer.
Parameters
ResourceFieldInterface[] $data: The raw data to return.
Return value
array The data prepared to be rendered.
Overrides FormatterInterface::prepare
File
- src/
Plugin/ formatter/ FormatterHalJson.php, line 44 - Contains \Drupal\restful\Plugin\formatter\FormatterHalJson.
Class
- FormatterHalJson
- Class FormatterHalJson @package Drupal\restful\Plugin\formatter
Namespace
Drupal\restful\Plugin\formatterCode
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.
if (!($resource = $this
->getResource())) {
throw new ServerConfigurationException('Resource unavailable for HAL formatter.');
}
$is_list_request = $resource
->getRequest()
->isListRequest($resource
->getPath());
$values = $this
->extractFieldValues($data);
$values = $this
->limitFields($values);
if ($is_list_request) {
// If this is a listing, move everything into the _embedded.
$curies_resource = $this
->withCurie($resource
->getResourceMachineName());
$output = array(
'_embedded' => array(
$curies_resource => $values,
),
);
}
else {
$output = reset($values) ?: array();
}
$data_provider = $resource
->getDataProvider();
if ($data_provider && method_exists($data_provider, 'count') && $is_list_request) {
// Get the total number of items for the current request without
// pagination.
$output['count'] = $data_provider
->count();
}
if (method_exists($resource, 'additionalHateoas')) {
$output = array_merge($output, $resource
->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;
}