ConfigManager.php 18.3 KB
Newer Older
1 2 3 4
<?php

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 10
use Drupal\Core\Entity\EntityManagerInterface;
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;
15 16 17 18 19

/**
 * The ConfigManager provides helper functions for the configuration system.
 */
class ConfigManager implements ConfigManagerInterface {
20
  use StringTranslationTrait;
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38

  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface
   */
  protected $entityManager;

  /**
   * The configuration factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The typed config manager.
   *
39
   * @var \Drupal\Core\Config\TypedConfigManagerInterface
40 41 42
   */
  protected $typedConfigManager;

43 44 45 46 47 48 49
  /**
   * The active configuration storage.
   *
   * @var \Drupal\Core\Config\StorageInterface
   */
  protected $activeStorage;

50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
  /**
   * The event dispatcher.
   *
   * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
   */
  protected $eventDispatcher;

  /**
   * The configuration collection info.
   *
   * @var \Drupal\Core\Config\ConfigCollectionInfo
   */
  protected $configCollectionInfo;

  /**
   * The configuration storages keyed by collection name.
   *
   * @var \Drupal\Core\Config\StorageInterface[]
   */
  protected $storages;

71 72 73 74 75
  /**
   * Creates ConfigManager objects.
   *
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager.
76 77
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   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 83 84 85
   * @param \Drupal\Core\Config\StorageInterface $active_storage
   *   The active configuration storage.
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
   *   The event dispatcher.
86
   */
87
  public function __construct(EntityManagerInterface $entity_manager, ConfigFactoryInterface $config_factory, TypedConfigManagerInterface $typed_config_manager, TranslationInterface $string_translation, StorageInterface $active_storage, EventDispatcherInterface $event_dispatcher) {
88 89 90 91
    $this->entityManager = $entity_manager;
    $this->configFactory = $config_factory;
    $this->typedConfigManager = $typed_config_manager;
    $this->stringTranslation = $string_translation;
92
    $this->activeStorage = $active_storage;
93
    $this->eventDispatcher = $event_dispatcher;
94 95 96 97 98 99 100
  }

  /**
   * {@inheritdoc}
   */
  public function getEntityTypeIdByName($name) {
    $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;
102 103 104 105 106
    });
    return key($entities);
  }

  /**
107 108 109 110 111 112 113 114 115 116 117 118 119
   * {@inheritdoc}
   */
  public function loadConfigEntityByName($name) {
    $entity_type_id = $this->getEntityTypeIdByName($name);
    if ($entity_type_id) {
      $entity_type = $this->entityManager->getDefinition($entity_type_id);
      $id = substr($name, strlen($entity_type->getConfigPrefix()) + 1);
      return $this->entityManager->getStorage($entity_type_id)->load($id);
    }
    return NULL;
  }

  /**
120 121 122 123 124 125
   * {@inheritdoc}
   */
  public function getEntityManager() {
    return $this->entityManager;
  }

126 127 128 129 130 131 132
  /**
   * {@inheritdoc}
   */
  public function getConfigFactory() {
    return $this->configFactory;
  }

133 134 135
  /**
   * {@inheritdoc}
   */
136 137 138 139 140
  public function diff(StorageInterface $source_storage, StorageInterface $target_storage, $source_name, $target_name = NULL, $collection = StorageInterface::DEFAULT_COLLECTION) {
    if ($collection != StorageInterface::DEFAULT_COLLECTION) {
      $source_storage = $source_storage->createCollection($collection);
      $target_storage = $target_storage->createCollection($collection);
    }
141 142 143
    if (!isset($target_name)) {
      $target_name = $source_name;
    }
144 145 146
    // The output should show configuration object differences formatted as YAML.
    // But the configuration is not necessarily stored in files. Therefore, they
    // need to be read and parsed, and lastly, dumped into YAML strings.
147 148
    $source_data = explode("\n", Yaml::encode($source_storage->read($source_name)));
    $target_data = explode("\n", Yaml::encode($target_storage->read($target_name)));
149 150 151 152

    // Check for new or removed files.
    if ($source_data === array('false')) {
      // Added file.
153 154 155
      // Cast the result of t() to a string, as the diff engine doesn't know
      // about objects.
      $source_data = array((string) $this->t('File added'));
156 157 158
    }
    if ($target_data === array('false')) {
      // Deleted file.
159 160 161
      // Cast the result of t() to a string, as the diff engine doesn't know
      // about objects.
      $target_data = array((string) $this->t('File removed'));
162 163
    }

164
    return new Diff($source_data, $target_data);
165 166 167 168 169
  }

  /**
   * {@inheritdoc}
   */
