summaryrefslogtreecommitdiffstatshomepage
path: root/core/modules/migrate_drupal/src/FieldDiscovery.php
blob: 4a26c9708d60026c49fed7f061d5ec8b830f97b2 (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
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
120
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
<?php

namespace Drupal\migrate_drupal;

use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\migrate\Exception\RequirementsException;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Plugin\MigrationPluginManagerInterface;
use Drupal\migrate\Plugin\RequirementsInterface;
use Drupal\migrate_drupal\Plugin\MigrateFieldPluginManagerInterface;
use Psr\Log\LoggerInterface;

/**
 * Provides field discovery for Drupal 6 & 7 migrations.
 */
class FieldDiscovery implements FieldDiscoveryInterface {

  /**
   * An array of already discovered field plugin information.
   *
   * @var array
   */
  protected $fieldPluginCache;

  /**
   * The field plugin manager.
   *
   * @var \Drupal\migrate_drupal\Plugin\MigrateFieldPluginManagerInterface
   */
  protected $fieldPluginManager;

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

  /**
   * The logger channel service.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * A cache of discovered fields.
   *
   * It is an array of arrays. If the entity type is bundleable, a third level
   * of arrays is added to account for fields discovered at the bundle level.
   *
   * [{core}][{entity_type}][{bundle}]
   *
   * @var array
   */
  protected $discoveredFieldsCache = [];

  /**
   * An array of bundle keys, keyed by drupal core version.
   *
   * In Drupal 6, only nodes were fieldable, and the bundles were called
   * 'type_name'.  In Drupal 7, everything became entities, and the more
   * generic 'bundle' was used.
   *
   * @var array
   */
  protected $bundleKeys = [
    FieldDiscoveryInterface::DRUPAL_6 => 'type_name',
    FieldDiscoveryInterface::DRUPAL_7 => 'bundle',
  ];

  /**
   * An array of source plugin ids, keyed by Drupal core version.
   *
   * @var array
   */
  protected $sourcePluginIds = [
    FieldDiscoveryInterface::DRUPAL_6 => 'd6_field_instance',
    FieldDiscoveryInterface::DRUPAL_7 => 'd7_field_instance',
  ];

  /**
   * An array of supported Drupal core versions.
   *
   * @var array
   */
  protected $supportedCoreVersions = [
    FieldDiscoveryInterface::DRUPAL_6,
    FieldDiscoveryInterface::DRUPAL_7,
  ];

  /**
   * Constructs a FieldDiscovery object.
   *
   * @param \Drupal\migrate_drupal\Plugin\MigrateFieldPluginManagerInterface $field_plugin_manager
   *   The field plugin manager.
   * @param \Drupal\migrate\Plugin\MigrationPluginManagerInterface $migration_plugin_manager
   *   The migration plugin manager.
   * @param \Psr\Log\LoggerInterface $logger
   *   The logger channel service.
   */
  public function __construct(MigrateFieldPluginManagerInterface $field_plugin_manager, MigrationPluginManagerInterface $migration_plugin_manager, LoggerInterface $logger) {
    $this->fieldPluginManager = $field_plugin_manager;
    $this->migrationPluginManager = $migration_plugin_manager;
    $this->logger = $logger;
  }

  /**
   * {@inheritdoc}
   */
  public function addAllFieldProcesses(MigrationInterface $migration) {
    $core = $this->getCoreVersion($migration);
    $fields = $this->getAllFields($core);
    foreach ($fields as $entity_type_id => $bundle) {
      $this->addEntityFieldProcesses($migration, $entity_type_id);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function addEntityFieldProcesses(MigrationInterface $migration, $entity_type_id) {
    $core = $this->getCoreVersion($migration);
    $fields = $this->getAllFields($core);
    if (!empty($fields[$entity_type_id])  && is_array($fields[$entity_type_id])) {
      foreach ($fields[$entity_type_id] as $bundle => $fields) {
        $this->addBundleFieldProcesses($migration, $entity_type_id, $bundle);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function addBundleFieldProcesses(MigrationInterface $migration, $entity_type_id, $bundle) {
    $core = $this->getCoreVersion($migration);
    $fields = $this->getAllFields($core);
    $plugin_definition = $migration->getPluginDefinition();
    if (empty($fields[$entity_type_id][$bundle])) {
      return;
    }
    $bundle_fields = $fields[$entity_type_id][$bundle];
    foreach ($bundle_fields as $field_name => $field_info) {
      $plugin = $this->getFieldPlugin($field_info['type'], $migration);
      if ($plugin) {
        $method = $plugin_definition['field_plugin_method'] ?? 'defineValueProcessPipeline';

        call_user_func_array([
          $plugin,
          $method,
        ], [
          $migration,
          $field_name,
          $field_info,
        ]);
      }
      else {
        // Default to a get process plugin if this is a value migration.
        if ((empty($plugin_definition['field_plugin_method']) || $plugin_definition['field_plugin_method'] === 'defineValueProcessPipeline')) {
          $migration->setProcessOfProperty($field_name, $field_name);
        }
      }
    }
  }

  /**
   * Returns the appropriate field plugin for a given field type.
   *
   * @param string $field_type
   *   The field type.
   * @param \Drupal\migrate\Plugin\MigrationInterface $migration
   *   The migration to retrieve the plugin for.
   *
   * @return \Drupal\migrate_drupal\Plugin\MigrateFieldInterface|bool
   *   The appropriate field plugin to process this field type.
   *
   * @throws \Drupal\Component\Plugin\Exception\PluginException
   * @throws \InvalidArgumentException
   */
  protected function getFieldPlugin($field_type, MigrationInterface $migration) {
    $core = $this->getCoreVersion($migration);
    if (!isset($this->fieldPluginCache[$core][$field_type])) {
      try {
        $plugin_id = $this->fieldPluginManager->getPluginIdFromFieldType($field_type, ['core' => $core], $migration);
        $plugin = $this->fieldPluginManager->createInstance($plugin_id, ['core' => $core], $migration);
      }
      catch (PluginNotFoundException) {
        $plugin = FALSE;
      }
      $this->fieldPluginCache[$core][$field_type] = $plugin;
    }
    return $this->fieldPluginCache[$core][$field_type];
  }

  /**
   * Gets all field information related to this migration.
   *
   * @param string $core
   *   The Drupal core version to get fields for.
   *
   * @return array
   *   A multidimensional array of source data from the relevant field instance
   *   migration, keyed first by entity type, then by bundle and finally by
   *   field name.
   */
  protected function getAllFields($core) {
    if (empty($this->discoveredFieldsCache[$core])) {
      $this->discoveredFieldsCache[$core] = [];
      $source_plugin = $this->getSourcePlugin($core);
      foreach ($source_plugin as $row) {
        /** @var \Drupal\migrate\Row $row */
        if ($core === FieldDiscoveryInterface::DRUPAL_7) {
          $entity_type_id = $row->get('entity_type');
        }
        else {
          $entity_type_id = 'node';
        }
        $bundle = $row->getSourceProperty($this->bundleKeys[$core]);
        $this->discoveredFieldsCache[$core][$entity_type_id][$bundle][$row->getSourceProperty('field_name')] = $row->getSource();
      }
    }
    return $this->discoveredFieldsCache[$core];
  }

  /**
   * Gets all field information for a particular entity type.
   *
   * @param string $core
   *   The Drupal core version.
   * @param string $entity_type_id
   *   The legacy entity type ID.
   *
   * @return array
   *   A multidimensional array of source data from the relevant field instance
   *   migration for the entity type, keyed first by bundle and then by field
   *   name.
   */
  protected function getEntityFields($core, $entity_type_id) {
    $fields = $this->getAllFields($core);
    if (!empty($fields[$entity_type_id])) {
      return $fields[$entity_type_id];
    }
    return [];
  }

  /**
   * Gets all field information for a particular entity type and bundle.
   *
   * @param string $core
   *   The Drupal core version.
   * @param string $entity_type_id
   *   The legacy entity type ID.
   * @param string $bundle
   *   The legacy bundle (or content_type).
   *
   * @return array
   *   An array of source data from the relevant field instance migration for
   *   the bundle, keyed by field name.
   */
  protected function getBundleFields($core, $entity_type_id, $bundle) {
    $fields = $this->getEntityFields($core, $entity_type_id);
    if (!empty($fields[$bundle])) {
      return $fields[$bundle];
    }
    return [];
  }

  /**
   * Gets the source plugin to use to gather field information.
   *
   * @param string $core
   *   The Drupal core version.
   *
   * @return array|\Drupal\migrate\Plugin\MigrateSourceInterface
   *   The source plugin, or an empty array if none can be found that meets
   *   requirements.
   */
  protected function getSourcePlugin($core) {
    $definition = $this->getFieldInstanceStubMigrationDefinition($core);
    $source_plugin = $this->migrationPluginManager
      ->createStubMigration($definition)
      ->getSourcePlugin();
    if ($source_plugin instanceof RequirementsInterface) {
      try {
        $source_plugin->checkRequirements();
      }
      catch (RequirementsException $e) {
        // If checkRequirements() failed, the source database did not support
        // fields (i.e., Field is not installed in D7). Therefore, $fields will
        // be empty and below we'll return an empty array. The migration will
        // proceed without adding fields.
        $this->logger->notice('Field discovery failed for Drupal core version @core. Did this site have the Field module installed? Error: @message', [
          '@core' => $core,
          '@message' => $e->getMessage(),
        ]);
        return [];
      }
    }
    return $source_plugin;
  }

  /**
   * Provides the stub migration definition for a given Drupal core version.
   *
   * @param string $core
   *   The Drupal core version.
   *
   * @return array
   *   The stub migration definition.
   */
  protected function getFieldInstanceStubMigrationDefinition($core) {
    return [
      'destination' => ['plugin' => 'null'],
      'idMap' => ['plugin' => 'null'],
      'source' => [
        'ignore_map' => TRUE,
        'plugin' => $this->sourcePluginIds[$core],
      ],
    ];
  }

  /**
   * Finds the core version of a Drupal migration.
   *
   * @param \Drupal\migrate\Plugin\MigrationInterface $migration
   *   The migration.
   *
   * @return string|bool
   *   A string representation of the Drupal version, or FALSE.
   *
   * @throws \InvalidArgumentException
   */
  protected function getCoreVersion(MigrationInterface $migration) {
    $tags = $migration->getMigrationTags();
    if (in_array('Drupal 7', $tags, TRUE)) {
      return FieldDiscoveryInterface::DRUPAL_7;
    }
    elseif (in_array('Drupal 6', $tags, TRUE)) {
      return FieldDiscoveryInterface::DRUPAL_6;
    }
    throw new \InvalidArgumentException("Drupal Core version not found for this migration");
  }

}