StorageCopyTrait.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. namespace Drupal\Core\Config;
  3. /**
  4. * Utility trait to copy configuration from one storage to another.
  5. */
  6. trait StorageCopyTrait {
  7. /**
  8. * Copy the configuration from one storage to another and remove stale items.
  9. *
  10. * This method empties target storage and copies all collections from source.
  11. * Configuration is only copied and not imported, should not be used
  12. * with the active storage as the target.
  13. *
  14. * @param \Drupal\Core\Config\StorageInterface $source
  15. * The configuration storage to copy from.
  16. * @param \Drupal\Core\Config\StorageInterface $target
  17. * The configuration storage to copy to.
  18. */
  19. protected static function replaceStorageContents(StorageInterface $source, StorageInterface &$target) {
  20. // Make sure there is no stale configuration in the target storage.
  21. foreach (array_merge([StorageInterface::DEFAULT_COLLECTION], $target->getAllCollectionNames()) as $collection) {
  22. $target->createCollection($collection)->deleteAll();
  23. }
  24. // Copy all the configuration from all the collections.
  25. foreach (array_merge([StorageInterface::DEFAULT_COLLECTION], $source->getAllCollectionNames()) as $collection) {
  26. $source_collection = $source->createCollection($collection);
  27. $target_collection = $target->createCollection($collection);
  28. foreach ($source_collection->listAll() as $name) {
  29. $data = $source_collection->read($name);
  30. if ($data !== FALSE) {
  31. $target_collection->write($name, $data);
  32. }
  33. else {
  34. \Drupal::logger('config')->notice('Missing required data for configuration: %config', [
  35. '%config' => $name,
  36. ]);
  37. }
  38. }
  39. }
  40. // Make sure that the target is set to the same collection as the source.
  41. $target = $target->createCollection($source->getCollectionName());
  42. }
  43. }