ConfigSync.php 14.7 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\Render\RendererInterface;
25
use Drupal\Core\Url;
26 27
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
28 29 30 31

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

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

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

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

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

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

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

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

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

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

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

104 105 106 107 108 109 110
  /**
   * The renderer.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

111 112 113
  /**
   * Constructs the object.
   *
114 115 116 117 118 119
   * @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.
120 121 122 123
   * @param \Drupal\Core\Lock\LockBackendInterface $lock
   *   The lock object.
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
   *   Event dispatcher.
124
   * @param \Drupal\Core\Config\ConfigManagerInterface $config_manager
125
   *   Configuration manager.
126
   * @param \Drupal\Core\Config\TypedConfigManagerInterface $typed_config
127
   *   The typed configuration manager.
128
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
129
   *   The module handler.
130 131
   * @param \Drupal\Core\Extension\ModuleInstallerInterface $module_installer
   *   The module installer.
132
   * @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler
133
   *   The theme handler.
134 135
   * @param \Drupal\Core\Render\RendererInterface
   *   The renderer.
136
   */
137
  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, RendererInterface $renderer) {
138 139 140
    $this->stagingStorage = $staging_storage;
    $this->activeStorage = $active_storage;
    $this->snapshotStorage = $snapshot_storage;
141 142
    $this->lock = $lock;
    $this->eventDispatcher = $event_dispatcher;
143
    $this->configManager = $config_manager;
144
    $this->typedConfigManager = $typed_config;
145
    $this->moduleHandler = $module_handler;
146
    $this->moduleInstaller = $module_installer;
147
    $this->themeHandler = $theme_handler;
148
    $this->renderer = $renderer;
149 150 151 152 153 154 155 156 157
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.storage.staging'),
      $container->get('config.storage'),
158
      $container->get('config.storage.snapshot'),
159
      $container->get('lock.persistent'),
160
      $container->get('event_dispatcher'),
161
      $container->get('config.manager'),
162 163
      $container->get('config.typed'),
      $container->get('module_handler'),
164
      $container->get('module_installer'),
165 166
      $container->get('theme_handler'),
      $container->get('renderer')
167 168 169 170 171 172
    );
  }

  /**
   * {@inheritdoc}
   */
173
  public function getFormId() {
174 175 176 177 178 179
    return 'config_admin_import_form';
  }

  /**
   * {@inheritdoc}
   */
180
  public function buildForm(array $form, FormStateInterface $form_state) {
181 182 183
    $form['actions'] = array('#type' => 'actions');
    $form['actions']['submit'] = array(
      '#type' => 'submit',
184
      '#value' => $this->t('Import all'),
185
    );
186 187
    $source_list = $this->stagingStorage->listAll();
    $storage_comparer = new StorageComparer($this->stagingStorage, $this->activeStorage, $this->configManager);
188
    if (empty($source_list) || !$storage_comparer->createChangelist()->hasChanges()) {
189
      $form['no_changes'] = array(
190
        '#type' => 'table',
191 192
        '#header' => array('Name', 'Operations'),
        '#rows' => array(),
193
        '#empty' => $this->t('There are no configuration changes to import.'),
194 195 196 197
      );
      $form['actions']['#access'] = FALSE;
      return $form;
    }
198 199 200 201 202
    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;
    }
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
    // A list of changes will be displayed, so check if the user should be
    // warned of potential losses to configuration.
    if ($this->snapshotStorage->exists('core.extension')) {
      $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);
220 221 222 223 224 225 226 227 228 229
        $message = [
          [
            '#markup' => $this->t('The following items in your active configuration have changes since the last import that may be lost on the next import.')
          ],
          [
            '#theme' => 'item_list',
            '#items' => $change_list,
          ]
        ];
        drupal_set_message($this->renderer->renderPlain($message), 'warning');
230
      }
231 232
    }

233 234 235
    // Store the comparer for use in the submit.
    $form_state->set('storage_comparer', $storage_comparer);

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

