You are here

abstract class FieldTargetBase in Feeds 8.3

Helper class for field mappers.

Hierarchy

Expanded class hierarchy of FieldTargetBase

12 files declare their use of FieldTargetBase
Boolean.php in src/Feeds/Target/Boolean.php
ConfigEntityReference.php in src/Feeds/Target/ConfigEntityReference.php
DateTargetBase.php in src/Feeds/Target/DateTargetBase.php
Email.php in src/Feeds/Target/Email.php
EntityReference.php in src/Feeds/Target/EntityReference.php

... See full list

File

src/Plugin/Type/Target/FieldTargetBase.php, line 21

Namespace

Drupal\feeds\Plugin\Type\Target
View source
abstract class FieldTargetBase extends TargetBase implements ConfigurableTargetInterface, TranslatableTargetInterface {

  /**
   * The field settings.
   *
   * @var array
   */
  protected $fieldSettings;

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

  /**
   * {@inheritdoc}
   */
  public static function targets(array &$targets, FeedTypeInterface $feed_type, array $definition) {
    $processor = $feed_type
      ->getProcessor();
    if (!$processor instanceof EntityProcessorInterface) {
      return $targets;
    }
    $field_definitions = \Drupal::service('entity_field.manager')
      ->getFieldDefinitions($processor
      ->entityType(), $processor
      ->bundle());
    foreach ($field_definitions as $id => $field_definition) {
      if (isset($targets[$id])) {
        continue;
      }
      if ($id === $processor
        ->bundleKey()) {
        continue;
      }
      if (in_array($field_definition
        ->getType(), $definition['field_types'])) {
        if ($target = static::prepareTarget($field_definition)) {
          $target
            ->setPluginId($definition['id']);
          $targets[$id] = $target;
        }
      }
    }
  }

