ConfigSync.php 14.1 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains \Drupal\config\Form\ConfigSync.
 */

namespace Drupal\config\Form;

10
use Drupal\Component\Uuid\UuidInterface;
11
use Drupal\Core\Config\ConfigImporterException;
12
use Drupal\Core\Config\ConfigImporter;
13
use Drupal\Core\Config\TypedConfigManagerInterface;
14 15
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
16
use Drupal\Core\Extension\ModuleInstallerInterface;
17
use Drupal\Core\Extension\ThemeHandlerInterface;
18
use Drupal\Core\Config\ConfigManagerInterface;
19
use Drupal\Core\Form\FormBase;
20
use Drupal\Core\Config\StorageInterface;
21
use Drupal\Core\Form\FormStateInterface;
22 23
use Drupal\Core\Lock\LockBackendInterface;
use Drupal\Core\Config\StorageComparer;
24
use Drupal\Core\Url;
25 26
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
27 28 29 30

/**
 * Construct the storage changes in a configuration synchronization form.
 */
31
class ConfigSync extends FormBase {
32 33 34 35 36 37 38 39 40

  /**
   * The database lock object.
   *
   * @var \Drupal\Core\Lock\LockBackendInterface
   */
  protected $lock;

  /**
41
   * The staging configuration object.
42 43 44
   *
   * @var \Drupal\Core\Config\StorageInterface
   */
45
  protected $stagingStorage;
46 47

  /**
48
   * The active configuration object.
49 50 51
   *
   * @var \Drupal\Core\Config\StorageInterface
   */
52 53 54 55 56 57 58 59
  protected $activeStorage;

  /**
   * The snapshot configuration object.
   *
   * @var \Drupal\Core\Config\StorageInterface
   */
  protected $snapshotStorage;
60 61 62 63 64 65 66 67 68

  /**
   * Event dispatcher.
   *
   * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
   */
  protected $eventDispatcher;

  /**
69 70 71
   * The configuration manager.
   *
   * @var \Drupal\Core\Config\ConfigManagerInterface;
72
   */
73
  protected $configManager;
74

75 76 77
  /**
   * The typed config manager.
   *
78
   * @var \Drupal\Core\Config\TypedConfigManagerInterface
79 80 81
   */
  protected $typedConfigManager;

82 83 84 85 86 87 88 89 90 91 92 93 94 95
  /**
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The theme handler.
   *
   * @var \Drupal\Core\Extension\ThemeHandlerInterface
   */
  protected $themeHandler;

96 97 98 99 100 101 102
  /**
   * The module installer.
   *
   * @var \Drupal\Core\Extension\ModuleInstallerInterface
   */
  protected $moduleInstaller;

103 104 105
  /**
   * Constructs the object.
   *
106 107 108 109 110 111
   * @param \Drupal\Core\Config\StorageInterface $staging_storage
   *   The source storage.
   * @param \Drupal\Core\Config\StorageInterface $active_storage
   *   The target storage.
   * @param \Drupal\Core\Config\StorageInterface $snapshot_storage
   *   The snapshot storage.
112 113 114 115
   * @param \Drupal\Core\Lock\LockBackendInterface $lock
   *   The lock object.
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
   *   Event dispatcher.
116
   * @param \Drupal\Core\Config\ConfigManagerInterface $config_manager
117
   *   Configuration manager.
118
   * @param \Drupal\Core\Config\TypedConfigManagerInterface $typed_config
119
   *   The typed configuration manager.
120 121
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler
122 123
   * @param \Drupal\Core\Extension\ModuleInstallerInterface $module_installer
   *   The module installer.
124 125
   * @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler
   *   The theme handler
126
   */
127
  public function __construct(StorageInterface $staging_storage, StorageInterface $active_storage, StorageInterface $snapshot_storage, LockBackendInterface $lock, EventDispatcherInterface $event_dispatcher, ConfigManagerInterface $config_manager, TypedConfigManagerInterface $typed_config, ModuleHandlerInterface $module_handler, ModuleInstallerInterface $module_installer, ThemeHandlerInterface $theme_handler) {
128 129 130
    $this->stagingStorage = $staging_storage;
    $this->activeStorage = $active_storage;
    $this->snapshotStorage = $snapshot_storage;
131 132
    $this->lock = $lock;
    $this->eventDispatcher = $event_dispatcher;
133
    $this->configManager = $config_manager;
134
    $this->typedConfigManager = $typed_config;
135
    $this->moduleHandler = $module_handler;
136
    $this->moduleInstaller = $module_installer;
137
    $this->themeHandler = $theme_handler;
138 139 140 141 142 143 144 145 146
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.storage.staging'),
      $container->get('config.storage'),
147
      $container->get('config.storage.snapshot'),
148
      $container->get('lock.persistent'),
149
      $container->get('event_dispatcher'),
150
      $container->get('config.manager'),
151 152
      $container->get('config.typed'),
      $container->get('module_handler'),
153
      $container->get('module_installer'),
154
      $container->get('theme_handler')
155 156 157 158 159 160
    );
  }

  /**
   * {@inheritdoc}
   */