239 240 241 242 243
    foreach ($storage_comparer->getAllCollectionNames() as $collection) {
      if ($collection != StorageInterface::DEFAULT_COLLECTION) {
        $form[$collection]['collection_heading'] = array(
          '#type' => 'html_tag',
          '#tag' => 'h2',
244
          '#value' => $this->t('@collection configuration collection', array('@collection' => $collection)),
245
        );
246
      }
247 248 249 250
      foreach ($storage_comparer->getChangelist(NULL, $collection) as $config_change_type => $config_names) {
        if (empty($config_names)) {
          continue;
        }
251

252 253 254 255 256 257 258 259
        // @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':
260
            $form[$collection][$config_change_type]['heading']['#value'] = $this->formatPlural(count($config_names), '@count new', '@count new');
261
            break;
262

263
          case 'update':
264
            $form[$collection][$config_change_type]['heading']['#value'] = $this->formatPlural(count($config_names), '@count changed', '@count changed');
265
            break;
266

267
          case 'delete':
268
            $form[$collection][$config_change_type]['heading']['#value'] = $this->formatPlural(count($config_names), '@count removed', '@count removed');
269
            break;
270

271
          case 'rename':
272
            $form[$collection][$config_change_type]['heading']['#value'] = $this->formatPlural(count($config_names), '@count renamed', '@count renamed');
273
            break;
274
        }
275 276 277
        $form[$collection][$config_change_type]['list'] = array(
          '#type' => 'table',
          '#header' => array('Name', 'Operations'),
278
        );
279 280 281 282 283

        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']);
284
            $config_name = $this->t('@source_name to @target_name', array('@source_name' => $names['old_name'], '@target_name' => $names['new_name']));
285 286 287 288 289
          }
          else {
            $route_options = array('source_name' => $config_name);
          }
          if ($collection != StorageInterface::DEFAULT_COLLECTION) {
290
            $route_name = 'config.diff_collection';
291 292 293
            $route_options['collection'] = $collection;
          }
          else {
294
            $route_name = 'config.diff';
295 296 297
          }
          $links['view_diff'] = array(
            'title' => $this->t('View differences'),
298
            'url' => Url::fromRoute($route_name, $route_options),
299 300
            'attributes' => array(
              'class' => array('use-ajax'),
301
              'data-dialog-type' => 'modal',
302 303 304
              'data-dialog-options' => json_encode(array(
                'width' => 700
              )),
305
            ),
306 307 308 309 310 311 312 313 314 315 316
          );
          $form[$collection][$config_change_type]['list']['#rows'][] = array(
            'name' => $config_name,
            'operations' => array(
              'data' => array(
                '#type' => 'operations',
                '#links' => $links,
              ),
            ),
          );
        }
317 318 319 320 321 322 323 324
      }
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
325
  public function submitForm(array &$form, FormStateInterface $form_state) {
326
    $config_importer = new ConfigImporter(
327
      $form_state->get('storage_comparer'),
328
      $this->eventDispatcher,
329
      $this->configManager,
330
      $this->lock,
331 332
      $this->typedConfigManager,
      $this->moduleHandler,
333
      $this->moduleInstaller,
334
      $this->themeHandler,
335
      $this->getStringTranslation()
336 337
    );
    if ($config_importer->alreadyImporting()) {
338
      drupal_set_message($this->t('Another request may be synchronizing configuration already.'));
339 340
    }
    else{
341 342 343 344 345 346 347 348 349 350 351 352 353 354
      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));
        }
355

356 357 358 359
        batch_set($batch);
      }
      catch (ConfigImporterException $e) {
        // There are validation errors.
360
        drupal_set_message($this->t('The configuration cannot be imported because it failed validation for the following reasons:'), 'error');
361 362 363 364
        foreach ($config_importer->getErrors() as $message) {
          drupal_set_message($message, 'error');
        }
      }
365 366 367 368 369 370
    }
  }

  /**
   * Processes the config import batch and persists the importer.
   *
371
   * @param \Drupal\Core\Config\ConfigImporter $config_importer
372
   *   The batch config importer object to persist.
373
   * @param string $sync_step
374
   *   The synchronization step to do.
375
   * @param array $context
376 377
   *   The batch context.
   */
378
  public static function processBatch(ConfigImporter $config_importer, $sync_step, &$context) {
379 380
    if (!isset($context['sandbox']['config_importer'])) {
      $context['sandbox']['config_importer'] = $config_importer;
381
    }
382 383

    $config_importer = $context['sandbox']['config_importer'];
384
    $config_importer->doSyncStep($sync_step, $context);
385 386 387 388 389 390
    if ($errors = $config_importer->getErrors()) {
      if (!isset($context['results']['errors'])) {
        $context['results']['errors'] = array();
      }
      $context['results']['errors'] += $errors;
    }
391 392 393 394 395
  }

  /**
   * Finish batch.
   *
396
   * This function is a static function to avoid serializing the ConfigSync
397 398 399 400
   * object unnecessarily.
   */
  public static function finishBatch($success, $results, $operations) {
    if ($success) {
401 402 403
      if (!empty($results['errors'])) {
        foreach ($results['errors'] as $error) {
          drupal_set_message($error, 'error');
404
          \Drupal::logger('config_sync')->error($error);
405 406 407 408 409 410
        }
        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.'));
      }
411 412 413 414 415 416 417 418
    }
    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');
    }
419 420
  }

421

422
}