Skip to content

Instantly share code, notes, and snippets.

@simesy
Last active March 27, 2018 03:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simesy/755897d43b24e06afeed to your computer and use it in GitHub Desktop.
Save simesy/755897d43b24e06afeed to your computer and use it in GitHub Desktop.
Migrate process plugin: entity_lookup
<?php
/**
* @file
* Contains \Drupal\migrate_entity_lookup\Plugin\migrate\process\EntityLookup.
*/
namespace Drupal\migrate_entity_lookup\Plugin\migrate\process;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;
use Drupal\migrate\MigrateException;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* This plugin changes the current value by using it for an entity property search
* and returning an entity id.
*
* @MigrateProcessPlugin(
* id = "entity_lookup"
* )
*/
class EntityLookup extends ProcessPluginBase implements ContainerFactoryPluginInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityQuery;
/**
* Constructs an EntityLookup 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 mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Entity\Query\QueryFactory $entity_query
* The entity query factory.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, QueryFactory $entity_query) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityQuery = $entity_query;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity.query')
);
}
/**
* {@inheritdoc}
*/
public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
if (empty($value)) {
// @todo: allow a default_value if nothing in source.
return null;
}
else {
$query = $this->entityQuery->get($this->configuration['entity_type']);
$entity_ids = $query->condition($this->configuration['property'], $value)->range(0, 1)->execute();
if (count($entity_ids)) {
return reset($entity_ids);
}
else {
// @todo: Return a default value if failed to retrieve one.
return null;
}
}
}
}
process:
field_dest:
plugin: entity_lookup
source: source_field
entity_type: taxonomy_term
property: name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment