You are here

public function ContentExportTrait::processContentExportFiles in Content Synchronization 8.2

Same name and namespace in other branches
  1. 3.0.x src/Form/ContentExportTrait.php \Drupal\content_sync\Form\ContentExportTrait::processContentExportFiles()

Processes the content archive export batch

Parameters

$files: The batch content to persist.

$serializer_context:

array $context: The batch context.

File

src/Form/ContentExportTrait.php, line 85

Class

ContentExportTrait
Defines the content export form.

Namespace

Drupal\content_sync\Form

Code

public function processContentExportFiles($entities, $serializer_context = [], &$context) {

  //Initialize Batch
  if (empty($context['sandbox'])) {
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['current_number'] = 0;
    $context['sandbox']['queue'] = $entities;
    $context['sandbox']['max'] = count($entities);
  }
  $item = array_pop($context['sandbox']['queue']);

  // Get submitted values
  $entity_type = $item['entity_type'];

  //Validate that it is a Content Entity
  $instances = $this
    ->getEntityTypeManager()
    ->getDefinitions();
  if (!(isset($instances[$entity_type]) && $instances[$entity_type] instanceof ContentEntityType)) {
    $context['results']['errors'][] = $this
      ->t('Entity type @entity_type does not exist or it is not a content instance.', [
      '@entity_type' => $entity_type,
    ]);
  }
  else {
    if (isset($item['entity_uuid'])) {
      $entity_id = $item['entity_uuid'];
      $entity = $this
        ->getEntityTypeManager()
        ->getStorage($entity_type)
        ->loadByProperties([
        'uuid' => $entity_id,
      ]);
      $entity = array_shift($entity);
    }
    else {
      $entity_id = $item['entity_id'];
      $entity = $this
        ->getEntityTypeManager()
        ->getStorage($entity_type)
        ->load($entity_id);
    }

    //Make sure the entity exist for import
    if (empty($entity)) {
      $context['results']['errors'][] = $this
        ->t('Entity does not exist:') . $entity_type . "(" . $entity_id . ")";
    }
    else {

      // Create the name
      $bundle = $entity
        ->bundle();
      $uuid = $entity
        ->uuid();
      $name = $entity_type . "." . $bundle . "." . $uuid;
      if (!isset($context['exported'][$name])) {

        // Generate the YAML file.
        $exported_entity = $this
          ->getContentExporter()
          ->exportEntity($entity, $serializer_context);
        if (isset($serializer_context['export_type'])) {
          if ($serializer_context['export_type'] == 'snapshot') {

            //Save to cs_db_snapshot table.
            $activeStorage = new ContentDatabaseStorage(\Drupal::database(), 'cs_db_snapshot');
            $activeStorage
              ->cs_write($name, Yaml::decode($exported_entity), $entity_type . '.' . $bundle);
          }
          else {

            // Compate the YAML from the snapshot.
            // If for some reason is not on our snapshoot then add it.
            // Or if the new YAML is different the update it.
            $activeStorage = new ContentDatabaseStorage(\Drupal::database(), 'cs_db_snapshot');
            $exported_entity_snapshoot = $activeStorage
              ->cs_read($name);
            if (!$exported_entity_snapshoot || Yaml::encode($exported_entity_snapshoot) !== $exported_entity) {

              //Save to cs_db_snapshot table.
              $activeStorage
                ->cs_write($name, Yaml::decode($exported_entity), $entity_type . '.' . $bundle);
            }
            if ($serializer_context['export_type'] == 'tar') {

              // YAML in Archive .
              $this
                ->getArchiver()
                ->addString("entities/{$entity_type}/{$bundle}/{$name}.yml", $exported_entity);

              // Include Files to the archiver.
              if (method_exists($entity, 'getFileUri') && !empty($serializer_context['content_sync_directory_files'])) {
                $uri = $entity
                  ->getFileUri();
                $scheme = \Drupal::service('stream_wrapper_manager')
                  ->getScheme($uri);
                $destination = "{$serializer_context['content_sync_directory_files']}/{$scheme}/";
                $destination = str_replace($scheme . '://', $destination, $uri);
                $strip_path = str_replace('/files', '', $serializer_context['content_sync_directory_files']);
                $this
                  ->getArchiver()
                  ->addModify([
                  $destination,
                ], '', $strip_path);
              }
            }
            if ($serializer_context['export_type'] == 'folder') {

              // YAML in a directory.
              $path = $serializer_context['content_sync_directory_entities'] . "/{$entity_type}/{$bundle}";
              $destination = $path . "/{$name}.yml";
              \Drupal::service('file_system')
                ->prepareDirectory($path, FileSystemInterface::CREATE_DIRECTORY);
              $file = \Drupal::service('file_system')
                ->saveData($exported_entity, $destination, FileSystemInterface::EXISTS_REPLACE);
            }

            // Invalidate the CS Cache of the entity.
            $cache = \Drupal::cache('content')
              ->invalidate($entity_type . "." . $bundle . ":" . $name);
            if ($serializer_context['include_dependencies']) {

              //Include Dependencies
              $context['exported'][$name] = $name;
              if (!isset($context['sandbox']['dependencies'][$name])) {
                $exported_entity = Yaml::decode($exported_entity);
                $queue = $this->contentSyncManager
                  ->generateExportQueue([
                  $name => $exported_entity,
                ], $context['exported']);
                $context['sandbox']['dependencies'] = array_merge((array) $context['sandbox']['dependencies'], $queue);
                unset($queue[$name]);
                if (!empty($queue)) {

                  // Update the batch operations number
                  $context['sandbox']['max'] = $context['sandbox']['max'] + count($queue);
                  $context['sandbox']['queue'] = $queue;
                }
              }
            }
          }
        }
      }
    }
  }
  $context['message'] = $name;
  $context['results'][] = $name;
  $context['sandbox']['progress']++;
  $context['finished'] = $context['sandbox']['max'] > 0 && $context['sandbox']['progress'] < $context['sandbox']['max'] ? $context['sandbox']['progress'] / $context['sandbox']['max'] : 1;
}