You are here

public function ContentImportTrait::syncContent in Content Synchronization 3.0.x

Same name and namespace in other branches
  1. 8.2 src/Form/ContentImportTrait.php \Drupal\content_sync\Form\ContentImportTrait::syncContent()

Processes the content import to be updated or created batch and persists the importer.

Parameters

$content_to_sync:

string $serializer_context:

array $context: The batch context.

File

src/Form/ContentImportTrait.php, line 55

Class

ContentImportTrait
Defines the content import form.

Namespace

Drupal\content_sync\Form

Code

public function syncContent(array $content_to_sync, $serializer_context = [], &$context) {
  if (empty($context['sandbox'])) {
    $directory = $serializer_context['content_sync_directory_entities'];
    $queue = $this->contentSyncManager
      ->generateImportQueue($content_to_sync, $directory);
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['queue'] = $queue;
    $context['sandbox']['directory'] = $directory;
    $context['sandbox']['max'] = count($queue);
  }
  if (!empty($context['sandbox']['queue'])) {
    $error = FALSE;
    $item = array_pop($context['sandbox']['queue']);
    $decoded_entity = $item['decoded_entity'];
    $entity_type_id = $item['entity_type_id'];
    $entity = $this->contentSyncManager
      ->getContentImporter()
      ->importEntity($decoded_entity, $serializer_context);
    if ($entity) {
      $context['results'][] = TRUE;
      $context['message'] = $this
        ->t('Imported content @label (@entity_type: @id).', [
        '@label' => $entity
          ->label(),
        '@id' => $entity
          ->id(),
        '@entity_type' => $entity
          ->getEntityTypeId(),
      ]);

      // Invalidate the CS Cache of the entity.
      $bundle = $entity
        ->bundle();
      $entity_id = $entity
        ->getEntityTypeId();
      $name = $entity_id . "." . $bundle . "." . $entity
        ->uuid();
      $cache = \Drupal::cache('content')
        ->invalidate($entity_id . "." . $bundle . ":" . $name);
      unset($entity);
    }
    else {
      $error = TRUE;
    }
    if ($error) {
      $context['message'] = $this
        ->t('Error importing content of type @entity_type.', [
        '@entity_type' => $entity_type_id,
      ]);
      if (!isset($context['results']['errors'])) {
        $context['results']['errors'] = [];
      }
      $context['results']['errors'][] = $context['message'];
    }
    if ($error) {
      \Drupal::messenger()
        ->addError($context['message']);
    }

    // We need to count the progress anyway even if an error has occured.
    $context['sandbox']['progress']++;
  }
  $context['finished'] = $context['sandbox']['max'] > 0 && $context['sandbox']['progress'] < $context['sandbox']['max'] ? $context['sandbox']['progress'] / $context['sandbox']['max'] : 1;
}