You are here

class ContentSynchronizerCommands in Content Synchronizer 8

Same name and namespace in other branches
  1. 8.2 src/Commands/ContentSynchronizerCommands.php \Drupal\content_synchronizer\Commands\ContentSynchronizerCommands
  2. 3.x src/Commands/ContentSynchronizerCommands.php \Drupal\content_synchronizer\Commands\ContentSynchronizerCommands

A Drush commandfile.

In addition to this file, you need a drush.services.yml in root of your module, and a composer.json file that provides the name of the services file to use.

See these files for an example of injecting Drupal services:

Hierarchy

Expanded class hierarchy of ContentSynchronizerCommands

1 string reference to 'ContentSynchronizerCommands'
drush.services.yml in ./drush.services.yml
drush.services.yml
1 service uses ContentSynchronizerCommands
content_synchronizer.commands in ./drush.services.yml
\Drupal\content_synchronizer\Commands\ContentSynchronizerCommands

File

src/Commands/ContentSynchronizerCommands.php, line 24

Namespace

Drupal\content_synchronizer\Commands
View source
class ContentSynchronizerCommands extends DrushCommands {

  /**
   *
   * Create an import from passed .zip file.
   *
   * @param $path
   *   Optional. The cache bin to fetch from.
   * @param array $options
   *   An associative array of options whose values come from cli, aliases, config, etc.
   *
   * @option as_function
   *   if this command will call as a function, in this case, return ImportEntity Id.
   *
   * @command content:synchronizer-create-import
   * @aliases csci,content-synchronizer-create-import
   * @return integer
   */
  public function synchronizerCreateImport($path, $options = [
    'as_function' => FALSE,
  ]) {
    if (file_exists($path)) {
      $extensionData = explode('.', $path);
      if (end($extensionData) == 'zip') {
        if ($file = file_save_data(file_get_contents($path))) {
          $name = strip_tags(t('Drush import - %date', [
            '%date' => \Drupal::service('date.formatter')
              ->format(time()),
          ]));
          $ie = ImportEntity::create([
            'name' => $name,
            ImportEntity::FIELD_ARCHIVE => $file,
          ]);
          $ie
            ->save();
          $this->logger
            ->notice(t('The import has been created')
            ->__toString());
        }
      }
      else {
        $this->logger
          ->error(t('The file is not a .zip archive')
          ->__toString());
      }
    }
    else {
      $this->logger
        ->error(t('No file found')
        ->__toString());
    }
    if ($options['as_function'] == TRUE) {
      return $ie
        ->id();
    }
  }

  /**
   * Delete temporary files.
   *
   *
   * @command content:synchronizer-clean-temporary-files
   * @aliases csctf,content-synchronizer-clean-temporary-files
   */
  public function synchronizerCleanTemporaryFiles() {
    $path = \Drupal::service('file_system')
      ->realpath(ExportEntityWriter::GENERATOR_DIR);
    foreach (glob($path . '/*') as $file) {
      if (is_dir($file)) {
        file_unmanaged_delete_recursive($file);
      }
    }
  }

  /**
   * Launch the export of the passed ID.
   *
   * @param $exportId
   *   The export id.
   * @param $destination
   *   File to create
   *
   * @command content:synchronizer-launch-export
   * @aliases cslex,content-synchronizer-launch-export
   */
  public function synchronizerLaunchExport($exportId, $destination = '') {
    if ($export = ExportEntity::load($exportId)) {
      $entitiesToExport = $export
        ->getEntitiesList();
      $writer = new ExportEntityWriter();
      $writer
        ->initFromId($export
        ->label());
      $processor = new ExportProcessor($writer);

      // Loop for log.
      $count = count($entitiesToExport);
      foreach (array_values($entitiesToExport) as $key => $entity) {
        try {
          $processor
            ->exportEntity($entity);
          $status = t('Exported');
        } catch (\Exception $error) {
          $this->logger
            ->error($error
            ->getMessage());
          $status = t('Error');
        }
        $this->logger
          ->notice(t('[@key/@count] - "@label" - @status', [
          '@key' => $key + 1,
          '@count' => $count,
          '@label' => ExportEntityWriter::getEntityLabel($entity),
          '@status' => $status,
        ])
          ->__toString());
      }

      // Deplace archive.
      $tempArchive = $path = \Drupal::service('file_system')
        ->realpath($processor
        ->closeProcess());
      if ($destination == '') {
        $destination = './' . basename($tempArchive);
      }
      rename($tempArchive, $destination);
      $this->logger
        ->notice(t('Archive file : @destination', [
        '@destination' => $destination,
      ])
        ->__toString());
    }
  }

