3 namespace Drupal\Core\Config;
5 use Drupal\Component\Diff\Diff;
6 use Drupal\Core\Config\Entity\ConfigDependencyManager;
7 use Drupal\Core\Config\Entity\ConfigEntityInterface;
8 use Drupal\Core\Config\Entity\ConfigEntityTypeInterface;
9 use Drupal\Core\Entity\EntityManagerInterface;
10 use Drupal\Core\Entity\EntityTypeInterface;
11 use Drupal\Core\Serialization\Yaml;
12 use Drupal\Core\StringTranslation\StringTranslationTrait;
13 use Drupal\Core\StringTranslation\TranslationInterface;
14 use Symfony\Component\EventDispatcher\EventDispatcherInterface;
17 * The ConfigManager provides helper functions for the configuration system.
19 class ConfigManager implements ConfigManagerInterface {
20 use StringTranslationTrait;
25 * @var \Drupal\Core\Entity\EntityManagerInterface
27 protected $entityManager;
30 * The configuration factory.
32 * @var \Drupal\Core\Config\ConfigFactoryInterface
34 protected $configFactory;
37 * The typed config manager.
39 * @var \Drupal\Core\Config\TypedConfigManagerInterface
41 protected $typedConfigManager;
44 * The active configuration storage.
46 * @var \Drupal\Core\Config\StorageInterface
48 protected $activeStorage;
51 * The event dispatcher.
53 * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
55 protected $eventDispatcher;
58 * The configuration collection info.
60 * @var \Drupal\Core\Config\ConfigCollectionInfo
62 protected $configCollectionInfo;
65 * The configuration storages keyed by collection name.
67 * @var \Drupal\Core\Config\StorageInterface[]
72 * Creates ConfigManager objects.
74 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
76 * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
77 * The configuration factory.
78 * @param \Drupal\Core\Config\TypedConfigManagerInterface $typed_config_manager
79 * The typed config manager.
80 * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
81 * The string translation service.
82 * @param \Drupal\Core\Config\StorageInterface $active_storage
83 * The active configuration storage.
84 * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
85 * The event dispatcher.
87 public function __construct(EntityManagerInterface $entity_manager, ConfigFactoryInterface $config_factory, TypedConfigManagerInterface $typed_config_manager, TranslationInterface $string_translation, StorageInterface $active_storage, EventDispatcherInterface $event_dispatcher) {
88 $this->entityManager = $entity_manager;
89 $this->configFactory = $config_factory;
90 $this->typedConfigManager = $typed_config_manager;
91 $this->stringTranslation = $string_translation;
92 $this->activeStorage = $active_storage;
93 $this->eventDispatcher = $event_dispatcher;
99 public function getEntityTypeIdByName($name) {
100 $entities = array_filter($this->entityManager->getDefinitions(), function (EntityTypeInterface $entity_type) use ($name) {
101 return ($entity_type instanceof ConfigEntityTypeInterface && $config_prefix = $entity_type->getConfigPrefix()) && strpos($name, $config_prefix . '.') === 0;
103 return key($entities);
109 public function loadConfigEntityByName($name) {
110 $entity_type_id = $this->getEntityTypeIdByName($name);
111 if ($entity_type_id) {
112 $entity_type = $this->entityManager->getDefinition($entity_type_id);
113 $id = substr($name, strlen($entity_type->getConfigPrefix()) + 1);
114 return $this->entityManager->getStorage($entity_type_id)->load($id);
122 public function getEntityManager() {
123 return $this->entityManager;
129 public function getConfigFactory() {
130 return $this->configFactory;
136 public function diff(StorageInterface $source_storage, StorageInterface $target_storage, $source_name, $target_name = NULL, $collection = StorageInterface::DEFAULT_COLLECTION) {
137 if ($collection != StorageInterface::DEFAULT_COLLECTION) {
138 $source_storage = $source_storage->createCollection($collection);
139 $target_storage = $target_storage->createCollection($collection);
141 if (!isset($target_name)) {
142 $target_name = $source_name;
144 // The output should show configuration object differences formatted as YAML.
145 // But the configuration is not necessarily stored in files. Therefore, they
146 // need to be read and parsed, and lastly, dumped into YAML strings.
147 $source_data = explode("\n", Yaml::encode($source_storage->read($source_name)));
148 $target_data = explode("\n", Yaml::encode($target_storage->read($target_name)));
150 // Check for new or removed files.
151 if ($source_data === ['false']) {
153 // Cast the result of t() to a string, as the diff engine doesn't know
155 $source_data = [(string) $this->t('File added')];
157 if ($target_data === ['false']) {
159 // Cast the result of t() to a string, as the diff engine doesn't know
161 $target_data = [(string) $this->t('File removed')];
164 return new Diff($source_data, $target_data);
170 public function createSnapshot(StorageInterface $source_storage, StorageInterface $snapshot_storage) {
171 // Empty the snapshot of all configuration.
172 $snapshot_storage->deleteAll();
173 foreach ($snapshot_storage->getAllCollectionNames() as $collection) {
174 $snapshot_collection = $snapshot_storage->createCollection($collection);
175 $snapshot_collection->deleteAll();
177 foreach ($source_storage->listAll() as $name) {
178 $snapshot_storage->write($name, $source_storage->read($name));
180 // Copy collections as well.
181 foreach ($source_storage->getAllCollectionNames() as $collection) {
182 $source_collection = $source_storage->createCollection($collection);
183 $snapshot_collection = $snapshot_storage->createCollection($collection);
184 foreach ($source_collection->listAll() as $name) {
185 $snapshot_collection->write($name, $source_collection->read($name));
193 public function uninstall($type, $name) {
194 $entities = $this->getConfigEntitiesToChangeOnDependencyRemoval($type, [$name], FALSE);
195 // Fix all dependent configuration entities.
196 /** @var \Drupal\Core\Config\Entity\ConfigEntityInterface $entity */
197 foreach ($entities['update'] as $entity) {
200 // Remove all dependent configuration entities.
201 foreach ($entities['delete'] as $entity) {
202 $entity->setUninstalling(TRUE);
206 $config_names = $this->configFactory->listAll($name . '.');
207 foreach ($config_names as $config_name) {
208 $this->configFactory->getEditable($config_name)->delete();
211 // Remove any matching configuration from collections.
212 foreach ($this->activeStorage->getAllCollectionNames() as $collection) {
213 $collection_storage = $this->activeStorage->createCollection($collection);
214 $collection_storage->deleteAll($name . '.');
217 $schema_dir = drupal_get_path($type, $name) . '/' . InstallStorage::CONFIG_SCHEMA_DIRECTORY;
218 if (is_dir($schema_dir)) {
219 // Refresh the schema cache if uninstalling an extension that provides
220 // configuration schema.
221 $this->typedConfigManager->clearCachedDefinitions();
228 public function getConfigDependencyManager() {
229 $dependency_manager = new ConfigDependencyManager();
230 // Read all configuration using the factory. This ensures that multiple
231 // deletes during the same request benefit from the static cache. Using the
232 // factory also ensures configuration entity dependency discovery has no
233 // dependencies on the config entity classes. Assume data with UUID is a
234 // config entity. Only configuration entities can be depended on so we can
235 // ignore everything else.
236 $data = array_map(function ($config) {
237 $data = $config->get();
238 if (isset($data['uuid'])) {
242 }, $this->configFactory->loadMultiple($this->activeStorage->listAll()));
243 $dependency_manager->setData(array_filter($data));
244 return $dependency_manager;
250 public function findConfigEntityDependents($type, array $names, ConfigDependencyManager $dependency_manager = NULL) {
251 if (!$dependency_manager) {
252 $dependency_manager = $this->getConfigDependencyManager();
255 foreach ($names as $name) {
256 $dependencies = array_merge($dependencies, $dependency_manager->getDependentEntities($type, $name));
258 return $dependencies;
264 public function findConfigEntityDependentsAsEntities($type, array $names, ConfigDependencyManager $dependency_manager = NULL) {
265 $dependencies = $this->findConfigEntityDependents($type, $names, $dependency_manager);
267 $definitions = $this->entityManager->getDefinitions();
268 foreach ($dependencies as $config_name => $dependency) {
269 // Group by entity type to efficient load entities using
270 // \Drupal\Core\Entity\EntityStorageInterface::loadMultiple().
271 $entity_type_id = $this->getEntityTypeIdByName($config_name);
272 // It is possible that a non-configuration entity will be returned if a
273 // simple configuration object has a UUID key. This would occur if the
274 // dependents of the system module are calculated since system.site has
276 if ($entity_type_id) {
277 $id = substr($config_name, strlen($definitions[$entity_type_id]->getConfigPrefix()) + 1);
278 $entities[$entity_type_id][] = $id;
281 $entities_to_return = [];
282 foreach ($entities as $entity_type_id => $entities_to_load) {
283 $storage = $this->entityManager->getStorage($entity_type_id);
284 // Remove the keys since there are potential ID clashes from different
285 // configuration entity types.
286 $entities_to_return = array_merge($entities_to_return, array_values($storage->loadMultiple($entities_to_load)));
288 return $entities_to_return;
294 public function getConfigEntitiesToChangeOnDependencyRemoval($type, array $names, $dry_run = TRUE) {
295 $dependency_manager = $this->getConfigDependencyManager();
297 // Store the list of dependents in three separate variables. This allows us
298 // to determine how the dependency graph changes as entities are fixed by
299 // calling the onDependencyRemoval() method.
301 // The list of original dependents on $names. This list never changes.
302 $original_dependents = $this->findConfigEntityDependentsAsEntities($type, $names, $dependency_manager);
304 // The current list of dependents on $names. This list is recalculated when
305 // calling an entity's onDependencyRemoval() method results in the entity
306 // changing. This list is passed to each entity's onDependencyRemoval()
307 // method as the list of affected entities.
308 $current_dependents = $original_dependents;
310 // The list of dependents to process. This list changes as entities are
311 // processed and are either fixed or deleted.
312 $dependents_to_process = $original_dependents;
314 // Initialize other variables.
315 $affected_uuids = [];
322 // Try to fix the dependents and find out what will happen to the dependency
323 // graph. Entities are processed in the order of most dependent first. For
324 // example, this ensures that Menu UI third party dependencies on node types
325 // are fixed before processing the node type's other dependents.
326 while ($dependent = array_pop($dependents_to_process)) {
327 /** @var \Drupal\Core\Config\Entity\ConfigEntityInterface $dependent */
329 // Clone the entity so any changes do not change any static caches.
330 $dependent = clone $dependent;
333 if ($this->callOnDependencyRemoval($dependent, $current_dependents, $type, $names)) {
334 // Recalculate dependencies and update the dependency graph data.
335 $dependent->calculateDependencies();
336 $dependency_manager->updateData($dependent->getConfigDependencyName(), $dependent->getDependencies());
337 // Based on the updated data rebuild the list of current dependents.
338 // This will remove entities that are no longer dependent after the
340 $current_dependents = $this->findConfigEntityDependentsAsEntities($type, $names, $dependency_manager);
341 // Rebuild the list of entities that we need to process using the new
342 // list of current dependents and removing any entities that we've
343 // already processed.
344 $dependents_to_process = array_filter($current_dependents, function ($current_dependent) use ($affected_uuids) {
345 return !in_array($current_dependent->uuid(), $affected_uuids);
347 // Ensure that the dependent has actually been fixed. It is possible
348 // that other dependencies cause it to still be in the list.
350 foreach ($dependents_to_process as $key => $entity) {
351 if ($entity->uuid() == $dependent->uuid()) {
353 unset($dependents_to_process[$key]);
358 $affected_uuids[] = $dependent->uuid();
359 $return['update'][] = $dependent;
362 // If the entity cannot be fixed then it has to be deleted.
364 $affected_uuids[] = $dependent->uuid();
365 // Deletes should occur in the order of the least dependent first. For
366 // example, this ensures that fields are removed before field storages.
367 array_unshift($return['delete'], $dependent);
370 // Use the list of affected UUIDs to filter the original list to work out
371 // which configuration entities are unchanged.
372 $return['unchanged'] = array_filter($original_dependents, function ($dependent) use ($affected_uuids) {
373 return !(in_array($dependent->uuid(), $affected_uuids));
382 public function getConfigCollectionInfo() {
383 if (!isset($this->configCollectionInfo)) {
384 $this->configCollectionInfo = new ConfigCollectionInfo();
385 $this->eventDispatcher->dispatch(ConfigEvents::COLLECTION_INFO, $this->configCollectionInfo);
387 return $this->configCollectionInfo;
391 * Calls an entity's onDependencyRemoval() method.
393 * A helper method to call onDependencyRemoval() with the correct list of
394 * affected entities. This list should only contain dependencies on the
395 * entity. Configuration and content entity dependencies will be converted
396 * into entity objects.
398 * @param \Drupal\Core\Config\Entity\ConfigEntityInterface $entity
399 * The entity to call onDependencyRemoval() on.
400 * @param \Drupal\Core\Config\Entity\ConfigEntityInterface[] $dependent_entities
401 * The list of dependent configuration entities.
402 * @param string $type
403 * The type of dependency being checked. Either 'module', 'theme', 'config'
405 * @param array $names
406 * The specific names to check. If $type equals 'module' or 'theme' then it
407 * should be a list of module names or theme names. In the case of 'config'
408 * or 'content' it should be a list of configuration dependency names.
411 * TRUE if the entity has changed as a result of calling the
412 * onDependencyRemoval() method, FALSE if not.
414 protected function callOnDependencyRemoval(ConfigEntityInterface $entity, array $dependent_entities, $type, array $names) {
415 $entity_dependencies = $entity->getDependencies();
416 if (empty($entity_dependencies)) {
417 // No dependent entities nothing to do.
421 $affected_dependencies = [
428 // Work out if any of the entity's dependencies are going to be affected.
429 if (isset($entity_dependencies[$type])) {
430 // Work out which dependencies the entity has in common with the provided
432 $affected_dependencies[$type] = array_intersect($entity_dependencies[$type], $names);
434 // If the dependencies are entities we need to convert them into objects.
435 if ($type == 'config' || $type == 'content') {
436 $affected_dependencies[$type] = array_map(function ($name) use ($type) {
437 if ($type == 'config') {
438 return $this->loadConfigEntityByName($name);
441 // Ignore the bundle.
442 list($entity_type_id,, $uuid) = explode(':', $name);
443 return $this->entityManager->loadEntityByConfigTarget($entity_type_id, $uuid);
445 }, $affected_dependencies[$type]);
449 // Merge any other configuration entities into the list of affected
450 // dependencies if necessary.
451 if (isset($entity_dependencies['config'])) {
452 foreach ($dependent_entities as $dependent_entity) {
453 if (in_array($dependent_entity->getConfigDependencyName(), $entity_dependencies['config'])) {
454 $affected_dependencies['config'][] = $dependent_entity;
459 // Key the entity arrays by config dependency name to make searching easy.
460 foreach (['config', 'content'] as $dependency_type) {
461 $affected_dependencies[$dependency_type] = array_combine(
462 array_map(function ($entity) {
463 return $entity->getConfigDependencyName();
464 }, $affected_dependencies[$dependency_type]),
465 $affected_dependencies[$dependency_type]
469 // Inform the entity.
470 return $entity->onDependencyRemoval($affected_dependencies);
476 public function findMissingContentDependencies() {
477 $content_dependencies = [];
478 $missing_dependencies = [];
479 foreach ($this->activeStorage->readMultiple($this->activeStorage->listAll()) as $config_data) {
480 if (isset($config_data['dependencies']['content'])) {
481 $content_dependencies = array_merge($content_dependencies, $config_data['dependencies']['content']);
483 if (isset($config_data['dependencies']['enforced']['content'])) {
484 $content_dependencies = array_merge($content_dependencies, $config_data['dependencies']['enforced']['content']);
487 foreach (array_unique($content_dependencies) as $content_dependency) {
488 // Format of the dependency is entity_type:bundle:uuid.
489 list($entity_type, $bundle, $uuid) = explode(':', $content_dependency, 3);
490 if (!$this->entityManager->loadEntityByUuid($entity_type, $uuid)) {
491 $missing_dependencies[$uuid] = [
492 'entity_type' => $entity_type,
498 return $missing_dependencies;