StorageComparer.php 15.1 KB
Newer Older
1 2 3
<?php

namespace Drupal\Core\Config;
4

5
use Drupal\Core\Cache\MemoryBackend;
6
use Drupal\Core\Config\Entity\ConfigDependencyManager;
7
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
8 9 10 11

/**
 * Defines a config storage comparer.
 */
12 13
class StorageComparer implements StorageComparerInterface {
  use DependencySerializationTrait;
14 15 16 17 18 19 20 21

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

22 23 24 25 26 27 28
  /**
   * The source storages keyed by collection.
   *
   * @var \Drupal\Core\Config\StorageInterface[]
   */
  protected $sourceStorages;

29 30 31 32 33 34 35
  /**
   * The target storage used to write configuration changes.
   *
   * @var \Drupal\Core\Config\StorageInterface
   */
  protected $targetStorage;

36 37 38 39 40 41 42 43 44 45 46 47 48 49
  /**
   * The target storages keyed by collection.
   *
   * @var \Drupal\Core\Config\StorageInterface[]
   */
  protected $targetStorages;

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

50 51 52
  /**
   * List of changes to between the source storage and the target storage.
   *
53 54
   * The list is keyed by storage collection name.
   *
55 56 57 58 59
   * @var array
   */
  protected $changelist;

  /**
60
   * Sorted list of all the configuration object names in the source storage.
61
   *
62 63
   * The list is keyed by storage collection name.
   *
64 65 66 67 68
   * @var array
   */
  protected $sourceNames = array();

  /**
69
   * Sorted list of all the configuration object names in the target storage.
70
   *
71 72
   * The list is keyed by storage collection name.
   *
73 74 75 76
   * @var array
   */
  protected $targetNames = array();

77
  /**
78
   * A memory cache backend to statically cache source configuration data.
79
   *
80
   * @var \Drupal\Core\Cache\MemoryBackend
81
   */
82
  protected $sourceCacheStorage;
83 84

  /**
85
   * A memory cache backend to statically cache target configuration data.
86
   *
87
   * @var \Drupal\Core\Cache\MemoryBackend
88
   */
89
  protected $targetCacheStorage;
90

91 92 93 94
  /**
   * Constructs the Configuration storage comparer.
   *
   * @param \Drupal\Core\Config\StorageInterface $source_storage
95
   *   Storage object used to read configuration.
96
   * @param \Drupal\Core\Config\StorageInterface $target_storage
97
   *   Storage object used to write configuration.
98 99
   * @param \Drupal\Core\Config\ConfigManagerInterface $config_manager
   *   The configuration manager.
100
   */
101
  public function __construct(StorageInterface $source_storage, StorageInterface $target_storage, ConfigManagerInterface $config_manager) {
102 103 104 105 106 107 108 109 110 111 112 113
    // Wrap the storages in a static cache so that multiple reads of the same
    // raw configuration object are not costly.
    $this->sourceCacheStorage = new MemoryBackend(__CLASS__ . '::source');
    $this->sourceStorage = new CachedStorage(
      $source_storage,
      $this->sourceCacheStorage
    );
    $this->targetCacheStorage = new MemoryBackend(__CLASS__ . '::target');
    $this->targetStorage = new CachedStorage(
      $target_storage,
      $this->targetCacheStorage
    );
114 115
    $this->configManager = $config_manager;
    $this->changelist[StorageInterface::DEFAULT_COLLECTION] = $this->getEmptyChangelist();
116 117 118 119 120
  }

  /**
   * {@inheritdoc}
   */
121 122 123 124 125 126 127 128 129 130
  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];
131 132 133 134 135
  }

  /**
   * {@inheritdoc}
   */
136 137 138 139 140 141 142 143 144 145
  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];
146 147 148 149 150 151 152 153 154 155
  }

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

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

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

  /**
   * {@inheritdoc}
   */
  public function createChangelist() {
202 203 204 205 206 207 208
    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.
209
      if ($collection == StorageInterface::DEFAULT_COLLECTION) {
210 211 212
        $this->addChangelistRename($collection);
      }
    }
213
    return $this;
214 215 216
  }

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

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

  /**
247 248 249
   * Creates the update changelist.
   *
   * The list of updates is sorted so that dependencies are created before
250 251
   * configuration entities that depend on them. For example, field storages
   * should be updated before fields.
252 253 254
   *
   * @param string $collection
   *   The storage collection to operate on.
255
   */
256
  protected function addChangelistUpdate($collection) {
257
    $recreates = array();
258
    foreach (array_intersect($this->sourceNames[$collection], $this->targetNames[$collection]) as $name) {
259 260 261 262
      $source_data = $this->getSourceStorage($collection)->read($name);
      $target_data = $this->getTargetStorage($collection)->read($name);
      if ($source_data !== $target_data) {
        if (isset($source_data['uuid']) && $source_data['uuid'] !== $target_data['uuid']) {
263 264
          // 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
265
          // synchronization should do the same.
266 267 268
          $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 303 304 305
    foreach ($this->sourceNames[$collection] as $name) {
      $data = $this->getSourceStorage($collection)->read($name);
      if (isset($data['uuid']) && in_array($name, $create_list)) {
        $create_uuids[$data['uuid']] = $name;
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
      }
    }
    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()
322
    foreach ($this->targetNames[$collection] as $name) {
323
      $data = $this->getTargetStorage($collection)->read($name);
324 325
      if (isset($data['uuid']) && isset($create_uuids[$data['uuid']])) {
        // Remove the item from the create list.
326
        $this->removeFromChangelist($collection, 'create', $create_uuids[$data['uuid']]);
327
        // Remove the item from the delete list.
328
        $this->removeFromChangelist($collection, 'delete', $name);
329 330 331 332 333
        // Create the rename name.
        $renames[] = $this->createRenameName($name, $create_uuids[$data['uuid']]);
      }
    }

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

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

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

363 364 365 366
  /**
   * {@inheritdoc}
   */
  public function reset() {
367
    $this->changelist = array(StorageInterface::DEFAULT_COLLECTION => $this->getEmptyChangelist());
368
    $this->sourceNames = $this->targetNames = array();
369 370 371
    // Reset the static configuration data caches.
    $this->sourceCacheStorage->deleteAll();
    $this->targetCacheStorage->deleteAll();
372 373 374 375 376 377
    return $this->createChangelist();
  }

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

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

398 399 400
  /**
   * Gets and sorts configuration data from the source and target storages.
   */
401 402 403 404 405
  protected function getAndSortConfigData($collection) {
    $source_storage = $this->getSourceStorage($collection);
    $target_storage = $this->getTargetStorage($collection);
    $target_names = $target_storage->listAll();
    $source_names = $source_storage->listAll();
406 407 408 409
    // Prime the static caches by reading all the configuration in the source
    // and target storages.
    $target_data = $target_storage->readMultiple($target_names);
    $source_data = $source_storage->readMultiple($source_names);
410 411
    // If the collection only supports simple configuration do not use
    // configuration dependencies.
412
    if ($collection == StorageInterface::DEFAULT_COLLECTION) {
413
      $dependency_manager = new ConfigDependencyManager();
414 415
      $this->targetNames[$collection] = $dependency_manager->setData($target_data)->sortAll();
      $this->sourceNames[$collection] = $dependency_manager->setData($source_data)->sortAll();
416 417 418 419 420
    }
    else {
      $this->targetNames[$collection] = $target_names;
      $this->sourceNames[$collection] = $source_names;
    }
421 422
  }

423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
  /**
   * 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],
    );
  }
450 451 452 453 454 455 456 457 458 459 460 461

  /**
   * {@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;
  }

462
}