170
  public function createSnapshot(StorageInterface $source_storage, StorageInterface $snapshot_storage) {
171
    // Empty the snapshot of all configuration.
172
    $snapshot_storage->deleteAll();
173 174 175 176
    foreach ($snapshot_storage->getAllCollectionNames() as $collection) {
      $snapshot_collection = $snapshot_storage->createCollection($collection);
      $snapshot_collection->deleteAll();
    }
177 178 179
    foreach ($source_storage->listAll() as $name) {
      $snapshot_storage->write($name, $source_storage->read($name));
    }
180 181 182 183 184 185 186 187
    // Copy collections as well.
    foreach ($source_storage->getAllCollectionNames() as $collection) {
      $source_collection = $source_storage->createCollection($collection);
      $snapshot_collection = $snapshot_storage->createCollection($collection);
      foreach ($source_collection->listAll() as $name) {
        $snapshot_collection->write($name, $source_collection->read($name));
      }
    }
188 189 190
  }

  /**
191
   * {@inheritdoc}
192
   */
193
  public function uninstall($type, $name) {
194 195 196 197 198
    $entities = $this->getConfigEntitiesToChangeOnDependencyRemoval($type, [$name], FALSE);
    // Fix all dependent configuration entities.
    /** @var \Drupal\Core\Config\Entity\ConfigEntityInterface $entity */
    foreach ($entities['update'] as $entity) {
      $entity->save();
199
    }
200 201 202 203
    // Remove all dependent configuration entities.
    foreach ($entities['delete'] as $entity) {
      $entity->setUninstalling(TRUE);
      $entity->delete();
204 205
    }

206 207
    $config_names = $this->configFactory->listAll($name . '.');
    foreach ($config_names as $config_name) {
208
      $this->configFactory->getEditable($config_name)->delete();
209
    }
210 211 212 213 214 215 216

    // Remove any matching configuration from collections.
    foreach ($this->activeStorage->getAllCollectionNames() as $collection) {
      $collection_storage = $this->activeStorage->createCollection($collection);
      $collection_storage->deleteAll($name . '.');
    }

217
    $schema_dir = drupal_get_path($type, $name) . '/' . InstallStorage::CONFIG_SCHEMA_DIRECTORY;
218 219 220 221 222 223
    if (is_dir($schema_dir)) {
      // Refresh the schema cache if uninstalling an extension that provides
      // configuration schema.
      $this->typedConfigManager->clearCachedDefinitions();
    }
  }
224

225 226 227
  /**
   * {@inheritdoc}
   */
228
  public function getConfigDependencyManager() {
229
    $dependency_manager = new ConfigDependencyManager();
230 231 232 233 234 235 236 237 238 239 240 241 242 243
    // Read all configuration using the factory. This ensures that multiple
    // deletes during the same request benefit from the static cache. Using the
    // factory also ensures configuration entity dependency discovery has no
    // dependencies on the config entity classes. Assume data with UUID is a
    // config entity. Only configuration entities can be depended on so we can
    // ignore everything else.
    $data = array_map(function($config) {
      $data = $config->get();
      if (isset($data['uuid'])) {
        return $data;
      }
      return FALSE;
    }, $this->configFactory->loadMultiple($this->activeStorage->listAll()));
    $dependency_manager->setData(array_filter($data));
244 245 246 247 248 249 250 251 252 253
    return $dependency_manager;
  }

  /**
   * {@inheritdoc}
   */
  public function findConfigEntityDependents($type, array $names, ConfigDependencyManager $dependency_manager = NULL) {
    if (!$dependency_manager) {
      $dependency_manager = $this->getConfigDependencyManager();
    }
254 255 256 257 258 259 260 261 262 263
    $dependencies = array();
    foreach ($names as $name) {
      $dependencies = array_merge($dependencies, $dependency_manager->getDependentEntities($type, $name));
    }
    return $dependencies;
  }

  /**
   * {@inheritdoc}
   */
