Skip to content
Snippets Groups Projects

Issue #3506812: Add generic handling of JSON:API includes

Files
3
@@ -67,7 +67,7 @@ class JsonApi extends RestClient {
],
'response_format' => [
'#type' => 'hidden',
'#default_value' => 'json',
'#default_value' => 'external_entities_api_json',
],
'data_path' => [
'list' => [
@@ -91,7 +91,7 @@ class JsonApi extends RestClient {
],
'pager' => [
'#type' => NULL,
// Drupal uses a 50 elements per bage basis so we go for 1 query per
// Drupal uses a 50 elements per page basis so we go for 1 query per
// page. 50 is the JSON:API default limit anyway.
'default_limit' => [
'#type' => 'hidden',
@@ -348,16 +348,49 @@ class JsonApi extends RestClient {
$result = parent::load($id);
// Check for "included".
if (!empty($result[1])) {
// JSONPath returned an array of object so we got "extra" from "included".
$included = array_slice($result, 1);
$result = $result[0];
$result['included'] = $included;
}
static::$cachedData[$this->configuration['endpoint']][$id] = $result;
return $result;
}
protected function resolveRelationships(&$result): void
{
// Collect all includes and index them by type and id.
$includedRegistry = [];
foreach ($result['included'] as $included_entry) {
$included_id = ($included_entry['type'] ?? NULL) . ':' . $included_entry['id'];
$includedRegistry[$included_id] = $included_entry;
}
$this->_resolveRelationsRecursive($result['relationships'], $includedRegistry);
}
protected function _resolveRelationsRecursive(&$relationships, $includedRegistry): void
{
foreach ($relationships as $field => $relationship) {
if (!empty($relationship['data'])) {
// Relationships can be single or multi-value.
if (isset($relationship['data']['id'])) {
$this->_mapRelationshipData($relationships[$field]['data'], $includedRegistry);
} else {
foreach ($relationship['data'] as $i => $data) {
$this->_mapRelationshipData($relationships[$field]['data'][$i], $includedRegistry);
}
}
}
}
}
protected function _mapRelationshipData(&$data, array $includedRegistry): void
{
if (isset($data['id'])) {
$included_id = ($data['type'] ?? NULL) . ':' . $data['id'];
if (isset($includedRegistry[$included_id])) {
$data['included'] = $includedRegistry[$included_id];
}
if (!empty($data['relationships'])) {
$this->_resolveRelationsRecursive($data['relationships'], $includedRegistry);
}
}
}
}
Loading