StorageComparer.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. <?php
  2. namespace Drupal\Core\Config;
  3. use Drupal\Core\Cache\MemoryBackend;
  4. use Drupal\Core\Config\Entity\ConfigDependencyManager;
  5. use Drupal\Core\DependencyInjection\DependencySerializationTrait;
  6. /**
  7. * Defines a config storage comparer.
  8. */
  9. class StorageComparer implements StorageComparerInterface {
  10. use DependencySerializationTrait;
  11. /**
  12. * The source storage used to discover configuration changes.
  13. *
  14. * @var \Drupal\Core\Config\StorageInterface
  15. */
  16. protected $sourceStorage;
  17. /**
  18. * The source storages keyed by collection.
  19. *
  20. * @var \Drupal\Core\Config\StorageInterface[]
  21. */
  22. protected $sourceStorages;
  23. /**
  24. * The target storage used to write configuration changes.
  25. *
  26. * @var \Drupal\Core\Config\StorageInterface
  27. */
  28. protected $targetStorage;
  29. /**
  30. * The target storages keyed by collection.
  31. *
  32. * @var \Drupal\Core\Config\StorageInterface[]
  33. */
  34. protected $targetStorages;
  35. /**
  36. * List of changes to between the source storage and the target storage.
  37. *
  38. * The list is keyed by storage collection name.
  39. *
  40. * @var array
  41. */
  42. protected $changelist;
  43. /**
  44. * Sorted list of all the configuration object names in the source storage.
  45. *
  46. * The list is keyed by storage collection name.
  47. *
  48. * @var array
  49. */
  50. protected $sourceNames = [];
  51. /**
  52. * Sorted list of all the configuration object names in the target storage.
  53. *
  54. * The list is keyed by storage collection name.
  55. *
  56. * @var array
  57. */
  58. protected $targetNames = [];
  59. /**
  60. * A memory cache backend to statically cache source configuration data.
  61. *
  62. * @var \Drupal\Core\Cache\MemoryBackend
  63. */
  64. protected $sourceCacheStorage;
  65. /**
  66. * A memory cache backend to statically cache target configuration data.
  67. *
  68. * @var \Drupal\Core\Cache\MemoryBackend
  69. */
  70. protected $targetCacheStorage;
  71. /**
  72. * Constructs the Configuration storage comparer.
  73. *
  74. * @param \Drupal\Core\Config\StorageInterface $source_storage
  75. * Storage object used to read configuration.
  76. * @param \Drupal\Core\Config\StorageInterface $target_storage
  77. * Storage object used to write configuration.
  78. * @param \Drupal\Core\Config\ConfigManagerInterface $config_manager
  79. * (deprecated) The configuration manager. The $config_manager parameter is deprecated since version 8.7.0 and will be removed in 9.0.0.
  80. */
  81. public function __construct(StorageInterface $source_storage, StorageInterface $target_storage, ConfigManagerInterface $config_manager = NULL) {
  82. // Wrap the storages in a static cache so that multiple reads of the same
  83. // raw configuration object are not costly.
  84. $this->sourceCacheStorage = new MemoryBackend();
  85. $this->sourceStorage = new CachedStorage(
  86. $source_storage,
  87. $this->sourceCacheStorage
  88. );
  89. $this->targetCacheStorage = new MemoryBackend();
  90. $this->targetStorage = new CachedStorage(
  91. $target_storage,
  92. $this->targetCacheStorage
  93. );
  94. $this->changelist[StorageInterface::DEFAULT_COLLECTION] = $this->getEmptyChangelist();
  95. if ($config_manager !== NULL) {
  96. @trigger_error('The storage comparer does not need a config manager. The parameter is deprecated since version 8.7.0 and will be removed in 9.0.0. Omit the third parameter. See https://www.drupal.org/node/2993271.', E_USER_DEPRECATED);
  97. }
  98. }
  99. /**
  100. * {@inheritdoc}
  101. */
  102. public function getSourceStorage($collection = StorageInterface::DEFAULT_COLLECTION) {
  103. if (!isset($this->sourceStorages[$collection])) {
  104. if ($collection == StorageInterface::DEFAULT_COLLECTION) {
  105. $this->sourceStorages[$collection] = $this->sourceStorage;
  106. }
  107. else {
  108. $this->sourceStorages[$collection] = $this->sourceStorage->createCollection($collection);
  109. }
  110. }
  111. return $this->sourceStorages[$collection];
  112. }
  113. /**
  114. * {@inheritdoc}
  115. */
  116. public function getTargetStorage($collection = StorageInterface::DEFAULT_COLLECTION) {
  117. if (!isset($this->targetStorages[$collection])) {
  118. if ($collection == StorageInterface::DEFAULT_COLLECTION) {
  119. $this->targetStorages[$collection] = $this->targetStorage;
  120. }
  121. else {
  122. $this->targetStorages[$collection] = $this->targetStorage->createCollection($collection);
  123. }
  124. }
  125. return $this->targetStorages[$collection];
  126. }
  127. /**
  128. * {@inheritdoc}
  129. */
  130. public function getEmptyChangelist() {
  131. return [
  132. 'create' => [],
  133. 'update' => [],
  134. 'delete' => [],
  135. 'rename' => [],
  136. ];
  137. }
  138. /**
  139. * {@inheritdoc}
  140. */
  141. public function getChangelist($op = NULL, $collection = StorageInterface::DEFAULT_COLLECTION) {
  142. if ($op) {
  143. return $this->changelist[$collection][$op];
  144. }
  145. return $this->changelist[$collection];
  146. }
  147. /**
  148. * Adds changes to the changelist.
  149. *
  150. * @param string $collection
  151. * The storage collection to add changes for.
  152. * @param string $op
  153. * The change operation performed. Either delete, create, rename, or update.
  154. * @param array $changes
  155. * Array of changes to add to the changelist.
  156. * @param array $sort_order
  157. * Array to sort that can be used to sort the changelist. This array must
  158. * contain all the items that are in the change list.
  159. */
  160. protected function addChangeList($collection, $op, array $changes, array $sort_order = NULL) {
  161. // Only add changes that aren't already listed.
  162. $changes = array_diff($changes, $this->changelist[$collection][$op]);
  163. $this->changelist[$collection][$op] = array_merge($this->changelist[$collection][$op], $changes);
  164. if (isset($sort_order)) {
  165. $count = count($this->changelist[$collection][$op]);
  166. // Sort the changelist in the same order as the $sort_order array and
  167. // ensure the array is keyed from 0.
  168. $this->changelist[$collection][$op] = array_values(array_intersect($sort_order, $this->changelist[$collection][$op]));
  169. if ($count != count($this->changelist[$collection][$op])) {
  170. throw new \InvalidArgumentException("Sorting the $op changelist should not change its length.");
  171. }
  172. }
  173. }
  174. /**
  175. * {@inheritdoc}
  176. */
  177. public function createChangelist() {
  178. foreach ($this->getAllCollectionNames() as $collection) {
  179. $this->changelist[$collection] = $this->getEmptyChangelist();
  180. $this->getAndSortConfigData($collection);
  181. $this->addChangelistCreate($collection);
  182. $this->addChangelistUpdate($collection);
  183. $this->addChangelistDelete($collection);
  184. // Only collections that support configuration entities can have renames.
  185. if ($collection == StorageInterface::DEFAULT_COLLECTION) {
  186. $this->addChangelistRename($collection);
  187. }
  188. }
  189. return $this;
  190. }
  191. /**
  192. * Creates the delete changelist.
  193. *
  194. * The list of deletes is sorted so that dependencies are deleted after
  195. * configuration entities that depend on them. For example, fields should be
  196. * deleted after field storages.
  197. *
  198. * @param string $collection
  199. * The storage collection to operate on.
  200. */
  201. protected function addChangelistDelete($collection) {
  202. $deletes = array_diff(array_reverse($this->targetNames[$collection]), $this->sourceNames[$collection]);
  203. $this->addChangeList($collection, 'delete', $deletes);
  204. }
  205. /**
  206. * Creates the create changelist.
  207. *
  208. * The list of creates is sorted so that dependencies are created before
  209. * configuration entities that depend on them. For example, field storages
  210. * should be created before fields.
  211. *
  212. * @param string $collection
  213. * The storage collection to operate on.
  214. */
  215. protected function addChangelistCreate($collection) {
  216. $creates = array_diff($this->sourceNames[$collection], $this->targetNames[$collection]);
  217. $this->addChangeList($collection, 'create', $creates);
  218. }
  219. /**
  220. * Creates the update changelist.
  221. *
  222. * The list of updates is sorted so that dependencies are created before
  223. * configuration entities that depend on them. For example, field storages
  224. * should be updated before fields.
  225. *
  226. * @param string $collection
  227. * The storage collection to operate on.
  228. */
  229. protected function addChangelistUpdate($collection) {
  230. $recreates = [];
  231. foreach (array_intersect($this->sourceNames[$collection], $this->targetNames[$collection]) as $name) {
  232. $source_data = $this->getSourceStorage($collection)->read($name);
  233. $target_data = $this->getTargetStorage($collection)->read($name);
  234. if ($source_data !== $target_data) {
  235. if (isset($source_data['uuid']) && $source_data['uuid'] !== $target_data['uuid']) {
  236. // The entity has the same file as an existing entity but the UUIDs do
  237. // not match. This means that the entity has been recreated so config
  238. // synchronization should do the same.
  239. $recreates[] = $name;
  240. }
  241. else {
  242. $this->addChangeList($collection, 'update', [$name]);
  243. }
  244. }
  245. }
  246. if (!empty($recreates)) {
  247. // Recreates should become deletes and creates. Deletes should be ordered
  248. // so that dependencies are deleted first.
  249. $this->addChangeList($collection, 'create', $recreates, $this->sourceNames[$collection]);
  250. $this->addChangeList($collection, 'delete', $recreates, array_reverse($this->targetNames[$collection]));
  251. }
  252. }
  253. /**
  254. * Creates the rename changelist.
  255. *
  256. * The list of renames is created from the different source and target names
  257. * with same UUID. These changes will be removed from the create and delete
  258. * lists.
  259. *
  260. * @param string $collection
  261. * The storage collection to operate on.
  262. */
  263. protected function addChangelistRename($collection) {
  264. // Renames will be present in both the create and delete lists.
  265. $create_list = $this->getChangelist('create', $collection);
  266. $delete_list = $this->getChangelist('delete', $collection);
  267. if (empty($create_list) || empty($delete_list)) {
  268. return;
  269. }
  270. $create_uuids = [];
  271. foreach ($this->sourceNames[$collection] as $name) {
  272. $data = $this->getSourceStorage($collection)->read($name);
  273. if (isset($data['uuid']) && in_array($name, $create_list)) {
  274. $create_uuids[$data['uuid']] = $name;
  275. }
  276. }
  277. if (empty($create_uuids)) {
  278. return;
  279. }
  280. $renames = [];
  281. // Renames should be ordered so that dependencies are renamed last. This
  282. // ensures that if there is logic in the configuration entity class to keep
  283. // names in sync it will still work. $this->targetNames is in the desired
  284. // order due to the use of configuration dependencies in
  285. // \Drupal\Core\Config\StorageComparer::getAndSortConfigData().
  286. // Node type is a good example of a configuration entity that renames other
  287. // configuration when it is renamed.
  288. // @see \Drupal\node\Entity\NodeType::postSave()
  289. foreach ($this->targetNames[$collection] as $name) {
  290. $data = $this->getTargetStorage($collection)->read($name);
  291. if (isset($data['uuid']) && isset($create_uuids[$data['uuid']])) {
  292. // Remove the item from the create list.
  293. $this->removeFromChangelist($collection, 'create', $create_uuids[$data['uuid']]);
  294. // Remove the item from the delete list.
  295. $this->removeFromChangelist($collection, 'delete', $name);
  296. // Create the rename name.
  297. $renames[] = $this->createRenameName($name, $create_uuids[$data['uuid']]);
  298. }
  299. }
  300. $this->addChangeList($collection, 'rename', $renames);
  301. }
  302. /**
  303. * Removes the entry from the given operation changelist for the given name.
  304. *
  305. * @param string $collection
  306. * The storage collection to operate on.
  307. * @param string $op
  308. * The changelist to act on. Either delete, create, rename or update.
  309. * @param string $name
  310. * The name of the configuration to remove.
  311. */
  312. protected function removeFromChangelist($collection, $op, $name) {
  313. $key = array_search($name, $this->changelist[$collection][$op]);
  314. if ($key !== FALSE) {
  315. unset($this->changelist[$collection][$op][$key]);
  316. }
  317. }
  318. /**
  319. * {@inheritdoc}
  320. */
  321. public function moveRenameToUpdate($rename, $collection = StorageInterface::DEFAULT_COLLECTION) {
  322. $names = $this->extractRenameNames($rename);
  323. $this->removeFromChangelist($collection, 'rename', $rename);
  324. $this->addChangeList($collection, 'update', [$names['new_name']], $this->sourceNames[$collection]);
  325. }
  326. /**
  327. * {@inheritdoc}
  328. */
  329. public function reset() {
  330. $this->changelist = [StorageInterface::DEFAULT_COLLECTION => $this->getEmptyChangelist()];
  331. $this->sourceNames = $this->targetNames = [];
  332. // Reset the static configuration data caches.
  333. $this->sourceCacheStorage->deleteAll();
  334. $this->targetCacheStorage->deleteAll();
  335. return $this->createChangelist();
  336. }
  337. /**
  338. * {@inheritdoc}
  339. */
  340. public function hasChanges() {
  341. foreach ($this->getAllCollectionNames() as $collection) {
  342. foreach (['delete', 'create', 'update', 'rename'] as $op) {
  343. if (!empty($this->changelist[$collection][$op])) {
  344. return TRUE;
  345. }
  346. }
  347. }
  348. return FALSE;
  349. }
  350. /**
  351. * {@inheritdoc}
  352. */
  353. public function validateSiteUuid() {
  354. $source = $this->sourceStorage->read('system.site');
  355. $target = $this->targetStorage->read('system.site');
  356. // It is possible that the storage does not contain system.site
  357. // configuration. In such cases the site UUID cannot be valid.
  358. return $source && $target && $source['uuid'] === $target['uuid'];
  359. }
  360. /**
  361. * Gets and sorts configuration data from the source and target storages.
  362. */
  363. protected function getAndSortConfigData($collection) {
  364. $source_storage = $this->getSourceStorage($collection);
  365. $target_storage = $this->getTargetStorage($collection);
  366. $target_names = $target_storage->listAll();
  367. $source_names = $source_storage->listAll();
  368. // Prime the static caches by reading all the configuration in the source
  369. // and target storages.
  370. $target_data = $target_storage->readMultiple($target_names);
  371. $source_data = $source_storage->readMultiple($source_names);
  372. // If the collection only supports simple configuration do not use
  373. // configuration dependencies.
  374. if ($collection == StorageInterface::DEFAULT_COLLECTION) {
  375. $dependency_manager = new ConfigDependencyManager();
  376. $this->targetNames[$collection] = $dependency_manager->setData($target_data)->sortAll();
  377. $this->sourceNames[$collection] = $dependency_manager->setData($source_data)->sortAll();
  378. }
  379. else {
  380. $this->targetNames[$collection] = $target_names;
  381. $this->sourceNames[$collection] = $source_names;
  382. }
  383. }
  384. /**
  385. * Creates a rename name from the old and new names for the object.
  386. *
  387. * @param string $old_name
  388. * The old configuration object name.
  389. * @param string $new_name
  390. * The new configuration object name.
  391. *
  392. * @return string
  393. * The configuration change name that encodes both the old and the new name.
  394. *
  395. * @see \Drupal\Core\Config\StorageComparerInterface::extractRenameNames()
  396. */
  397. protected function createRenameName($old_name, $new_name) {
  398. return $old_name . '::' . $new_name;
  399. }
  400. /**
  401. * {@inheritdoc}
  402. */
  403. public function extractRenameNames($name) {
  404. $names = explode('::', $name, 2);
  405. return [
  406. 'old_name' => $names[0],
  407. 'new_name' => $names[1],
  408. ];
  409. }
  410. /**
  411. * {@inheritdoc}
  412. */
  413. public function getAllCollectionNames($include_default = TRUE) {
  414. $collections = array_unique(array_merge($this->sourceStorage->getAllCollectionNames(), $this->targetStorage->getAllCollectionNames()));
  415. if ($include_default) {
  416. array_unshift($collections, StorageInterface::DEFAULT_COLLECTION);
  417. }
  418. return $collections;
  419. }
  420. }