264 265
  public function findConfigEntityDependentsAsEntities($type, array $names, ConfigDependencyManager $dependency_manager = NULL) {
    $dependencies = $this->findConfigEntityDependents($type, $names, $dependency_manager);
266 267 268 269
    $entities = array();
    $definitions = $this->entityManager->getDefinitions();
    foreach ($dependencies as $config_name => $dependency) {
      // Group by entity type to efficient load entities using
270
      // \Drupal\Core\Entity\EntityStorageInterface::loadMultiple().
271 272 273 274 275 276 277 278 279 280 281 282
      $entity_type_id = $this->getEntityTypeIdByName($config_name);
      // It is possible that a non-configuration entity will be returned if a
      // simple configuration object has a UUID key. This would occur if the
      // dependents of the system module are calculated since system.site has
      // a UUID key.
      if ($entity_type_id) {
        $id = substr($config_name, strlen($definitions[$entity_type_id]->getConfigPrefix()) + 1);
        $entities[$entity_type_id][] = $id;
      }
    }
    $entities_to_return = array();
    foreach ($entities as $entity_type_id => $entities_to_load) {
283
      $storage = $this->entityManager->getStorage($entity_type_id);
284 285
      // Remove the keys since there are potential ID clashes from different
      // configuration entity types.
286
      $entities_to_return = array_merge($entities_to_return, array_values($storage->loadMultiple($entities_to_load)));
287 288 289 290
    }
    return $entities_to_return;
  }

291 292 293 294 295 296 297 298 299
  /**
   * {@inheritdoc}
   */
  public function getConfigEntitiesToChangeOnDependencyRemoval($type, array $names, $dry_run = TRUE) {
    // Determine the current list of dependent configuration entities and set up
    // initial values.
    $dependency_manager = $this->getConfigDependencyManager();
    $dependents = $this->findConfigEntityDependentsAsEntities($type, $names, $dependency_manager);
    $original_dependencies = $dependents;
300
    $delete_uuids = $update_uuids = [];
301 302 303 304 305 306 307 308

    $return = [
      'update' => [],
      'delete' => [],
      'unchanged' => [],
    ];

    // Try to fix any dependencies and find out what will happen to the
309
    // dependency graph. Entities are processed in the order of most dependent
310 311 312
    // first. For example, this ensures that Menu UI third party dependencies on
    // node types are fixed before processing the node type's other
    // dependencies.
313
    while ($dependent = array_pop($dependents)) {
314 315 316 317 318
      /** @var \Drupal\Core\Config\Entity\ConfigEntityInterface $dependent */
      if ($dry_run) {
        // Clone the entity so any changes do not change any static caches.
        $dependent = clone $dependent;
      }
319
      $fixed = FALSE;
320 321
      if ($this->callOnDependencyRemoval($dependent, $original_dependencies, $type, $names)) {
        // Recalculate dependencies and update the dependency graph data.
322 323
        $dependent->calculateDependencies();
        $dependency_manager->updateData($dependent->getConfigDependencyName(), $dependent->getDependencies());
324 325
        // Based on the updated data rebuild the list of dependents. This will
        // remove entities that are no longer dependent after the recalculation.
326
        $dependents = $this->findConfigEntityDependentsAsEntities($type, $names, $dependency_manager);
327 328 329 330
        // Remove any entities that we've already marked for deletion.
        $dependents = array_filter($dependents, function ($dependent) use ($delete_uuids) {
          return !in_array($dependent->uuid(), $delete_uuids);
        });
331 332 333 334
        // Ensure that the dependency has actually been fixed. It is possible
        // that the dependent has multiple dependencies that cause it to be in
        // the dependency chain.
        $fixed = TRUE;
335
        foreach ($dependents as $key => $entity) {
336 337
          if ($entity->uuid() == $dependent->uuid()) {
            $fixed = FALSE;
338
            unset($dependents[$key]);
339 340 341 342 343 344 345 346
            break;
          }
        }
        if ($fixed) {
          $return['update'][] = $dependent;
          $update_uuids[] = $dependent->uuid();
        }
      }
347 348 349
      // If the entity cannot be fixed then it has to be deleted.
      if (!$fixed) {
        $delete_uuids[] = $dependent->uuid();
350 351 352
        // Deletes should occur in the order of the least dependent first. For
        // example, this ensures that fields are removed before field storages.
        array_unshift($return['delete'], $dependent);
353
      }
354 355 356 357 358 359 360 361 362 363
    }
    // Use the lists of UUIDs to filter the original list to work out which
    // configuration entities are unchanged.
    $return['unchanged'] = array_filter($original_dependencies, function ($dependent) use ($delete_uuids, $update_uuids) {
      return !(in_array($dependent->uuid(), $delete_uuids) || in_array($dependent->uuid(), $update_uuids));
    });

    return $return;
  }

364 365 366 367 368 369 370 371 372 373 374
  /**
   * {@inheritdoc}
   */
  public function getConfigCollectionInfo() {
    if (!isset($this->configCollectionInfo)) {
      $this->configCollectionInfo = new ConfigCollectionInfo();
      $this->eventDispatcher->dispatch(ConfigEvents::COLLECTION_INFO, $this->configCollectionInfo);
    }
    return $this->configCollectionInfo;
  }

