StorageComparer.php 14.8 KB
Newer Older
1 2 3 4 5 6 7 8
<?php

/**
 * @file
 * Contains \Drupal\Core\Config\StorageComparer.
 */

namespace Drupal\Core\Config;
9 10

use Drupal\Component\Utility\String;
11
use Drupal\Core\Config\Entity\ConfigDependencyManager;
12
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
13 14 15 16

/**
 * Defines a config storage comparer.
 */
17 18
class StorageComparer implements StorageComparerInterface {
  use DependencySerializationTrait;
19 20 21 22 23 24 25 26

  /**
   * The source storage used to discover configuration changes.
   *
   * @var \Drupal\Core\Config\StorageInterface
   */
  protected $sourceStorage;

27 28 29 30 31 32 33
  /**
   * The source storages keyed by collection.
   *
   * @var \Drupal\Core\Config\StorageInterface[]
   */
  protected $sourceStorages;

34 35 36 37 38 39 40
  /**
   * The target storage used to write configuration changes.
   *
   * @var \Drupal\Core\Config\StorageInterface
   */
  protected $targetStorage;

41 42 43 44 45 46 47 48 49 50 51 52 53 54
  /**
   * The target storages keyed by collection.
   *
   * @var \Drupal\Core\Config\StorageInterface[]
   */
  protected $targetStorages;

  /**
   * The configuration manager.
   *
   * @var \Drupal\Core\Config\ConfigManagerInterface
   */
  protected $configManager;

55 56 57
  /**
   * List of changes to between the source storage and the target storage.
   *
58 59
   * The list is keyed by storage collection name.
   *
60 61 62 63 64
   * @var array
   */
  protected $changelist;

  /**
65
   * Sorted list of all the configuration object names in the source storage.
66
   *
67 68
   * The list is keyed by storage collection name.
   *
69 70 71 72 73
   * @var array
   */
  protected $sourceNames = array();

  /**
74
   * Sorted list of all the configuration object names in the target storage.
75
   *
76 77
   * The list is keyed by storage collection name.
   *
78 79 80 81
   * @var array
   */
  protected $targetNames = array();

82 83 84
  /**
   * The source configuration data keyed by name.
   *
85 86
   * The data is keyed by storage collection name.
   *
87 88 89 90 91 92 93
   * @var array
   */
  protected $sourceData = array();

  /**
   * The target configuration data keyed by name.
   *
94 95
   * The data is keyed by storage collection name.
   *
96 97 98 99
   * @var array
   */
  protected $targetData = array();

100 101 102 103
  /**
   * Constructs the Configuration storage comparer.
   *
   * @param \Drupal\Core\Config\StorageInterface $source_storage
104
   *   Storage object used to read configuration.
105
   * @param \Drupal\Core\Config\StorageInterface $target_storage
106
   *   Storage object used to write configuration.
107 108
   * @param \Drupal\Core\Config\ConfigManagerInterface $config_manager
   *   The configuration manager.
109
   */
110
  public function __construct(StorageInterface $source_storage, StorageInterface $target_storage, ConfigManagerInterface $config_manager) {
111 112
    $this->sourceStorage = $source_storage;
    $this->targetStorage = $target_storage;
113 114
    $this->configManager = $config_manager;
    $this->changelist[StorageInterface::DEFAULT_COLLECTION] = $this->getEmptyChangelist();
115 116 117 118 119
  }

  /**
   * {@inheritdoc}
   */
120 121 122 123 124 125 126 127 128 129
  public function getSourceStorage($collection = StorageInterface::DEFAULT_COLLECTION) {
    if (!isset($this->sourceStorages[$collection])) {
      if ($collection == StorageInterface::DEFAULT_COLLECTION) {
        $this->sourceStorages[$collection] = $this->sourceStorage;
      }
      else {
        $this->sourceStorages[$collection] = $this->sourceStorage->createCollection($collection);
      }
    }
    return $this->sourceStorages[$collection];
130 131 132 133 134
  }

