You are here

public function GatsbyEntityLogger::logEntityWithRelationships in Gatsby Live Preview & Incremental Builds 8

Same name and namespace in other branches
  1. 2.0.x modules/gatsby_fastbuilds/src/GatsbyEntityLogger.php \Drupal\gatsby_fastbuilds\GatsbyEntityLogger::logEntityWithRelationships()

Logs an entity create/update/delete and includes all related entity data.

Parameters

Drupal\Core\Entity\ContentEntityInterface $entity: The entity to log the details for.

string $action: The action for this entity (insert, update, or delete).

File

modules/gatsby_fastbuilds/src/GatsbyEntityLogger.php, line 100

Class

GatsbyEntityLogger
Defines a service for logging content entity changes using log entities.

Namespace

Drupal\gatsby_fastbuilds

Code

public function logEntityWithRelationships(ContentEntityInterface $entity, string $action) {
  $this
    ->deleteLoggedEntity($entity
    ->uuid(), $entity
    ->language()
    ->getId());
  $json = [];
  if ($action !== 'delete') {
    $json = $this->gatsbyInstantPreview
      ->getJson($entity);
    if (!$json) {
      return;
    }
    if (!empty($json['data']['relationships'])) {

      // Generate JSON for all related entities to send to Gatsby.
      $entity_data = [];
      $this->gatsbyInstantPreview
        ->buildRelationshipJson($json['data']['relationships'], $entity_data);
      if (!empty($entity_data)) {

        // Remove the uuid keys from the array.
        $entity_data = array_values($entity_data);
        $original_data = $json['data'];
        $entity_data[] = $original_data;
        $json['data'] = $entity_data;
      }
    }
  }
  $json['id'] = $entity
    ->uuid();
  $json['action'] = $action;
  $log_entry = [
    'entity_uuid' => $entity
      ->uuid(),
    'title' => $entity
      ->label(),
    'entity' => $entity
      ->getEntityTypeId(),
    'bundle' => $entity
      ->bundle(),
    'langcode' => $entity
      ->language()
      ->getId(),
    'action' => $action,
    'json' => json_encode($json),
  ];
  $log = $this->entityTypeManager
    ->getStorage('gatsby_log_entity')
    ->create($log_entry);
  $log
    ->save();
}