  /**
   * Prepares a target definition.
   *
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The field definition.
   *
   * @return \Drupal\feeds\FieldTargetDefinition
   *   The target definition.
   */
  protected static function prepareTarget(FieldDefinitionInterface $field_definition) {
    return FieldTargetDefinition::createFromFieldDefinition($field_definition)
      ->addProperty('value');
  }

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, array $plugin_definition) {
    $this->targetDefinition = $configuration['target_definition'];
    $this->settings = $this->targetDefinition
      ->getFieldDefinition()
      ->getSettings();
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * {@inheritdoc}
   */
  public function setTarget(FeedInterface $feed, EntityInterface $entity, $field_name, array $values) {
    if ($values = $this
      ->prepareValues($values)) {
      $entity_target = $this
        ->getEntityTarget($feed, $entity);
      if (!empty($entity_target)) {
        $item_list = $entity_target
          ->get($field_name);

        // Append these values to the existing values.
        $values = array_merge($item_list
          ->getValue(), $values);
        $item_list
          ->setValue($values);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function isMutable() {
    return !$this->targetDefinition
      ->getFieldDefinition()
      ->isReadOnly();
  }

  /**
   * {@inheritdoc}
   */
  public function isEmpty(FeedInterface $feed, EntityInterface $entity, $field_name) {
    return $entity
      ->get($field_name)
      ->isEmpty();
  }

  /**
   * Get entity, or entity translation to set the map.
   *
   * @param \Drupal\feeds\FeedInterface $feed
   *   The feed.
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity to import.
   *
   * @see \Drupal\feeds\Plugin\Type\Target\FieldTargetBase::isTargetTranslatable()
   *
   * @return \Drupal\Core\Entity\EntityInterface|null
   *   Self entity or entity translation.
   */
  public function getEntityTarget(FeedInterface $feed, EntityInterface $entity) {
    if ($entity instanceof TranslatableInterface && $this
      ->isTargetTranslatable()) {
      if ($this
        ->languageExists()) {
        $processor = $feed
          ->getType()
          ->getProcessor();
        if ($processor instanceof EntityProcessorInterface) {
          return $processor
            ->getEntityTranslation($feed, $entity, $this
            ->getLangcode());
        }
      }
      return;
    }
    return $entity;
  }

  /**
   * Prepares the the values that will be mapped to an entity.
   *
   * @param array $values
   *   The values.
   */
  protected function prepareValues(array $values) {
    $return = [];
    foreach ($values as $delta => $columns) {
      try {
        $this
          ->prepareValue($delta, $columns);
        $return[] = $columns;
      } catch (EmptyFeedException $e) {

        // Nothing wrong here.
      } catch (TargetValidationException $e) {

        // Validation failed.
        $this
          ->addMessage($e
          ->getFormattedMessage(), 'error');
      }
    }
    return $return;
  }

  /**
   * Prepares a single value.
   *
   * @param int $delta
   *   The field delta.
   * @param array $values
   *   The values.
   */
  protected function prepareValue($delta, array &$values) {
    foreach ($values as $column => $value) {
      $values[$column] = (string) $value;
    }
  }

  /**
   * Constructs a base query which is used to find an existing entity.
   *
   * @return \Drupal\Core\Entity\Query\QueryInterface
   *   An entity query.
   *
   * @see ::getUniqueValue()
   */
  protected function getUniqueQuery() {
    return \Drupal::entityQuery($this->feedType
      ->getProcessor()
      ->entityType())
      ->range(0, 1)
      ->accessCheck(FALSE);
  }

  /**
   * Looks for an existing entity and returns an entity ID if found.
   *
   * @param \Drupal\feeds\FeedInterface $feed
   *   The feed that is being processed.
   * @param string $target
   *   The ID of the field target plugin.
   * @param string $key
   *   The property of the field to search on.
   * @param string $value
   *   The value to look for.
   *
   * @return string|int|null
   *   An entity ID, if found. Null otherwise.
   */
  public function getUniqueValue(FeedInterface $feed, $target, $key, $value) {
    $base_fields = \Drupal::service('entity_field.manager')
      ->getBaseFieldDefinitions($this->feedType
      ->getProcessor()
      ->entityType());
    if (isset($base_fields[$target])) {
      $field = $target;
    }
    else {
      $field = "{$target}.{$key}";
    }

    // Construct "Unique" query.
    $query = $this
      ->getUniqueQuery()
      ->condition($field, $value);

    // Restrict search to the same bundle if the entity type we import for
    // supports bundles.
    $bundle_key = $this->feedType
      ->getProcessor()
      ->bundleKey();
    if ($bundle_key) {
      $query
        ->condition($bundle_key, $this->feedType
        ->getProcessor()
        ->bundle());
    }

    // Execute "Unique" query.
    if ($result = $query
      ->execute()) {
      return reset($result);
    }
  }

  /**
   * Returns the messenger to use.
   *
   * @return \Drupal\Core\Messenger\MessengerInterface
   *   The messenger service.
   */
  protected function getMessenger() {
    return \Drupal::messenger();
  }

  /**
   * Adds a message.
   *
   * @param string|\Drupal\Component\Render\MarkupInterface $message
   *   The translated message to be displayed to the user.
   * @param string $type
   *   (optional) The message's type.
   * @param bool $repeat
   *   (optional) If this is FALSE and the message is already set, then the
   *   message won't be repeated. Defaults to FALSE.
   */
  protected function addMessage($message, $type = 'status', $repeat = FALSE) {
    $this
      ->getMessenger()
      ->addMessage($message, $type, $repeat);
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    $this->dependencies = parent::calculateDependencies();

    // Add the configured field as a dependency.
    $field_definition = $this->targetDefinition
      ->getFieldDefinition();
    if ($field_definition && $field_definition instanceof EntityInterface) {
      $this->dependencies['config'][] = $field_definition
        ->getConfigDependencyName();
    }
    return $this->dependencies;
  }

  /**
   * {@inheritdoc}
   */
  public function onDependencyRemoval(array $dependencies) {

    // See if this target is responsible for any of the dependencies being
    // removed. If this is the case, indicate that the mapping that uses this
    // target needs to be removed from the feed type.
    $remove = FALSE;

    // Get all the current dependencies for this target.
    $current_dependencies = $this
      ->calculateDependencies();
    foreach ($current_dependencies as $group => $dependency_list) {

      // Check if any of the target dependencies match the dependencies being
      // removed.
      foreach ($dependency_list as $config_key) {
        if (isset($dependencies[$group]) && array_key_exists($config_key, $dependencies[$group])) {

          // This targets dependency matches a dependency being removed,
          // indicate that mapping using this target needs to be removed.
          $remove = TRUE;
          break 2;
        }
      }
    }
    return $remove;
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    $configuration = [];
    if ($this
      ->isTargetFieldTranslatable()) {
      $configuration['language'] = NULL;
    }
    return $configuration;
  }

  /**
   * {@inheritdoc}
   */
  public function getSummary() {
    $summary = [];
    if (!$this
      ->isMutable()) {
      $summary[] = $this
        ->t('Read only');
    }
    if ($this
      ->isTargetTranslatable()) {
      $language = $this
        ->getLanguageManager()
        ->getLanguage($this->configuration['language']);
      if ($language instanceof LanguageInterface) {
        $summary[] = $this
          ->t('Language: @language', [
          '@language' => $language
            ->getName(),
        ]);
      }
    }
    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    if ($this
      ->isTargetFieldTranslatable()) {
      $languages = $this
        ->getLanguageManager()
        ->getLanguages();
      $options = [
        '' => $this
          ->t('Default'),
      ];
      foreach ($languages as $langcode => $language) {
        $options[$langcode] = $language
          ->getName();
      }
      $language_default = !empty($this->configuration['language']) ? $this->configuration['language'] : '';
      $form['language'] = [
        '#title' => $this
          ->t('Language'),
        '#options' => $options,
        '#type' => 'select',
        '#default_value' => $language_default,
      ];
    }
    return $form;
  }

  /**
   * Gets the language manager.
   *
   * @return \Drupal\Core\Language\LanguageManagerInterface
   *   The language manager.
   */
  protected function getLanguageManager() {
    if (!isset($this->languageManager)) {
      $this
        ->setLanguageManager(\Drupal::service('language_manager'));
    }
    return $this->languageManager;
  }

  /**
   * Sets the language manager.
   *
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager.
   */
  public function setLanguageManager(LanguageManagerInterface $language_manager) {
    $this->languageManager = $language_manager;
  }

  /**
   * {@inheritdoc}
   */
  public function languageExists() {
    return $this
      ->getLanguageManager()
      ->getLanguage($this->configuration['language']) instanceof LanguageInterface;
  }

  /**
   * {@inheritdoc}
   */
  public function isTargetTranslatable() {
    return $this
      ->isTargetFieldTranslatable() && !empty($this->configuration['language']);
  }

  /**
   * Checks if the targeted field is translatable.
   *
   * @return bool
   *   True if the field is translatable. False otherwise.
   */
  protected function isTargetFieldTranslatable() {
    $field_storage = $this->targetDefinition
      ->getFieldDefinition()
      ->getFieldStorageDefinition();
    return !empty($field_storage) && $field_storage
      ->isTranslatable();
  }

  /**
   * {@inheritdoc}
   */
  public function getLangcode() {
    if (!empty($this->configuration['language'])) {
      return $this->configuration['language'];
    }

    // Get the language from the processor, if the processor has one.
    $processor = $this->feedType
      ->getProcessor();
    if ($processor instanceof EntityProcessorInterface) {
      return $processor
        ->entityLanguage();
    }

    // Return default language.
    return $this
      ->getLanguageManager()
      ->getDefaultLanguage()
      ->getId();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigurablePluginBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm
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
DependencyTrait::$dependencies protected property The object's dependencies.
DependencyTrait::addDependencies protected function Adds multiple dependencies.
DependencyTrait::addDependency protected function Adds a dependency.
FieldTargetBase::$fieldSettings protected property The field settings.
FieldTargetBase::$languageManager protected property The language manager.
FieldTargetBase::addMessage protected function Adds a message.
FieldTargetBase::buildConfigurationForm public function Form constructor. Overrides TargetBase::buildConfigurationForm 6
FieldTargetBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides PluginBase::calculateDependencies
FieldTargetBase::defaultConfiguration public function Gets default configuration for this plugin. Overrides TargetBase::defaultConfiguration 6
FieldTargetBase::getEntityTarget public function Get entity, or entity translation to set the map.
FieldTargetBase::getLangcode public function Gets the configured language. Overrides TranslatableTargetInterface::getLangcode
FieldTargetBase::getLanguageManager protected function Gets the language manager.
FieldTargetBase::getMessenger protected function Returns the messenger to use.
FieldTargetBase::getSummary public function Returns the summary for a target. Overrides ConfigurableTargetInterface::getSummary 6
FieldTargetBase::getUniqueQuery protected function Constructs a base query which is used to find an existing entity.
FieldTargetBase::getUniqueValue public function Looks for an existing entity and returns an entity ID if found.
FieldTargetBase::isEmpty public function Returns if the value for the target is empty. Overrides TargetInterface::isEmpty
FieldTargetBase::isMutable public function Returns if the target is mutable. Overrides TargetInterface::isMutable 1
FieldTargetBase::isTargetFieldTranslatable protected function Checks if the targeted field is translatable.
FieldTargetBase::isTargetTranslatable public function Checks if the target is translatable. Overrides TranslatableTargetInterface::isTargetTranslatable
FieldTargetBase::languageExists public function Checks if the language selected on the target exists. Overrides TranslatableTargetInterface::languageExists
FieldTargetBase::onDependencyRemoval public function Allows a plugin to define whether it should be removed. Overrides TargetBase::onDependencyRemoval
FieldTargetBase::prepareTarget protected static function Prepares a target definition. 10
FieldTargetBase::prepareValue protected function Prepares a single value. 12
FieldTargetBase::prepareValues protected function Prepares the the values that will be mapped to an entity.
FieldTargetBase::setLanguageManager public function Sets the language manager.
FieldTargetBase::setTarget public function Sets the values on an object. Overrides TargetInterface::setTarget 4
FieldTargetBase::targets public static function Returns the targets defined by this plugin. Overrides TargetInterface::targets 1
FieldTargetBase::__construct public function Constructs a TargetBase object. Overrides TargetBase::__construct 5
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::$feedType protected property The importer this plugin is working for.
PluginBase::$linkGenerator protected property The link generator.
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::$urlGenerator protected property The url generator.
PluginBase::container private function Returns the service container.
PluginBase::defaultFeedConfiguration public function Returns default feed configuration. Overrides FeedsPluginInterface::defaultFeedConfiguration 3
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::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
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::l protected function Renders a link to a route given a route name and its parameters.
PluginBase::linkGenerator protected function Returns the link generator service.
PluginBase::onFeedDeleteMultiple public function A feed is being deleted. 3
PluginBase::onFeedSave public function A feed is being saved.
PluginBase::onFeedTypeDelete public function The feed type is being deleted. 1
PluginBase::onFeedTypeSave public function The feed type is being saved. 1
PluginBase::pluginType public function Returns the type of plugin. Overrides FeedsPluginInterface::pluginType
PluginBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration 1
PluginBase::url protected function Generates a URL or path for a specific route based on the given parameters.
PluginBase::urlGenerator protected function Returns the URL generator service.
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.
TargetBase::$targetDefinition protected property The target definition.
TargetBase::getTargetDefinition public function Returns the target's definition. Overrides TargetInterface::getTargetDefinition
TargetBase::submitConfigurationForm public function Form submission handler. Overrides ConfigurablePluginBase::submitConfigurationForm