  /**
   * {@inheritdoc}
   */
135 136 137 138 139 140 141 142 143 144
  public function getTargetStorage($collection = StorageInterface::DEFAULT_COLLECTION) {
    if (!isset($this->targetStorages[$collection])) {
      if ($collection == StorageInterface::DEFAULT_COLLECTION) {
        $this->targetStorages[$collection] = $this->targetStorage;
      }
      else {
        $this->targetStorages[$collection] = $this->targetStorage->createCollection($collection);
      }
    }
    return $this->targetStorages[$collection];
145 146 147 148 149 150 151 152 153 154
  }

  /**
   * {@inheritdoc}
   */
  public function getEmptyChangelist() {
    return array(
      'create' => array(),
      'update' => array(),
      'delete' => array(),
155
      'rename' => array(),
156 157 158 159 160 161
    );
  }

  /**
   * {@inheritdoc}
   */
162
  public function getChangelist($op = NULL, $collection = StorageInterface::DEFAULT_COLLECTION) {
163
    if ($op) {
164
      return $this->changelist[$collection][$op];
165
    }
166
    return $this->changelist[$collection];
167 168 169
  }

  /**
170 171
   * Adds changes to the changelist.
   *
172 173
   * @param string $collection
   *   The storage collection to add changes for.
174
   * @param string $op
175
   *   The change operation performed. Either delete, create, rename, or update.
176 177
   * @param array $changes
   *   Array of changes to add to the changelist.
178 179 180
   * @param array $sort_order
   *   Array to sort that can be used to sort the changelist. This array must
   *   contain all the items that are in the change list.
181
   */
182
  protected function addChangeList($collection, $op, array $changes, array $sort_order = NULL) {
183
    // Only add changes that aren't already listed.
184 185
    $changes = array_diff($changes, $this->changelist[$collection][$op]);
    $this->changelist[$collection][$op] = array_merge($this->changelist[$collection][$op], $changes);
186
    if (isset($sort_order)) {
187
      $count = count($this->changelist[$collection][$op]);
188
      // Sort the changelist in the same order as the $sort_order array and
189
      // ensure the array is keyed from 0.
190 191
      $this->changelist[$collection][$op] = array_values(array_intersect($sort_order, $this->changelist[$collection][$op]));
      if ($count != count($this->changelist[$collection][$op])) {
192 193 194
        throw new \InvalidArgumentException(String::format('Sorting the @op changelist should not change its length.', array('@op' => $op)));
      }
    }
195 196 197 198 199 200
  }

  /**
   * {@inheritdoc}
   */
  public function createChangelist() {
201 202 203 204 205 206 207 208 209 210 211 212 213 214
    foreach ($this->getAllCollectionNames() as $collection) {
      $this->changelist[$collection] = $this->getEmptyChangelist();
      $this->getAndSortConfigData($collection);
      $this->addChangelistCreate($collection);
      $this->addChangelistUpdate($collection);
      $this->addChangelistDelete($collection);
      // Only collections that support configuration entities can have renames.
      if ($this->configManager->supportsConfigurationEntities($collection)) {
        $this->addChangelistRename($collection);
      }
      // Only need data whilst calculating changelists. Free up the memory.
      $this->sourceData = NULL;
      $this->targetData = NULL;
    }
215
    return $this;
216 217 218
  }

  /**
219 220 221
   * Creates the delete changelist.
   *
   * The list of deletes is sorted so that dependencies are deleted after
222 223
   * configuration entities that depend on them. For example, fields should be
   * deleted after field storages.
224 225 226
   *
   * @param string $collection
   *   The storage collection to operate on.
227
   */
228 229 230
  protected function addChangelistDelete($collection) {
    $deletes = array_diff(array_reverse($this->targetNames[$collection]), $this->sourceNames[$collection]);
    $this->addChangeList($collection, 'delete', $deletes);
231 232 233
  }

