You are here

class EntityReferenceImportProcessor in YAML Content 8.2

Import processor to support entity queries and references.

Plugin annotation


@ImportProcessor(
  id = "entity_reference_import_processor",
  label = @Translation("Entity Reference Import Processor"),
  context = {
    "entity_type" = @ContextDefinition(
      "any",
      label = @Translation("Entity type"),
      required = "TRUE"
    ),
    "bundle" = @ContextDefinition(
      "any",
      label = @Translation("Bundle"),
      required = "FALSE"
    ),
    "type" = @ContextDefinition(
      "any",
      label = @Translation("Content type"),
      required = "FALSE"
    ),
    "limit" = @ContextDefinition(
      "any",
      label = @Translation("Result limit"),
      required = "FALSE"
    ),
    "conditions" = @ContextDefinition(
      "any",
      label = @Translation("Query conditions"),
      required = "FALSE"
    ),
  }
)

Hierarchy

Expanded class hierarchy of EntityReferenceImportProcessor

File

src/Plugin/YamlContent/EntityReferenceImportProcessor.php, line 43

Namespace

Drupal\yaml_content\Plugin\YamlContent
View source
class EntityReferenceImportProcessor extends ImportProcessorBase {

  /**
   * Query object used to build and execute the entity search.
   *
   * @var \Drupal\Core\Entity\Query\QueryInterface
   */
  protected $query;

  /**
   * {@inheritdoc}
   */
  public function preprocess(array &$import_data) {
    if (!$this->query) {
      $this
        ->buildQuery();
    }
    $results = $this->query
      ->execute();
    if (empty($results)) {

      // @todo Handle empty result sets.

      //return $this->noResults();
    }
    $this
      ->processResults($import_data, $results);
  }

  /**
   * Build and prepare the the entity query with configured filters.
   *
   * All filters are applied using the addQueryFilter() method. After executing
   * this method, the entity query object itself is available from the $query
   * property.
   *
   * @return \Drupal\Core\Entity\Query\QueryInterface
   *   The prepared query object using defined configuration.
   */
  protected function buildQuery() {
    $entity_type = $this
      ->getContextValue('entity_type');
    $this->query = \Drupal::entityQuery($entity_type);
    $this
      ->applyFilters();
    return $this->query;
  }

  /**
   * Apply configured filters to the query object.
   *
   * @todo Add support for `range()` operator instead of just `limit`.
   * @todo Add support for `condition()` operators.
   */
  protected function applyFilters() {
    $context = $this
      ->getContextValues();
    foreach ($context as $name => $value) {

      // Only apply filters for populated values.
      if (!is_null($value)) {

        // Handle special cases.
        switch ($name) {

          // Entity type should be already applied at query creation and require
          // nothing further.
          case 'entity_type':
            break;

          // Specially handle a `bundle` or `type` key for convenience.
          case 'bundle':
          case 'type':
            $this->query
              ->condition('type', $value);
            break;
          case 'limit':

            // Assume starting at 0 to apply limit only.
            $this->query
              ->range(0, $value);
            break;
          case 'conditions':
            foreach ($value as $field => $filter) {
              $op = is_array($filter) ? 'IN' : '=';
              $this->query
                ->condition($field, $filter, $op);
            }
        }
      }
    }
  }

  /**
   * Apply property filter to the entity query.
   *
   * This method may be overridden to provide further processing or mapping of
   * property values as needed for filters.
   *
   * @param string $entity_type
   *   The machine name for the entity type being queried.
   * @param string $property
   *   A property being filtered. All property definitions are compatible with
   *   those described in QueryInterface::condition().
   * @param mixed $value
   *   The value filtered in this condition.
   *
   * @see \Drupal\Core\Entity\Query\QueryInterface::condition()
   */
  protected function addQueryFilter($entity_type, $property, $value) {
    $this->query
      ->condition($property, $value);
  }

  /**
   * Handle behavior when no matches were found.
   *
   * @throws \Drupal\yaml_content\Plugin\YamlContent\MissingDataException
   */
  protected function noResults() {
    $entity_type = $this->configuration['entity_type'];
    $filters = $this->configuration['filters'];
    $error = 'Unable to find referenced content of type %type matching: @filters';
    throw new MissingDataException(__CLASS__ . ': ' . $this
      ->t($error, [
      '%type' => $entity_type,
      '@filters' => print_r($filters, TRUE),
    ]));
  }

