You are here

class DefaultDataProcessor in Entity Share 8.3

General default data processor.

Plugin annotation


@ImportProcessor(
  id = "default_data_processor",
  label = @Translation("Default data processor"),
  description = @Translation("General JSON data preparation to have Entity Share import working."),
  stages = {
    "is_entity_importable" = -10,
    "prepare_importable_entity_data" = -100,
    "post_entity_save" = 0,
  },
  locked = true,
)

Hierarchy

Expanded class hierarchy of DefaultDataProcessor

File

modules/entity_share_client/src/Plugin/EntityShareClient/Processor/DefaultDataProcessor.php, line 28

Namespace

Drupal\entity_share_client\Plugin\EntityShareClient\Processor
View source
class DefaultDataProcessor extends ImportProcessorPluginBase {

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

  /**
   * Logger.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * The Entity import state information service.
   *
   * @var \Drupal\entity_share_client\Service\StateInformationInterface
   */
  protected $stateInformation;

  /**
   * The Drupal datetime service.
   *
   * @var \Drupal\Component\Datetime\TimeInterface
   */
  protected $time;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    $instance->entityTypeManager = $container
      ->get('entity_type.manager');
    $instance->logger = $container
      ->get('logger.channel.entity_share_client');
    $instance->languageManager = $container
      ->get('language_manager');
    $instance->stateInformation = $container
      ->get('entity_share_client.state_information');
    $instance->time = $container
      ->get('datetime.time');
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  public function isEntityImportable(RuntimeImportContext $runtime_import_context, array $entity_json_data) {
    $field_mappings = $runtime_import_context
      ->getFieldMappings();
    $parsed_type = explode('--', $entity_json_data['type']);
    $entity_type_id = $parsed_type[0];
    $entity_bundle = $parsed_type[1];

    // @todo Refactor in attributes to avoid getting entity keys each time.
    $entity_storage = $this->entityTypeManager
      ->getStorage($entity_type_id);
    $entity_keys = $entity_storage
      ->getEntityType()
      ->getKeys();
    $langcode_public_name = FALSE;
    if (!empty($entity_keys['langcode']) && isset($field_mappings[$entity_type_id][$entity_bundle][$entity_keys['langcode']])) {
      $langcode_public_name = $field_mappings[$entity_type_id][$entity_bundle][$entity_keys['langcode']];
    }
    $data_langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED;
    if ($langcode_public_name && !empty($entity_json_data['attributes'][$langcode_public_name])) {
      $data_langcode = $entity_json_data['attributes'][$langcode_public_name];
    }

    // Check if we try to import an entity with langcode in a disabled language.
    if (is_null($this->languageManager
      ->getLanguage($data_langcode))) {

      // Use the entity type if there is no label.
      $entity_label = $entity_type_id;

      // Prepare entity label.
      if (isset($entity_keys['label']) && isset($field_mappings[$entity_type_id][$entity_bundle][$entity_keys['label']])) {
        $label_public_name = $field_mappings[$entity_type_id][$entity_bundle][$entity_keys['label']];
        if (!empty($entity_json_data['attributes'][$label_public_name])) {
          $entity_label = $entity_json_data['attributes'][$label_public_name];
        }
      }
      $log_variables = [
        '%entity_label' => $entity_label,
      ];
      $this->logger
        ->error('Trying to import an entity (%entity_label) in a disabled language.', $log_variables);
      $this
        ->messenger()
        ->addError($this
        ->t('Trying to import an entity (%entity_label) in a disabled language.', $log_variables));
      return FALSE;
    }
    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function prepareImportableEntityData(RuntimeImportContext $runtime_import_context, array &$entity_json_data) {
    $field_mappings = $runtime_import_context
      ->getFieldMappings();
    $parsed_type = explode('--', $entity_json_data['type']);
    $entity_type_id = $parsed_type[0];
    $entity_bundle = $parsed_type[1];

    // @todo Refactor in attributes to avoid getting entity keys each time.
    $entity_storage = $this->entityTypeManager
      ->getStorage($entity_type_id);
    $entity_keys = $entity_storage
      ->getEntityType()
      ->getKeys();
    $entity_keys_to_remove = [
      'id',
      'revision',
      // Remove the default_langcode boolean to be able to import content not
      // necessarily in the default language.
      'default_langcode',
    ];
    foreach ($entity_keys_to_remove as $entity_key_to_remove) {
      if (!isset($entity_keys[$entity_key_to_remove])) {
        continue;
      }

      // If there is nothing in the field mapping, the field should have been
      // disabled on the server website using JSON:API extras.
      if (!isset($field_mappings[$entity_type_id][$entity_bundle][$entity_keys[$entity_key_to_remove]])) {
        continue;
      }
      $public_name_to_remove = $field_mappings[$entity_type_id][$entity_bundle][$entity_keys[$entity_key_to_remove]];
      if (isset($entity_json_data['attributes'][$public_name_to_remove])) {
        unset($entity_json_data['attributes'][$public_name_to_remove]);
      }
    }

    // UUID is no longer included as attribute.
    $uuid_public_name = 'uuid';
    if (!empty($entity_keys['uuid']) && isset($field_mappings[$entity_type_id][$entity_bundle][$entity_keys['uuid']])) {
      $uuid_public_name = $field_mappings[$entity_type_id][$entity_bundle][$entity_keys['uuid']];
    }
    $entity_json_data['attributes'][$uuid_public_name] = $entity_json_data['id'];
  }

  /**
   * {@inheritdoc}
   */
  public function postEntitySave(RuntimeImportContext $runtime_import_context, ContentEntityInterface $processed_entity) {

    // Create or update the dedicated "Entity import status" entity.
    // At this point the entity has been successfully imported.
    $import_status_entity = $this->stateInformation
      ->getImportStatusOfEntity($processed_entity);
    if (!$import_status_entity) {

      // If a dedicated "Entity import status" entity doesn't exist (which
      // means that either this is a new imported entity, or it is a "legacy"
      // content imported before the introduction of "Entity import status"
      // entities), create it.
      $parameters = [
        'remote_website' => $runtime_import_context
          ->getRemote()
          ->id(),
        'channel_id' => $runtime_import_context
          ->getChannelId(),
      ];
      $this->stateInformation
        ->createImportStatusOfEntity($processed_entity, $parameters);
    }
    else {

      // "Entity import status" exists, just update the last import timestamp.
      $import_status_entity
        ->setLastImport($this->time
        ->getRequestTime())
        ->save();
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DefaultDataProcessor::$entityTypeManager protected property The entity type manager.
DefaultDataProcessor::$languageManager protected property The language manager.
DefaultDataProcessor::$logger protected property Logger.
DefaultDataProcessor::$stateInformation protected property The Entity import state information service.
DefaultDataProcessor::$time protected property The Drupal datetime service.
DefaultDataProcessor::create public static function Creates an instance of the plugin. Overrides ImportProcessorPluginBase::create
DefaultDataProcessor::isEntityImportable public function Method called on STAGE_IS_ENTITY_IMPORTABLE. Overrides ImportProcessorPluginBase::isEntityImportable
DefaultDataProcessor::postEntitySave public function Method called on STAGE_POST_ENTITY_SAVE. Overrides ImportProcessorPluginBase::postEntitySave
DefaultDataProcessor::prepareImportableEntityData public function Method called on STAGE_PREPARE_IMPORTABLE_ENTITY_DATA. Overrides ImportProcessorPluginBase::prepareImportableEntityData
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
ImportProcessorInterface::STAGE_IS_ENTITY_IMPORTABLE constant Processing stage: is entity importable.
ImportProcessorInterface::STAGE_POST_ENTITY_SAVE constant Processing stage: post entity save.
ImportProcessorInterface::STAGE_PREPARE_ENTITY_DATA constant Processing stage: prepare entity data.
ImportProcessorInterface::STAGE_PREPARE_IMPORTABLE_ENTITY_DATA constant Processing stage: prepare importable entity data.
ImportProcessorInterface::STAGE_PROCESS_ENTITY constant Processing stage: process entity.
ImportProcessorPluginBase::defaultConfiguration public function Gets default configuration for this plugin. Overrides ConfigurableInterface::defaultConfiguration 3
ImportProcessorPluginBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
ImportProcessorPluginBase::getDescription public function Returns the plugin's description. Overrides ImportProcessorInterface::getDescription
ImportProcessorPluginBase::getWeight public function Returns the weight for a specific processing stage. Overrides ImportProcessorInterface::getWeight
ImportProcessorPluginBase::isLocked public function Determines whether this processor should always be enabled. Overrides ImportProcessorInterface::isLocked
ImportProcessorPluginBase::label public function Returns the label for use on the administration pages. Overrides ImportProcessorInterface::label
ImportProcessorPluginBase::prepareEntityData public function Method called on STAGE_PREPARE_ENTITY_DATA. Overrides ImportProcessorInterface::prepareEntityData
ImportProcessorPluginBase::processEntity public function Method called on STAGE_PROCESS_ENTITY. Overrides ImportProcessorInterface::processEntity 4
ImportProcessorPluginBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
ImportProcessorPluginBase::setWeight public function Sets the weight for a specific processing stage. Overrides ImportProcessorInterface::setWeight
ImportProcessorPluginBase::submitConfigurationForm public function Form submission handler.
ImportProcessorPluginBase::supportsStage public function Checks whether this processor implements a particular stage. Overrides ImportProcessorInterface::supportsStage
ImportProcessorPluginBase::validateConfigurationForm public function Form validation handler.
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.
PluginBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. 92
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.