You are here

abstract class ImporterBase in CSV Importer 8

Provides a base class for ImporterBase plugins.

Hierarchy

Expanded class hierarchy of ImporterBase

See also

\Drupal\csv_importer\Annotation\Importer

\Drupal\csv_importer\Plugin\ImporterManager

\Drupal\csv_importer\Plugin\ImporterInterface

Plugin API

5 files declare their use of ImporterBase
CommentImporter.php in src/Plugin/Importer/CommentImporter.php
MenuLinkImporter.php in src/Plugin/Importer/MenuLinkImporter.php
NodeImporter.php in src/Plugin/Importer/NodeImporter.php
TaxonomyImporter.php in src/Plugin/Importer/TaxonomyImporter.php
UserImporter.php in src/Plugin/Importer/UserImporter.php

File

src/Plugin/ImporterBase.php, line 21

Namespace

Drupal\csv_importer\Plugin
View source
abstract class ImporterBase extends PluginBase implements ImporterInterface {
  use StringTranslationTrait;

  /**
   * The entity type manager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The config service.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $config;

  /**
   * Constructs ImporterBase object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param string $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager service.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config
   *   The config service.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, ConfigFactoryInterface $config) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->entityTypeManager = $entity_type_manager;
    $this->config = $config;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('entity_type.manager'), $container
      ->get('config.factory'));
  }

  /**
   * {@inheritdoc}
   */
  public function data() {
    $csv = $this->configuration['csv'];
    $return = [];
    if ($csv && is_array($csv)) {
      $csv_fields = $csv[0];
      unset($csv[0]);
      foreach ($csv as $index => $data) {
        foreach ($data as $key => $content) {
          if (isset($csv_fields[$key])) {
            $content = Unicode::convertToUtf8($content, mb_detect_encoding($content));
            $fields = explode('|', $csv_fields[$key]);
            $field = $fields[0];
            if (count($fields) > 1) {
              foreach ($fields as $key => $in) {
                $return['content'][$index][$field][$in] = $content;
              }
            }
            elseif (isset($return['content'][$index][$field])) {
              $prev = $return['content'][$index][$field];
              $return['content'][$index][$field] = [];
              if (is_array($prev)) {
                $prev[] = $content;
                $return['content'][$index][$field] = $prev;
              }
              else {
                $return['content'][$index][$field][] = $prev;
                $return['content'][$index][$field][] = $content;
              }
            }
            else {
              $return['content'][$index][current($fields)] = $content;
            }
          }
        }
        if (isset($return[$index])) {
          $return['content'][$index] = array_intersect_key($return[$index], array_flip($this->configuration['fields']));
        }
      }
    }
    return $return;
  }

  /**
   * {@inheritdoc}
   */
  public function add($content, array &$context) {
    if (!$content) {
      return NULL;
    }
    $entity_type = $this->configuration['entity_type'];
    $entity_type_bundle = $this->configuration['entity_type_bundle'];
    $entity_definition = $this->entityTypeManager
      ->getDefinition($entity_type);
    $added = 0;
    $updated = 0;
    if ($entity_definition
      ->hasKey('bundle') && $entity_type_bundle) {
      $content[$entity_definition
        ->getKey('bundle')] = $this->configuration['entity_type_bundle'];
    }
    foreach ($content as $key => $item) {
      if (is_string($item) && file_exists($item)) {
        $created = file_save_data(file_get_contents($item), $this->config
          ->get('system.file')
          ->get('default_scheme') . '://' . basename($item), FileSystemInterface::EXISTS_REPLACE);
        $content[$key] = $created
          ->id();
      }
    }

    /** @var \Drupal\Core\Entity\Sql\SqlContentEntityStorage $entity_storage  */
    $entity_storage = $this->entityTypeManager
      ->getStorage($this->configuration['entity_type']);
    try {
      if (isset($content[$entity_definition
        ->getKeys()['id']]) && ($entity = $entity_storage
        ->load($content[$entity_definition
        ->getKeys()['id']]))) {

        /** @var \Drupal\Core\Entity\ContentEntityInterface $entity  */
        foreach ($content as $id => $set) {
          $entity
            ->set($id, $set);
        }
        if ($entity
          ->save()) {
          $context['results']['updated'][] = $entity
            ->id();
        }
      }
      else {

        /** @var \Drupal\Core\Entity\ContentEntityInterface $entity  */
        $entity = $this->entityTypeManager
          ->getStorage($this->configuration['entity_type'])
          ->create($content);
        if ($entity
          ->save()) {
          $context['results']['added'][] = $entity
            ->id();
        }
      }
    } catch (\Exception $e) {
    }
  }

  /**
   * {@inheritdoc}
   */
  public function finished($success, array $results, array $operations) {
    $message = '';
    if ($success) {
      $message = $this
        ->t('@count_added content added and @count_updated updated', [
        '@count_added' => isset($results['added']) ? count($results['added']) : 0,
        '@count_updated' => isset($results['updated']) ? count($results['updated']) : 0,
      ]);
    }
    $this
      ->messenger()
      ->addMessage($message);
  }

  /**
   * {@inheritdoc}
   */
  public function process() {
    if ($data = $this
      ->data()) {
      foreach ($data['content'] as $content) {
        $process['operations'][] = [
          [
            $this,
            'add',
          ],
          [
            $content,
          ],
        ];
      }
    }
    $process['finished'] = [
      $this,
      'finished',
    ];
    batch_set($process);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
ImporterBase::$config protected property The config service.
ImporterBase::$entityTypeManager protected property The entity type manager service.
ImporterBase::add public function Add content. Overrides ImporterInterface::add
ImporterBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
ImporterBase::data public function Prepare data for import. Overrides ImporterInterface::data
ImporterBase::finished public function Batch finish handler. Overrides ImporterInterface::finished
ImporterBase::process public function Run batch operations. Overrides ImporterInterface::process
ImporterBase::__construct public function Constructs ImporterBase object. Overrides PluginBase::__construct
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.