Skip to content

Instantly share code, notes, and snippets.

@simesy
Last active March 27, 2018 03:07
Show Gist options
  • 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\MigrateException;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;
use Drupal\Core\Entity\EntityTypeManagerInterface;
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 $entityTypeManager;
/**
* 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 array $entity_type_manager
* The entity type manager.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@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')
);
}
/**
* {@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 {
$storage = $this->entityTypeManager->getStorage($this->configuration['entity_type']);
$query = $storage->getQuery();
$entity_ids = $query->condition($this->configuration['property'], $value)->range(0, 1)->execute();
// drush_print_r(array($this->configuration['entity_type'], $this->configuration['property'], $value, $entity_ids));
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