You are here

public function GatsbyInstantPreview::buildRelationshipJson in Gatsby Live Preview & Incremental Builds 8

Same name and namespace in other branches
  1. 2.0.x modules/gatsby_instantpreview/src/GatsbyInstantPreview.php \Drupal\gatsby_instantpreview\GatsbyInstantPreview::buildRelationshipJson()

Builds an array of entity JSON data based on entity relationships.

1 call to GatsbyInstantPreview::buildRelationshipJson()
GatsbyInstantPreview::gatsbyPrepareData in modules/gatsby_instantpreview/src/GatsbyInstantPreview.php
Prepares Gatsby Data to send to the preview and build servers.

File

modules/gatsby_instantpreview/src/GatsbyInstantPreview.php, line 198

Class

GatsbyInstantPreview
Defines a class to extend the default preview system with an instant preview.

Namespace

Drupal\gatsby_instantpreview

Code

public function buildRelationshipJson($relationships, &$entity_data, $included_types = []) {
  foreach ($relationships as $data) {
    if (empty($data['data'])) {
      continue;
    }
    $related_items = $data['data'];

    // Check if this is a single value field.
    if (!empty($data['data']['type'])) {
      $related_items = [
        $data['data'],
      ];
    }
    foreach ($related_items as $related_data) {

      // Add JSON if the entity type is one that should be sent to Gatsby.
      $entityType = !empty($related_data['type']) ? explode('--', $related_data['type']) : "";
      if (!empty($entityType) && (!$included_types || in_array($entityType[0], $included_types, TRUE))) {

        // Skip this entity if it's already been added to the data array.
        if (!empty($entity_data[$related_data['id']])) {
          continue;
        }
        $related_entity = $this->entityRepository
          ->loadEntityByUuid($entityType[0], $related_data['id']);

        // Make sure the related entity is a valid entity.
        if (empty($related_entity) || !$related_entity instanceof ContentEntityInterface) {
          continue;
        }
        $related_json = $this
          ->getJson($related_entity);
        if (!$related_json) {
          continue;
        }
        $entity_data[$related_data['id']] = $related_json['data'];

        // We need to traverse all related entities to get all relevant JSON.
        if (!empty($related_json['data']['relationships'])) {
          $this
            ->buildRelationshipJson($related_json['data']['relationships'], $entity_data, $included_types);
        }
      }
    }
  }
}