  /**
234 235 236
   * Creates the create changelist.
   *
   * The list of creates is sorted so that dependencies are created before
237 238
   * configuration entities that depend on them. For example, field storages
   * should be created before fields.
239 240 241
   *
   * @param string $collection
   *   The storage collection to operate on.
242
   */
243 244 245
  protected function addChangelistCreate($collection) {
    $creates = array_diff($this->sourceNames[$collection], $this->targetNames[$collection]);
    $this->addChangeList($collection, 'create', $creates);
246 247 248
  }

  /**
249 250 251
   * Creates the update changelist.
   *
   * The list of updates is sorted so that dependencies are created before
252 253
   * configuration entities that depend on them. For example, field storages
   * should be updated before fields.
254 255 256
   *
   * @param string $collection
   *   The storage collection to operate on.
257
   */
258
  protected function addChangelistUpdate($collection) {
259
    $recreates = array();
260 261 262
    foreach (array_intersect($this->sourceNames[$collection], $this->targetNames[$collection]) as $name) {
      if ($this->sourceData[$collection][$name] !== $this->targetData[$collection][$name]) {
        if (isset($this->sourceData[$collection][$name]['uuid']) && $this->sourceData[$collection][$name]['uuid'] != $this->targetData[$collection][$name]['uuid']) {
263 264 265 266 267 268
          // The entity has the same file as an existing entity but the UUIDs do
          // not match. This means that the entity has been recreated so config
          // synchronisation should do the same.
          $recreates[] = $name;
        }
        else {
269
          $this->addChangeList($collection, 'update', array($name));
270
        }
271 272
      }
    }
273 274 275 276

    if (!empty($recreates)) {
      // Recreates should become deletes and creates. Deletes should be ordered
      // so that dependencies are deleted first.
277 278
      $this->addChangeList($collection, 'create', $recreates, $this->sourceNames[$collection]);
      $this->addChangeList($collection, 'delete', $recreates, array_reverse($this->targetNames[$collection]));
279

280
    }
281 282
  }

283 284 285 286 287 288
  /**
   * Creates the rename changelist.
   *
   * The list of renames is created from the different source and target names
   * with same UUID. These changes will be removed from the create and delete
   * lists.
289 290 291
   *
   * @param string $collection
   *   The storage collection to operate on.
292
   */
293
  protected function addChangelistRename($collection) {
294
    // Renames will be present in both the create and delete lists.
295 296
    $create_list = $this->getChangelist('create', $collection);
    $delete_list = $this->getChangelist('delete', $collection);
297 298 299 300 301
    if (empty($create_list) || empty($delete_list)) {
      return;
    }

    $create_uuids = array();
302
    foreach ($this->sourceData[$collection] as $id => $data) {
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
      if (isset($data['uuid']) && in_array($id, $create_list)) {
        $create_uuids[$data['uuid']] = $id;
      }
    }
    if (empty($create_uuids)) {
      return;
    }

    $renames = array();

    // Renames should be ordered so that dependencies are renamed last. This
    // ensures that if there is logic in the configuration entity class to keep
    // names in sync it will still work. $this->targetNames is in the desired
    // order due to the use of configuration dependencies in
    // \Drupal\Core\Config\StorageComparer::getAndSortConfigData().
    // Node type is a good example of a configuration entity that renames other
    // configuration when it is renamed.
    // @see \Drupal\node\Entity\NodeType::postSave()
321 322
    foreach ($this->targetNames[$collection] as $name) {
      $data = $this->targetData[$collection][$name];
323 324
      if (isset($data['uuid']) && isset($create_uuids[$data['uuid']])) {
        // Remove the item from the create list.
325
        $this->removeFromChangelist($collection, 'create', $create_uuids[$data['uuid']]);
326
        // Remove the item from the delete list.
327
        $this->removeFromChangelist($collection, 'delete', $name);
328 329 330 331 332
        // Create the rename name.
        $renames[] = $this->createRenameName($name, $create_uuids[$data['uuid']]);
      }
    }

333
    $this->addChangeList($collection, 'rename', $renames);
334 335 336 337 338
  }

