3 namespace Drupal\migrate_plus\Plugin\migrate\process;
5 use Drupal\Core\Entity\EntityManagerInterface;
6 use Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface;
7 use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
8 use Drupal\migrate\Plugin\MigrationInterface;
9 use Drupal\migrate\MigrateException;
10 use Drupal\migrate\MigrateExecutableInterface;
11 use Drupal\migrate\ProcessPluginBase;
12 use Drupal\migrate\Row;
13 use Symfony\Component\DependencyInjection\ContainerInterface;
16 * This plugin looks for existing entities.
18 * @MigrateProcessPlugin(
19 * id = "entity_lookup",
20 * handle_multiples = TRUE
23 * In its most simple form, this plugin needs no configuration. However, if the
24 * lookup properties cannot be determined through introspection, define them via
27 * Example usage with minimal configuration:
30 * plugin: 'entity:node'
33 * plugin: default_value
36 * plugin: entity_lookup
40 * Example usage with full configuration:
43 * plugin: entity_lookup
48 * entity_type: taxonomy_term
52 class EntityLookup extends ProcessPluginBase implements ContainerFactoryPluginInterface {
57 * @var \Drupal\Core\Entity\EntityManagerInterface
59 protected $entityManager;
64 * @var \Drupal\migrate\Plugin\MigrationInterface
69 * The selection plugin.
71 * @var \Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface
73 protected $selectionPluginManager;
76 * The destination type.
80 protected $destinationEntityType;
83 * The destination bundle.
87 protected $destinationBundleKey;
90 * The lookup value's key.
94 protected $lookupValueKey;
97 * The lookup bundle's key.
101 protected $lookupBundleKey;
108 protected $lookupBundle;
111 * The lookup entity type.
115 protected $lookupEntityType;
118 * The destination property or field.
122 protected $destinationProperty;
127 public function __construct(array $configuration, $pluginId, $pluginDefinition, MigrationInterface $migration, EntityManagerInterface $entityManager, SelectionPluginManagerInterface $selectionPluginManager) {
128 parent::__construct($configuration, $pluginId, $pluginDefinition);
129 $this->migration = $migration;
130 $this->entityManager = $entityManager;
131 $this->selectionPluginManager = $selectionPluginManager;
132 $pluginIdParts = explode(':', $this->migration->getDestinationPlugin()->getPluginId());
133 $this->destinationEntityType = empty($pluginIdParts[1]) ?: $pluginIdParts[1];
134 $this->destinationBundleKey = !$this->destinationEntityType ?: $this->entityManager->getDefinition($this->destinationEntityType)->getKey('bundle');
140 public static function create(ContainerInterface $container, array $configuration, $pluginId, $pluginDefinition, MigrationInterface $migration = NULL) {
146 $container->get('entity.manager'),
147 $container->get('plugin.manager.entity_reference_selection')
154 public function transform($value, MigrateExecutableInterface $migrateExecutable, Row $row, $destinationProperty) {
155 // In case of subfields ('field_reference/target_id'), extract the field
157 $parts = explode('/', $destinationProperty);
158 $destinationProperty = reset($parts);
159 $this->determineLookupProperties($destinationProperty);
161 $this->destinationProperty = isset($this->configuration['destination_field']) ? $this->configuration['destination_field'] : NULL;
163 return $this->query($value);
167 * Determine the lookup properties from config or target field configuration.
169 * @param string $destinationProperty
170 * The destination property currently worked on. This is only used together
171 * with the $row above.
173 protected function determineLookupProperties($destinationProperty) {
174 if (!empty($this->configuration['value_key'])) {
175 $this->lookupValueKey = $this->configuration['value_key'];
177 if (!empty($this->configuration['bundle_key'])) {
178 $this->lookupBundleKey = $this->configuration['bundle_key'];
180 if (!empty($this->configuration['bundle'])) {
181 $this->lookupBundle = $this->configuration['bundle'];
183 if (!empty($this->configuration['entity_type'])) {
184 $this->lookupEntityType = $this->configuration['entity_type'];
187 if (empty($this->lookupValueKey) || empty($this->lookupBundleKey) || empty($this->lookupBundle) || empty($this->lookupEntityType)) {
188 // See if we can introspect the lookup properties from destination field.
189 if (!empty($this->migration->getProcess()[$this->destinationBundleKey][0]['default_value'])) {
190 $destinationEntityBundle = $this->migration->getProcess()[$this->destinationBundleKey][0]['default_value'];
191 $fieldConfig = $this->entityManager->getFieldDefinitions($this->destinationEntityType, $destinationEntityBundle)[$destinationProperty]->getConfig($destinationEntityBundle);
192 switch ($fieldConfig->getType()) {
193 case 'entity_reference':
194 if (empty($this->lookupBundle)) {
195 $handlerSettings = $fieldConfig->getSetting('handler_settings');
196 $bundles = array_filter((array) $handlerSettings['target_bundles']);
197 if (count($bundles) == 1) {
198 $this->lookupBundle = reset($bundles);
200 // This was added in 8.1.x is not supported in 8.0.x.
201 elseif (!empty($handlerSettings['auto_create']) && !empty($handlerSettings['auto_create_bundle'])) {
202 $this->lookupBundle = reset($handlerSettings['auto_create_bundle']);
206 // Make an assumption that if the selection handler can target more
207 // than one type of entity that we will use the first entity type.
208 $this->lookupEntityType = $this->lookupEntityType ?: reset($this->selectionPluginManager->createInstance($fieldConfig->getSetting('handler'))->getPluginDefinition()['entity_types']);
209 $this->lookupValueKey = $this->lookupValueKey ?: $this->entityManager->getDefinition($this->lookupEntityType)->getKey('label');
210 $this->lookupBundleKey = $this->lookupBundleKey ?: $this->entityManager->getDefinition($this->lookupEntityType)->getKey('bundle');
215 $this->lookupEntityType = 'file';
216 $this->lookupValueKey = $this->lookupValueKey ?: 'uri';
220 throw new MigrateException('Destination field type ' .
221 $fieldConfig->getType() . 'is not a recognized reference type.');
226 // If there aren't enough lookup properties available by now, then bail.
227 if (empty($this->lookupValueKey)) {
228 throw new MigrateException('The entity_lookup plugin requires a value_key, none located.');
230 if (!empty($this->lookupBundleKey) && empty($this->lookupBundle)) {
231 throw new MigrateException('The entity_lookup plugin found no bundle but destination entity requires one.');
233 if (empty($this->lookupEntityType)) {
234 throw new MigrateException('The entity_lookup plugin requires a entity_type, none located.');
239 * Checks for the existence of some value.
241 * @param mixed $value
242 * The value to query.
245 * Entity id if the queried entity exists. Otherwise NULL.
247 protected function query($value) {
248 // Entity queries typically are case-insensitive. Therefore, we need to
249 // handle case sensitive filtering as a post-query step. By default, it
250 // filters case insensitive. Change to true if that is not the desired
252 $ignoreCase = !empty($this->configuration['ignore_case']) ?: FALSE;
254 $multiple = is_array($value);
256 $query = $this->entityManager->getStorage($this->lookupEntityType)
258 ->condition($this->lookupValueKey, $value, $multiple ? 'IN' : NULL);
260 if ($this->lookupBundleKey) {
261 $query->condition($this->lookupBundleKey, $this->lookupBundle);
263 $results = $query->execute();
265 if (empty($results)) {
269 // By default do a case-sensitive comparison.
271 // Returns the entity's identifier.
272 foreach ($results as $k => $identifier) {
273 $result_value = $this->entityManager->getStorage($this->lookupEntityType)->load($identifier)->{$this->lookupValueKey}->value;
274 if (($multiple && !in_array($result_value, $value, TRUE)) || (!$multiple && $result_value !== $value)) {
280 if ($multiple && !empty($this->destinationProperty)) {
281 array_walk($results, function (&$value) {
282 $value = [$this->destinationProperty => $value];
286 return $multiple ? array_values($results) : reset($results);