375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
  /**
   * Calls an entity's onDependencyRemoval() method.
   *
   * A helper method to call onDependencyRemoval() with the correct list of
   * affected entities. This list should only contain dependencies on the
   * entity. Configuration and content entity dependencies will be converted
   * into entity objects.
   *
   * @param \Drupal\Core\Config\Entity\ConfigEntityInterface $entity
   *   The entity to call onDependencyRemoval() on.
   * @param \Drupal\Core\Config\Entity\ConfigEntityInterface[] $dependent_entities
   *   The list of dependent configuration entities.
   * @param string $type
   *   The type of dependency being checked. Either 'module', 'theme', 'config'
   *   or 'content'.
   * @param array $names
   *   The specific names to check. If $type equals 'module' or 'theme' then it
   *   should be a list of module names or theme names. In the case of 'config'
   *   or 'content' it should be a list of configuration dependency names.
   *
   * @return bool
   *   TRUE if the entity has changed as a result of calling the
   *   onDependencyRemoval() method, FALSE if not.
   */
  protected function callOnDependencyRemoval(ConfigEntityInterface $entity, array $dependent_entities, $type, array $names) {
    $entity_dependencies = $entity->getDependencies();
    if (empty($entity_dependencies)) {
      // No dependent entities nothing to do.
      return FALSE;
    }

    $affected_dependencies = array(
      'config' => array(),
      'content' => array(),
      'module' => array(),
      'theme' => array(),
    );

    // Work out if any of the entity's dependencies are going to be affected.
    if (isset($entity_dependencies[$type])) {
      // Work out which dependencies the entity has in common with the provided
      // $type and $names.
      $affected_dependencies[$type] = array_intersect($entity_dependencies[$type], $names);

      // If the dependencies are entities we need to convert them into objects.
      if ($type == 'config' || $type == 'content') {
        $affected_dependencies[$type] = array_map(function ($name) use ($type) {
          if ($type == 'config') {
423
            return $this->loadConfigEntityByName($name);
424 425
          }
          else {
426 427 428
            // Ignore the bundle.
            list($entity_type_id,, $uuid) = explode(':', $name);
            return $this->entityManager->loadEntityByConfigTarget($entity_type_id, $uuid);
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
          }
        }, $affected_dependencies[$type]);
      }
    }

    // Merge any other configuration entities into the list of affected
    // dependencies if necessary.
    if (isset($entity_dependencies['config'])) {
      foreach ($dependent_entities as $dependent_entity) {
        if (in_array($dependent_entity->getConfigDependencyName(), $entity_dependencies['config'])) {
          $affected_dependencies['config'][] = $dependent_entity;
        }
      }
    }

444 445 446 447 448 449 450 451
    // Key the entity arrays by config dependency name to make searching easy.
    foreach (['config', 'content'] as $dependency_type) {
      $affected_dependencies[$dependency_type] = array_combine(
        array_map(function ($entity) { return $entity->getConfigDependencyName(); }, $affected_dependencies[$dependency_type]),
        $affected_dependencies[$dependency_type]
      );
    }

452 453 454 455
    // Inform the entity.
    return $entity->onDependencyRemoval($affected_dependencies);
  }

456 457 458 459 460 461 462 463 464 465
  /**
   * {@inheritdoc}
   */
  public function findMissingContentDependencies() {
    $content_dependencies = array();
    $missing_dependencies = array();
    foreach ($this->activeStorage->readMultiple($this->activeStorage->listAll()) as $config_data) {
      if (isset($config_data['dependencies']['content'])) {
        $content_dependencies = array_merge($content_dependencies, $config_data['dependencies']['content']);
      }
466 467 468
      if (isset($config_data['dependencies']['enforced']['content'])) {
        $content_dependencies = array_merge($content_dependencies, $config_data['dependencies']['enforced']['content']);
      }
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
    }
    foreach (array_unique($content_dependencies) as $content_dependency) {
      // Format of the dependency is entity_type:bundle:uuid.
      list($entity_type, $bundle, $uuid) = explode(':', $content_dependency, 3);
      if (!$this->entityManager->loadEntityByUuid($entity_type, $uuid)) {
        $missing_dependencies[$uuid] = array(
          'entity_type' => $entity_type,
          'bundle' => $bundle,
          'uuid' => $uuid,
        );
      }
    }
    return $missing_dependencies;
  }

484
}