161
  public function getFormId() {
162 163 164 165 166 167
    return 'config_admin_import_form';
  }

  /**
   * {@inheritdoc}
   */
168
  public function buildForm(array $form, FormStateInterface $form_state) {
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
    $snapshot_comparer = new StorageComparer($this->activeStorage, $this->snapshotStorage, $this->configManager);
    if (!$form_state->getUserInput() && $snapshot_comparer->createChangelist()->hasChanges()) {
      $change_list = array();
      foreach ($snapshot_comparer->getAllCollectionNames() as $collection) {
        foreach ($snapshot_comparer->getChangelist(NULL, $collection) as $config_names) {
          if (empty($config_names)) {
            continue;
          }
          foreach ($config_names as $config_name) {
            $change_list[] = $config_name;
          }
        }
      }
      sort($change_list);
      $change_list_render = array(
        '#theme' => 'item_list',
        '#items' => $change_list,
      );
      $change_list_html = drupal_render($change_list_render);
      drupal_set_message($this->t('Your current configuration has changed. Changes to these configuration items will be lost on the next synchronization: !changes', array('!changes' => $change_list_html)), 'warning');
    }
190 191 192
    $form['actions'] = array('#type' => 'actions');
    $form['actions']['submit'] = array(
      '#type' => 'submit',
193
      '#value' => $this->t('Import all'),
194 195
    );

196 197
    $source_list = $this->stagingStorage->listAll();
    $storage_comparer = new StorageComparer($this->stagingStorage, $this->activeStorage, $this->configManager);
198
    if (empty($source_list) || !$storage_comparer->createChangelist()->hasChanges()) {
199
      $form['no_changes'] = array(
200
        '#type' => 'table',
201 202
        '#header' => array('Name', 'Operations'),
        '#rows' => array(),
203
        '#empty' => $this->t('There are no configuration changes to import.'),
204 205 206 207
      );
      $form['actions']['#access'] = FALSE;
      return $form;
    }
208 209 210 211 212
    elseif (!$storage_comparer->validateSiteUuid()) {
      drupal_set_message($this->t('The staged configuration cannot be imported, because it originates from a different site than this site. You can only synchronize configuration between cloned instances of this site.'), 'error');
      $form['actions']['#access'] = FALSE;
      return $form;
    }
213 214
    else {
      // Store the comparer for use in the submit.
215
      $form_state->set('storage_comparer', $storage_comparer);
216 217 218
    }

    // Add the AJAX library to the form for dialog support.
219
    $form['#attached']['library'][] = 'core/drupal.ajax';
220

221 222 223 224 225 226 227
    foreach ($storage_comparer->getAllCollectionNames() as $collection) {
      if ($collection != StorageInterface::DEFAULT_COLLECTION) {
        $form[$collection]['collection_heading'] = array(
          '#type' => 'html_tag',
          '#tag' => 'h2',
          '#value' => $this->t('!collection configuration collection', array('!collection' => $collection)),
        );
228
      }
229 230 231 232
      foreach ($storage_comparer->getChangelist(NULL, $collection) as $config_change_type => $config_names) {
        if (empty($config_names)) {
          continue;
        }
233

234 235 236 237 238 239 240 241
        // @todo A table caption would be more appropriate, but does not have the
        //   visual importance of a heading.
        $form[$collection][$config_change_type]['heading'] = array(
          '#type' => 'html_tag',
          '#tag' => 'h3',
        );
        switch ($config_change_type) {
          case 'create':
242
            $form[$collection][$config_change_type]['heading']['#value'] = $this->formatPlural(count($config_names), '@count new', '@count new');
243
            break;
244

245
          case 'update':
246
            $form[$collection][$config_change_type]['heading']['#value'] = $this->formatPlural(count($config_names), '@count changed', '@count changed');
247
            break;
248

249
          case 'delete':
250
            $form[$collection][$config_change_type]['heading']['#value'] = $this->formatPlural(count($config_names), '@count removed', '@count removed');
251
            break;
252

253
          case 'rename':
254
            $form[$collection][$config_change_type]['heading']['#value'] = $this->formatPlural(count($config_names), '@count renamed', '@count renamed');
255
            break;
256
        }
257 258 259
        $form[$collection][$config_change_type]['list'] = array(
          '#type' => 'table',
          '#header' => array('Name', 'Operations'),
260
        );
261 262 263 264 265 266 267 268 269 270 271

        foreach ($config_names as $config_name) {
          if ($config_change_type == 'rename') {
            $names = $storage_comparer->extractRenameNames($config_name);
            $route_options = array('source_name' => $names['old_name'], 'target_name' => $names['new_name']);
            $config_name = $this->t('!source_name to !target_name', array('!source_name' => $names['old_name'], '!target_name' => $names['new_name']));
          }
          else {
            $route_options = array('source_name' => $config_name);
          }
          if ($collection != StorageInterface::DEFAULT_COLLECTION) {
272
            $route_name = 'config.diff_collection';
273 274 275
            $route_options['collection'] = $collection;
          }
          else {
276
            $route_name = 'config.diff';
277 278 279
          }
          $links['view_diff'] = array(
            'title' => $this->t('View differences'),
280
            'url' => Url::fromRoute($route_name, $route_options),
281 282 283 284 285 286
            'attributes' => array(
              'class' => array('use-ajax'),
              'data-accepts' => 'application/vnd.drupal-modal',
              'data-dialog-options' => json_encode(array(
                'width' => 700
              )),
287
            ),
288 289 290 291 292 293 294 295 296 297 298
          );
          $form[$collection][$config_change_type]['list']['#rows'][] = array(
            'name' => $config_name,
            'operations' => array(
              'data' => array(
                '#type' => 'operations',
                '#links' => $links,
              ),
            ),
          );
        }
299 300 301 302 303 304 305 306
      }
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
307
  public function submitForm(array &$form, FormStateInterface $form_state) {
308
    $config_importer = new ConfigImporter(
309
      $form_state->get('storage_comparer'),
310
      $this->eventDispatcher,
311
      $this->configManager,
312
      $this->lock,
313 314
      $this->typedConfigManager,
      $this->moduleHandler,
315
      $this->moduleInstaller,
316
      $this->themeHandler,
317
      $this->getStringTranslation()
318 319
    );
    if ($config_importer->alreadyImporting()) {
320
      drupal_set_message($this->t('Another request may be synchronizing configuration already.'));
321 322
    }
    else{
323 324 325 326 327 328 329 330 331 332 333 334 335 336
      try {
        $sync_steps = $config_importer->initialize();
        $batch = array(
          'operations' => array(),
          'finished' => array(get_class($this), 'finishBatch'),
          'title' => t('Synchronizing configuration'),
          'init_message' => t('Starting configuration synchronization.'),
          'progress_message' => t('Completed @current step of @total.'),
          'error_message' => t('Configuration synchronization has encountered an error.'),
          'file' => drupal_get_path('module', 'config') . '/config.admin.inc',
        );
        foreach ($sync_steps as $sync_step) {
          $batch['operations'][] = array(array(get_class($this), 'processBatch'), array($config_importer, $sync_step));
        }
337

338 339 340 341 342 343 344 345 346
        batch_set($batch);
      }
      catch (ConfigImporterException $e) {
        // There are validation errors.
        drupal_set_message($this->t('The configuration synchronization failed validation.'));
        foreach ($config_importer->getErrors() as $message) {
          drupal_set_message($message, 'error');
        }
      }
347 348 349 350 351 352
    }
  }

  /**
   * Processes the config import batch and persists the importer.
   *
353
   * @param \Drupal\Core\Config\ConfigImporter $config_importer
354
   *   The batch config importer object to persist.
355
   * @param string $sync_step
356
   *   The synchronization step to do.
357 358 359
   * @param $context
   *   The batch context.
   */
360
  public static function processBatch(ConfigImporter $config_importer, $sync_step, &$context) {
361 362
    if (!isset($context['sandbox']['config_importer'])) {
      $context['sandbox']['config_importer'] = $config_importer;
363
    }
364 365

    $config_importer = $context['sandbox']['config_importer'];
366
    $config_importer->doSyncStep($sync_step, $context);
367 368 369 370 371 372
    if ($errors = $config_importer->getErrors()) {
      if (!isset($context['results']['errors'])) {
        $context['results']['errors'] = array();
      }
      $context['results']['errors'] += $errors;
    }
373 374 375 376 377
  }

  /**
   * Finish batch.
   *
378
   * This function is a static function to avoid serializing the ConfigSync
379 380 381 382
   * object unnecessarily.
   */
  public static function finishBatch($success, $results, $operations) {
    if ($success) {
383 384 385
      if (!empty($results['errors'])) {
        foreach ($results['errors'] as $error) {
          drupal_set_message($error, 'error');
386
          \Drupal::logger('config_sync')->error($error);
387 388 389 390 391 392
        }
        drupal_set_message(\Drupal::translation()->translate('The configuration was imported with errors.'), 'warning');
      }
      else {
        drupal_set_message(\Drupal::translation()->translate('The configuration was imported successfully.'));
      }
393 394 395 396 397 398 399 400
    }
    else {
      // An error occurred.
      // $operations contains the operations that remained unprocessed.
      $error_operation = reset($operations);
      $message = \Drupal::translation()->translate('An error occurred while processing %error_operation with arguments: @arguments', array('%error_operation' => $error_operation[0], '@arguments' => print_r($error_operation[1], TRUE)));
      drupal_set_message($message, 'error');
    }
401 402
  }

403

404
}