DomMigrationLookup.php 7.37 KB
Newer Older
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<?php

namespace Drupal\migrate_plus\Plugin\migrate\process;

use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Plugin\MigratePluginManagerInterface;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Row;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * String replacements on a source dom based on migration lookup.
 *
 * Meant to be used after dom process plugin.
 *
 * Available configuration keys:
 * - mode: What to modify. Possible values:
 *   - attribute: One element attribute.
 * - xpath: XPath query expression that will produce the \DOMNodeList to walk.
 * - attribute_options: A map of options related to the attribute mode. Required
 *   when mode is attribute. The keys can be:
 *   - name: Name of the attribute to match and modify.
 * - search: Regular expression to use. It should contain at least one
 *   parenthesized subpattern which will be used as the ID passed to
 *   migration_lookup process plugin.
 * - replace: Default value to use for replacements on migrations, if not
 *   specified on the migration. It should contain the '[mapped-id]' string
 *   where the looked-up migration value will be placed.
 * - migrations: A map of options indexed by migration machine name. Possible
 *   option values are:
 *   - replace: See replace option lines above.
 * - no_stub: If TRUE, then do not create stub entities during migration lookup.
 *   Optional, defaults to TRUE.
 *
 * Example:
 *
 * @code
 * process:
 *   'body/value':
 *     -
 *       plugin: dom
 *       method: import
 *       source: 'body/0/value'
 *     -
 *       plugin: dom_migration_lookup
 *       mode: attribute
 *       xpath: '//a'
 *       attribute_options:
 *         name: href
 *       search: '@/user/(\d+)@'
 *       replace: '/user/[mapped-id]'
 *       migrations:
 *         users:
 *           replace: '/user/[mapped-id]'
 *         people:
 *           replace: '/people/[mapped-id]'
 *     -
 *       plugin: dom
 *       method: export
 * @endcode
 *
 * @MigrateProcessPlugin(
 *   id = "dom_migration_lookup"
 * )
 */
class DomMigrationLookup extends DomStrReplace implements ContainerFactoryPluginInterface {

  /**
   * The migration to be executed.
   *
   * @var \Drupal\migrate\Plugin\MigrationInterface
   */
  protected $migration;

  /**
   * The process plugin manager.
   *
   * @var \Drupal\migrate\Plugin\MigratePluginManagerInterface
   */
  protected $processPluginManager;

  /**
   * Parameters passed to transform method, except the first, value.
   *
   * This helps to pass values to another process plugin.
   *
   * @var array
   */
  protected $transformParameters;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration, MigratePluginManagerInterface $process_plugin_manager) {
    $configuration += ['no_stub' => TRUE];
    $default_replace_missing = empty($configuration['replace']);
    if ($default_replace_missing) {
      $configuration['replace'] = 'prevent-requirement-fail';
    }
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    if ($default_replace_missing) {
      unset($this->configuration['replace']);
    }
    $this->migration = $migration;
    $this->processPluginManager = $process_plugin_manager;
    if (empty($this->configuration['migrations'])) {
      throw new InvalidPluginDefinitionException(
        $this->getPluginId(),
        "Configuration option 'migration' is required."
      );
    }
    if (!is_array($this->configuration['migrations'])) {
      throw new InvalidPluginDefinitionException(
        $this->getPluginId(),
        "Configuration option 'migration' should be a keyed array."
      );
    }
heddn's avatar
heddn committed
120
    // Add missing values if possible.
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
    $default_replace = isset($this->configuration['replace']) ? $this->configuration['replace'] : NULL;
    foreach ($this->configuration['migrations'] as $migration_name => $configuration_item) {
      if (!empty($configuration_item['replace'])) {
        continue;
      }
      if (is_null($default_replace)) {
        throw new InvalidPluginDefinitionException(
          $this->getPluginId(),
          "Please define either a global replace for all migrations, or a specific one for 'migrations.$migration_name'."
        );
      }
      $this->configuration['migrations'][$migration_name]['replace'] = $default_replace;
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $migration,
      $container->get('plugin.manager.migrate.process')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $this->init($value, $destination_property);
    $this->transformParameters = [
      'migrate_executable' => $migrate_executable,
      'row' => $row,
      'destination_property' => $destination_property,
    ];

    foreach ($this->xpath->query($this->configuration['xpath']) as $html_node) {
      $subject = $this->getSubject($html_node);
      if (empty($subject)) {
        // Could not find subject, skip processing.
        continue;
      }
      $search = $this->getSearch();
      if (!preg_match($search, $subject, $matches)) {
        // No match found, skip processing.
        continue;
      }
      $id = $matches[1];
      // Walk through defined migrations looking for a map.
      foreach ($this->configuration['migrations'] as $migration_name => $configuration) {
        $mapped_id = $this->migrationLookup($id, $migration_name);
        if (!is_null($mapped_id)) {
          // Not using getReplace(), since this implementation depends on the
          // migration.
          $replace = str_replace('[mapped-id]', $mapped_id, $configuration['replace']);
          $this->doReplace($html_node, $search, $replace, $subject);
          break;
        }
      }
    }

    return $this->document;
  }

  /**
   * {@inheritdoc}
   */
  protected function doReplace(\DOMElement $html_node, $search, $replace, $subject) {
    $new_subject = preg_replace($search, $replace, $subject);
    $this->postReplace($html_node, $new_subject);
  }

  /**
   * Lookup the migration mapped ID on one migration.
   *
   * @param mixed $id
   *   The ID to search with migration_lookup process plugin.
   * @param string $migration_name
   *   The migration to look into machine name.
   *
   * @return string|null
   *   The found mapped ID, or NULL if not found on the provided migration.
   */
  protected function migrationLookup($id, $migration_name) {
    $mapped_id = NULL;
    $parameters = [
      $id,
      $this->transformParameters['migrate_executable'],
      $this->transformParameters['row'],
      $this->transformParameters['destination_property'],
    ];
    $plugin_configuration = [
      'migration' => $migration_name,
      'no_stub' => $this->configuration['no_stub'],
    ];
    $migration_lookup_plugin = $this->processPluginManager
      ->createInstance('migration_lookup', $plugin_configuration, $this->migration);
    $mapped_id = call_user_func_array([$migration_lookup_plugin, 'transform'], $parameters);
    return $mapped_id;
  }

}