You are here

public function ContentHubEntitiesTracking::save in Acquia Content Hub 8

Saves a record of an imported entity.

Return value

bool TRUE if saving is successful, FALSE otherwise.

File

src/ContentHubEntitiesTracking.php, line 544

Class

ContentHubEntitiesTracking
Tracks in a table the list of all entities imported from Content Hub.

Namespace

Drupal\acquia_contenthub

Code

public function save() {

  // If we reached here then we have a valid input and can save safely.
  $query = $this->database
    ->merge(self::TABLE)
    ->key([
    'entity_id' => $this
      ->getEntityId(),
    'entity_type' => $this
      ->getEntityType(),
    'entity_uuid' => $this
      ->getUuid(),
  ])
    ->fields([
    'status_export' => $this
      ->getExportStatus(),
    'status_import' => $this
      ->getImportStatus(),
    'modified' => $this
      ->getModified(),
    'origin' => $this
      ->getOrigin(),
  ]);
  try {
    $result = $query
      ->execute();
  } catch (IntegrityConstraintViolationException $exception) {

    // There is an entity in the database with the same ID but different UUID.
    // It needs to be deleted before we can proceed.
    if ($record = ContentHubEntitiesTracking::loadByDrupalEntity($this
      ->getEntityType(), $this
      ->getEntityId())) {
      $record
        ->delete();
      \Drupal::logger('acquia_contenthub')
        ->debug('An outdated record for entity (%id, %type, %uuid) was deleted from the Entities Tracking table due to UUID mismatch.', [
        '%id' => $record
          ->getEntityId(),
        '%type' => $record
          ->getEntityType(),
        '%uuid' => $record
          ->getUuid(),
      ]);

      // Now retry the original query.
      $result = $query
        ->execute();
    }
    else {

      // If there is no duplicate record with different UUID, then the error
      // is unknown. Just throw the exception as it would normally happen.
      throw $exception;
    }
  }
  switch ($result) {
    case Merge::STATUS_INSERT:
    case Merge::STATUS_UPDATE:
      return TRUE;
  }
  return FALSE;
}