summaryrefslogtreecommitdiffstatshomepage
path: root/core/modules/migrate/src/MigrateLookup.php
blob: 53f4246c8ba6b717dc5f2841dfc2c0859c460b2d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php

namespace Drupal\migrate;

use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Plugin\MigrationPluginManagerInterface;

/**
 * Provides a migration lookup service.
 */
class MigrateLookup implements MigrateLookupInterface {

  /**
   * The migration plugin manager.
   *
   * @var \Drupal\migrate\Plugin\MigrationPluginManagerInterface
   */
  protected $migrationPluginManager;

  /**
   * Constructs a MigrateLookup object.
   *
   * @param \Drupal\migrate\Plugin\MigrationPluginManagerInterface $migration_plugin_manager
   *   The migration plugin manager.
   */
  public function __construct(MigrationPluginManagerInterface $migration_plugin_manager) {
    $this->migrationPluginManager = $migration_plugin_manager;
  }

  /**
   * {@inheritdoc}
   */
  public function lookup($migration_id, array $source_id_values) {
    $results = [];
    $migrations = $this->migrationPluginManager->createInstances($migration_id);
    if (!$migrations) {
      if (is_array($migration_id)) {
        if (count($migration_id) != 1) {
          throw new PluginException("Plugin IDs '" . implode("', '", $migration_id) . "' were not found.");
        }
        $migration_id = reset($migration_id);
      }
      throw new PluginNotFoundException($migration_id);
    }
    foreach ($migrations as $migration) {
      if ($result = $this->doLookup($migration, $source_id_values)) {
        $results = array_merge($results, $result);
      }
    }
    return $results;
  }

  /**
   * Performs a lookup.
   *
   * @param \Drupal\migrate\Plugin\MigrationInterface $migration
   *   The migration upon which to perform the lookup.
   * @param array $source_id_values
   *   The source ID values to look up.
   *
   * @return array
   *   An array of arrays of destination identifier values.
   *
   * @throws \Drupal\migrate\MigrateException
   *   Thrown when $source_id_values contains unknown keys, or the wrong number
   *   of keys.
   */
  protected function doLookup(MigrationInterface $migration, array $source_id_values) {
    $destination_keys = array_keys($migration->getDestinationPlugin()->getIds());
    $indexed_ids = $migration->getIdMap()
      ->lookupDestinationIds($source_id_values);
    $keyed_ids = [];
    foreach ($indexed_ids as $id) {
      $keyed_ids[] = array_combine($destination_keys, $id);
    }
    return $keyed_ids;
  }

}