  /**
   * Removes the entry from the given operation changelist for the given name.
   *
339 340
   * @param string $collection
   *   The storage collection to operate on.
341 342 343 344 345
   * @param string $op
   *   The changelist to act on. Either delete, create, rename or update.
   * @param string $name
   *   The name of the configuration to remove.
   */
346 347
  protected function removeFromChangelist($collection, $op, $name) {
    $key = array_search($name, $this->changelist[$collection][$op]);
348
    if ($key !== FALSE) {
349
      unset($this->changelist[$collection][$op][$key]);
350 351 352 353 354 355
    }
  }

  /**
   * {@inheritdoc}
   */
356
  public function moveRenameToUpdate($rename, $collection = StorageInterface::DEFAULT_COLLECTION) {
357
    $names = $this->extractRenameNames($rename);
358 359
    $this->removeFromChangelist($collection, 'rename', $rename);
    $this->addChangeList($collection, 'update', array($names['new_name']), $this->sourceNames[$collection]);
360 361
  }

362 363 364 365
  /**
   * {@inheritdoc}
   */
  public function reset() {
366
    $this->changelist = array(StorageInterface::DEFAULT_COLLECTION => $this->getEmptyChangelist());
367 368 369 370 371 372 373
    $this->sourceNames = $this->targetNames = array();
    return $this->createChangelist();
  }

  /**
   * {@inheritdoc}
   */
374 375 376 377 378 379
  public function hasChanges() {
    foreach ($this->getAllCollectionNames() as $collection) {
      foreach (array('delete', 'create', 'update', 'rename') as $op) {
        if (!empty($this->changelist[$collection][$op])) {
          return TRUE;
        }
380 381 382 383 384
      }
    }
    return FALSE;
  }

385 386 387 388 389 390 391 392 393
  /**
   * {@inheritdoc}
   */
  public function validateSiteUuid() {
    $source = $this->sourceStorage->read('system.site');
    $target = $this->targetStorage->read('system.site');
    return $source['uuid'] === $target['uuid'];
  }

394 395 396
  /**
   * Gets and sorts configuration data from the source and target storages.
   */
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
  protected function getAndSortConfigData($collection) {
    $source_storage = $this->getSourceStorage($collection);
    $target_storage = $this->getTargetStorage($collection);
    $target_names = $target_storage->listAll();
    $source_names = $source_storage->listAll();
    $this->targetData[$collection] = $target_storage->readMultiple($target_names);
    $this->sourceData[$collection] = $source_storage->readMultiple($source_names);
    // If the collection only supports simple configuration do not use
    // configuration dependencies.
    if ($this->configManager->supportsConfigurationEntities($collection)) {
      $dependency_manager = new ConfigDependencyManager();
      $this->targetNames[$collection] = $dependency_manager->setData($this->targetData[$collection])->sortAll();
      $this->sourceNames[$collection] = $dependency_manager->setData($this->sourceData[$collection])->sortAll();
    }
    else {
      $this->targetNames[$collection] = $target_names;
      $this->sourceNames[$collection] = $source_names;
    }
415 416
  }

417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
  /**
   * Creates a rename name from the old and new names for the object.
   *
   * @param string $old_name
   *   The old configuration object name.
   * @param string $new_name
   *   The new configuration object name.
   *
   * @return string
   *   The configuration change name that encodes both the old and the new name.
   *
   * @see \Drupal\Core\Config\StorageComparerInterface::extractRenameNames()
   */
  protected function createRenameName($name1, $name2) {
    return $name1 . '::' . $name2;
  }

  /**
   * {@inheritdoc}
   */
  public function extractRenameNames($name) {
    $names = explode('::', $name, 2);
    return array(
      'old_name' => $names[0],
      'new_name' => $names[1],
    );
  }
444 445 446 447 448 449 450 451 452 453 454 455

  /**
   * {@inheritdoc}
   */
  public function getAllCollectionNames($include_default = TRUE) {
    $collections = array_unique(array_merge($this->sourceStorage->getAllCollectionNames(), $this->targetStorage->getAllCollectionNames()));
    if ($include_default) {
      array_unshift($collections, StorageInterface::DEFAULT_COLLECTION);
    }
    return $collections;
  }

456
}