  /**
   * Launch the import of the passed ID.
   *
   * @param $importId
   *   The import id.
   * @param array $options
   *   An associative array of options whose values come from cli, aliases, config, etc.
   *
   * @option publish
   *   Autopublish imported content :  publish|unpublish
   * @option update
   *   Update stategy :  systematic|if_recent|no_update
   *
   * @command content:synchronizer-launch-import
   * @aliases cslim,content-synchronizer-launch-import
   *
   * @throws \Exception
   */
  public function synchronizerLaunchImport($importId, $options = [
    'publish' => '',
    'update' => '',
  ]) {
    if ($import = ImportEntity::load($importId)) {
      if (!in_array('publication_' . $options['publish'], array_keys(LaunchImportForm::getCreateOptions()))) {
        $message = "Publish option must be in : publish|unpublish";
        throw new \Exception($message);
      }
      if (!in_array('update_' . $options['update'], array_keys(LaunchImportForm::getUpdateOptions()))) {
        $message = "Update option must be in : systematic|if_recent|no_update";
        throw new \Exception($message);
      }
      $createType = 'publication_' . $options['publish'];
      $updateType = 'update_' . $options['update'];
      $importProcessor = new ImportProcessor($import);
      $importProcessor
        ->setCreationType($createType);
      $importProcessor
        ->setUpdateType($updateType);

      // Loop for logs.
      $rootEntities = $import
        ->getRootsEntities();
      $count = count($rootEntities);
      foreach ($rootEntities as $key => $rootEntityData) {
        try {
          $importProcessor
            ->importEntityFromRootData($rootEntityData);
          $status = array_key_exists('edit_url', $rootEntityData) ? t('Updated') : t('Created');
        } catch (\Exception $error) {
          $this->logger
            ->error($error
            ->getMessage());
          $status = t('Error');
        }
        $this->logger
          ->notice(t('[@key/@count] - "@label" - @status', [
          '@key' => $key + 1,
          '@count' => $count,
          '@status' => $status,
          '@label' => $rootEntityData['label'],
        ])
          ->__toString());
      }

      // Close process.
      $import
        ->removeArchive();
    }
  }

  /**
   * Export all nodes/taxo : bind together create Export, attach all node in & cslex
   *
   * @param $destination
   *   Destination file
   *
   * @command content:synchronizer-export-all
   * @aliases csexall
   */
  public function synchronizerAllExport($destination = '') {

    // 1 : create export
    $exportEntity = ExportEntity::create([
      'name' => 'export-all',
    ]);
    $exportEntity
      ->save();
    $exportId = $exportEntity
      ->id();

    // 2 : add all nodes / taxo
    foreach ([
      'node',
      'taxonomy_term',
    ] as $entity_type) {
      $ids = \Drupal::entityQuery($entity_type)
        ->execute();
      $entities = \Drupal::entityTypeManager()
        ->getStorage($entity_type)
        ->loadMultiple($ids);
      foreach ($entities as $entity) {
        $exportEntity
          ->addEntity($entity);
      }
    }

    // 3 : make export
    $this
      ->synchronizerLaunchExport($exportId, $destination);
  }

  /**
   * Import from zip : bind together csci & cslim
   *
   * @param $file_path
   *   zip file
   *
   * @command content:synchronizer-import-zip
   * @aliases csimzip
   *
   * @throws \Exception
   */
  public function synchronizerImportZip($file_path) {

    // 1 : create export
    $importId = $this
      ->synchronizerCreateImport($file_path, [
      'as_function' => TRUE,
    ]);

    // 2 : add all nodes of all node-types
    $this
      ->synchronizerLaunchImport($importId, [
      'publish' => 'publish',
      'update' => 'systematic',
    ]);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ContentSynchronizerCommands::synchronizerAllExport public function Export all nodes/taxo : bind together create Export, attach all node in & cslex
ContentSynchronizerCommands::synchronizerCleanTemporaryFiles public function Delete temporary files.
ContentSynchronizerCommands::synchronizerCreateImport public function Create an import from passed .zip file.
ContentSynchronizerCommands::synchronizerImportZip public function Import from zip : bind together csci & cslim
ContentSynchronizerCommands::synchronizerLaunchExport public function Launch the export of the passed ID.
ContentSynchronizerCommands::synchronizerLaunchImport public function Launch the import of the passed ID.