StorageComparer.php 15 KB

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