  /**
   * Process entity ID results into expected content structure.
   *
   * @param array $import_data
   *   Import data as loaded form a content file.
   * @param array $result_set
   *   The result data identified by the executed query.
   */
  protected function processResults(array &$import_data, array $result_set) {

    // Format and append entity reference value.
    foreach ($result_set as $entity_id) {
      $import_data[] = [
        'target_id' => $entity_id,
      ];
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ContextAwarePluginBase::$context protected property The data objects representing the context of this plugin.
ContextAwarePluginBase::$contexts Deprecated private property Data objects representing the contexts passed in the plugin configuration.
ContextAwarePluginBase::contextHandler protected function Wraps the context handler.
ContextAwarePluginBase::createContextFromConfiguration protected function Overrides ContextAwarePluginBase::createContextFromConfiguration
ContextAwarePluginBase::getCacheContexts public function The cache contexts associated with this object. Overrides CacheableDependencyInterface::getCacheContexts 9
ContextAwarePluginBase::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides CacheableDependencyInterface::getCacheMaxAge 7
ContextAwarePluginBase::getCacheTags public function The cache tags associated with this object. Overrides CacheableDependencyInterface::getCacheTags 4
ContextAwarePluginBase::getContext public function This code is identical to the Component in order to pick up a different Context class. Overrides ContextAwarePluginBase::getContext
ContextAwarePluginBase::getContextDefinition public function Overrides ContextAwarePluginBase::getContextDefinition
ContextAwarePluginBase::getContextDefinitions public function Overrides ContextAwarePluginBase::getContextDefinitions
ContextAwarePluginBase::getContextMapping public function Gets a mapping of the expected assignment names to their context names. Overrides ContextAwarePluginInterface::getContextMapping
ContextAwarePluginBase::getContexts public function Gets the defined contexts. Overrides ContextAwarePluginInterface::getContexts
ContextAwarePluginBase::getContextValue public function Gets the value for a defined context. Overrides ContextAwarePluginInterface::getContextValue
ContextAwarePluginBase::getContextValues public function Gets the values for all defined contexts. Overrides ContextAwarePluginInterface::getContextValues
ContextAwarePluginBase::setContext public function Set a context on this plugin. Overrides ContextAwarePluginBase::setContext
ContextAwarePluginBase::setContextMapping public function Sets a mapping of the expected assignment names to their context names. Overrides ContextAwarePluginInterface::setContextMapping
ContextAwarePluginBase::setContextValue public function Sets the value for a defined context. Overrides ContextAwarePluginBase::setContextValue
ContextAwarePluginBase::validateContexts public function Validates the set values for the defined contexts. Overrides ContextAwarePluginInterface::validateContexts
ContextAwarePluginBase::__construct public function Overrides \Drupal\Component\Plugin\PluginBase::__construct(). Overrides PluginBase::__construct 4
ContextAwarePluginBase::__get public function Implements magic __get() method.
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
EntityReferenceImportProcessor::$query protected property Query object used to build and execute the entity search.
EntityReferenceImportProcessor::addQueryFilter protected function Apply property filter to the entity query.
EntityReferenceImportProcessor::applyFilters protected function Apply configured filters to the query object.
EntityReferenceImportProcessor::buildQuery protected function Build and prepare the the entity query with configured filters.
EntityReferenceImportProcessor::noResults protected function Handle behavior when no matches were found.
EntityReferenceImportProcessor::preprocess public function Pre-process import data and manipulate it prior to content creation. Overrides ImportProcessorBase::preprocess
EntityReferenceImportProcessor::processResults protected function Process entity ID results into expected content structure.
ImportProcessorBase::$import public property Indicate that this plugin supports import operations.
ImportProcessorBase::postprocess public function Post-process imported content after it has been instantiated. Overrides ImportProcessorInterface::postprocess 1
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.
TypedDataTrait::$typedDataManager protected property The typed data manager used for creating the data types.
TypedDataTrait::getTypedDataManager public function Gets the typed data manager. 2
TypedDataTrait::setTypedDataManager public function Sets the typed data manager. 2