Move all files to 2017/

This commit is contained in:
Oliver Davies 2025-09-29 22:25:17 +01:00
parent ac7370f67f
commit 2875863330
15717 changed files with 0 additions and 0 deletions

View file

@ -0,0 +1,41 @@
<?php
namespace Drupal\config;
use Drupal\Core\Config\ConfigEvents;
use Drupal\Core\Config\ConfigImporterEvent;
use Drupal\Core\Config\ConfigImportValidateEventSubscriberBase;
/**
* Config subscriber.
*/
class ConfigSubscriber extends ConfigImportValidateEventSubscriberBase {
/**
* Checks that the Configuration module is not being uninstalled.
*
* @param \Drupal\Core\Config\ConfigImporterEvent $event
* The config import event.
*/
public function onConfigImporterValidate(ConfigImporterEvent $event) {
// Make sure config syncs performed via the Config UI don't break, but
// don't worry about syncs initiated via the command line.
if (PHP_SAPI === 'cli') {
return;
}
$importer = $event->getConfigImporter();
$core_extension = $importer->getStorageComparer()->getSourceStorage()->read('core.extension');
if (!isset($core_extension['module']['config'])) {
$importer->logError($this->t('Can not uninstall the Configuration module as part of a configuration synchronization through the user interface.'));
}
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events[ConfigEvents::IMPORT_VALIDATE][] = ['onConfigImporterValidate', 20];
return $events;
}
}

View file

@ -0,0 +1,164 @@
<?php
namespace Drupal\config\Controller;
use Drupal\Core\Archiver\ArchiveTar;
use Drupal\Core\Config\ConfigManagerInterface;
use Drupal\Core\Config\StorageInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Diff\DiffFormatter;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Url;
use Drupal\system\FileDownloadController;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Returns responses for config module routes.
*/
class ConfigController implements ContainerInjectionInterface {
/**
* The target storage.
*
* @var \Drupal\Core\Config\StorageInterface
*/
protected $targetStorage;
/**
* The source storage.
*
* @var \Drupal\Core\Config\StorageInterface
*/
protected $sourceStorage;
/**
* The configuration manager.
*
* @var \Drupal\Core\Config\ConfigManagerInterface
*/
protected $configManager;
/**
* The file download controller.
*
* @var \Drupal\system\FileDownloadController
*/
protected $fileDownloadController;
/**
* The diff formatter.
*
* @var \Drupal\Core\Diff\DiffFormatter
*/
protected $diffFormatter;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('config.storage'),
$container->get('config.storage.sync'),
$container->get('config.manager'),
new FileDownloadController(),
$container->get('diff.formatter')
);
}
/**
* Constructs a ConfigController object.
*
* @param \Drupal\Core\Config\StorageInterface $target_storage
* The target storage.
* @param \Drupal\Core\Config\StorageInterface $source_storage
* The source storage
* @param \Drupal\system\FileDownloadController $file_download_controller
* The file download controller.
*/
public function __construct(StorageInterface $target_storage, StorageInterface $source_storage, ConfigManagerInterface $config_manager, FileDownloadController $file_download_controller, DiffFormatter $diff_formatter) {
$this->targetStorage = $target_storage;
$this->sourceStorage = $source_storage;
$this->configManager = $config_manager;
$this->fileDownloadController = $file_download_controller;
$this->diffFormatter = $diff_formatter;
}
/**
* Downloads a tarball of the site configuration.
*/
public function downloadExport() {
file_unmanaged_delete(file_directory_temp() . '/config.tar.gz');
$archiver = new ArchiveTar(file_directory_temp() . '/config.tar.gz', 'gz');
// Get raw configuration data without overrides.
foreach ($this->configManager->getConfigFactory()->listAll() as $name) {
$archiver->addString("$name.yml", Yaml::encode($this->configManager->getConfigFactory()->get($name)->getRawData()));
}
// Get all override data from the remaining collections.
foreach ($this->targetStorage->getAllCollectionNames() as $collection) {
$collection_storage = $this->targetStorage->createCollection($collection);
foreach ($collection_storage->listAll() as $name) {
$archiver->addString(str_replace('.', '/', $collection) . "/$name.yml", Yaml::encode($collection_storage->read($name)));
}
}
$request = new Request(['file' => 'config.tar.gz']);
return $this->fileDownloadController->download($request, 'temporary');
}
/**
* Shows diff of specified configuration file.
*
* @param string $source_name
* The name of the configuration file.
* @param string $target_name
* (optional) The name of the target configuration file if different from
* the $source_name.
* @param string $collection
* (optional) The configuration collection name. Defaults to the default
* collection.
*
* @return string
* Table showing a two-way diff between the active and staged configuration.
*/
public function diff($source_name, $target_name = NULL, $collection = NULL) {
if (!isset($collection)) {
$collection = StorageInterface::DEFAULT_COLLECTION;
}
$diff = $this->configManager->diff($this->targetStorage, $this->sourceStorage, $source_name, $target_name, $collection);
$this->diffFormatter->show_header = FALSE;
$build = [];
$build['#title'] = t('View changes of @config_file', ['@config_file' => $source_name]);
// Add the CSS for the inline diff.
$build['#attached']['library'][] = 'system/diff';
$build['diff'] = [
'#type' => 'table',
'#attributes' => [
'class' => ['diff'],
],
'#header' => [
['data' => t('Active'), 'colspan' => '2'],
['data' => t('Staged'), 'colspan' => '2'],
],
'#rows' => $this->diffFormatter->format($diff),
];
$build['back'] = [
'#type' => 'link',
'#attributes' => [
'class' => [
'dialog-cancel',
],
],
'#title' => "Back to 'Synchronize configuration' page.",
'#url' => Url::fromRoute('config.sync'),
];
return $build;
}
}

View file

@ -0,0 +1,40 @@
<?php
namespace Drupal\config\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Defines the configuration export form.
*
* @internal
*/
class ConfigExportForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'config_export_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Export'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$form_state->setRedirect('config.export_download');
}
}

View file

@ -0,0 +1,113 @@
<?php
namespace Drupal\config\Form;
use Drupal\Core\Archiver\ArchiveTar;
use Drupal\Core\Config\StorageInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Defines the configuration import form.
*
* @internal
*/
class ConfigImportForm extends FormBase {
/**
* The configuration storage.
*
* @var \Drupal\Core\Config\StorageInterface
*/
protected $configStorage;
/**
* Constructs a new ConfigImportForm.
*
* @param \Drupal\Core\Config\StorageInterface $config_storage
* The configuration storage.
*/
public function __construct(StorageInterface $config_storage) {
$this->configStorage = $config_storage;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('config.storage.sync')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'config_import_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$directory = config_get_config_directory(CONFIG_SYNC_DIRECTORY);
$directory_is_writable = is_writable($directory);
if (!$directory_is_writable) {
$this->messenger()->addError($this->t('The directory %directory is not writable.', ['%directory' => $directory]));
}
$form['import_tarball'] = [
'#type' => 'file',
'#title' => $this->t('Configuration archive'),
'#description' => $this->t('Allowed types: @extensions.', ['@extensions' => 'tar.gz tgz tar.bz2']),
];
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Upload'),
'#disabled' => !$directory_is_writable,
];
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$all_files = $this->getRequest()->files->get('files', []);
if (!empty($all_files['import_tarball'])) {
$file_upload = $all_files['import_tarball'];
if ($file_upload->isValid()) {
$form_state->setValue('import_tarball', $file_upload->getRealPath());
return;
}
}
$form_state->setErrorByName('import_tarball', $this->t('The file could not be uploaded.'));
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
if ($path = $form_state->getValue('import_tarball')) {
$this->configStorage->deleteAll();
try {
$archiver = new ArchiveTar($path, 'gz');
$files = [];
foreach ($archiver->listContent() as $file) {
$files[] = $file['filename'];
}
$archiver->extractList($files, config_get_config_directory(CONFIG_SYNC_DIRECTORY));
$this->messenger()->addStatus($this->t('Your configuration files were successfully uploaded and are ready for import.'));
$form_state->setRedirect('config.sync');
}
catch (\Exception $e) {
$this->messenger()->addError($this->t('Could not extract the contents of the tar file. The error message is <em>@message</em>', ['@message' => $e->getMessage()]));
}
drupal_unlink($path);
}
}
}

View file

@ -0,0 +1,207 @@
<?php
namespace Drupal\config\Form;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
use Drupal\Core\Config\StorageInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormState;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a form for exporting a single configuration file.
*
* @internal
*/
class ConfigSingleExportForm extends FormBase {
/**
* The entity manager.
*
* @var \Drupal\Core\Entity\EntityManagerInterface
*/
protected $entityManager;
/**
* The config storage.
*
* @var \Drupal\Core\Config\StorageInterface
*/
protected $configStorage;
/**
* Tracks the valid config entity type definitions.
*
* @var \Drupal\Core\Entity\EntityTypeInterface[]
*/
protected $definitions = [];
/**
* Constructs a new ConfigSingleImportForm.
*
* @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
* The entity manager.
* @param \Drupal\Core\Config\StorageInterface $config_storage
* The config storage.
*/
public function __construct(EntityManagerInterface $entity_manager, StorageInterface $config_storage) {
$this->entityManager = $entity_manager;
$this->configStorage = $config_storage;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity.manager'),
$container->get('config.storage')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'config_single_export_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, $config_type = NULL, $config_name = NULL) {
foreach ($this->entityManager->getDefinitions() as $entity_type => $definition) {
if ($definition->entityClassImplements(ConfigEntityInterface::class)) {
$this->definitions[$entity_type] = $definition;
}
}
$entity_types = array_map(function (EntityTypeInterface $definition) {
return $definition->getLabel();
}, $this->definitions);
// Sort the entity types by label, then add the simple config to the top.
uasort($entity_types, 'strnatcasecmp');
$config_types = [
'system.simple' => $this->t('Simple configuration'),
] + $entity_types;
$form['config_type'] = [
'#title' => $this->t('Configuration type'),
'#type' => 'select',
'#options' => $config_types,
'#default_value' => $config_type,
'#ajax' => [
'callback' => '::updateConfigurationType',
'wrapper' => 'edit-config-type-wrapper',
],
];
$default_type = $form_state->getValue('config_type', $config_type);
$form['config_name'] = [
'#title' => $this->t('Configuration name'),
'#type' => 'select',
'#options' => $this->findConfiguration($default_type),
'#default_value' => $config_name,
'#prefix' => '<div id="edit-config-type-wrapper">',
'#suffix' => '</div>',
'#ajax' => [
'callback' => '::updateExport',
'wrapper' => 'edit-export-wrapper',
],
];
$form['export'] = [
'#title' => $this->t('Here is your configuration:'),
'#type' => 'textarea',
'#rows' => 24,
'#prefix' => '<div id="edit-export-wrapper">',
'#suffix' => '</div>',
];
if ($config_type && $config_name) {
$fake_form_state = (new FormState())->setValues([
'config_type' => $config_type,
'config_name' => $config_name,
]);
$form['export'] = $this->updateExport($form, $fake_form_state);
}
return $form;
}
/**
* Handles switching the configuration type selector.
*/
public function updateConfigurationType($form, FormStateInterface $form_state) {
$form['config_name']['#options'] = $this->findConfiguration($form_state->getValue('config_type'));
return $form['config_name'];
}
/**
* Handles switching the export textarea.
*/
public function updateExport($form, FormStateInterface $form_state) {
// Determine the full config name for the selected config entity.
if ($form_state->getValue('config_type') !== 'system.simple') {
$definition = $this->entityManager->getDefinition($form_state->getValue('config_type'));
$name = $definition->getConfigPrefix() . '.' . $form_state->getValue('config_name');
}
// The config name is used directly for simple configuration.
else {
$name = $form_state->getValue('config_name');
}
// Read the raw data for this config name, encode it, and display it.
$form['export']['#value'] = Yaml::encode($this->configStorage->read($name));
$form['export']['#description'] = $this->t('Filename: %name', ['%name' => $name . '.yml']);
return $form['export'];
}
/**
* Handles switching the configuration type selector.
*/
protected function findConfiguration($config_type) {
$names = [
'' => $this->t('- Select -'),
];
// For a given entity type, load all entities.
if ($config_type && $config_type !== 'system.simple') {
$entity_storage = $this->entityManager->getStorage($config_type);
foreach ($entity_storage->loadMultiple() as $entity) {
$entity_id = $entity->id();
if ($label = $entity->label()) {
$names[$entity_id] = new TranslatableMarkup('@label (@id)', ['@label' => $label, '@id' => $entity_id]);
}
else {
$names[$entity_id] = $entity_id;
}
}
}
// Handle simple configuration.
else {
// Gather the config entity prefixes.
$config_prefixes = array_map(function (EntityTypeInterface $definition) {
return $definition->getConfigPrefix() . '.';
}, $this->definitions);
// Find all config, and then filter our anything matching a config prefix.
$names = $this->configStorage->listAll();
$names = array_combine($names, $names);
foreach ($names as $config_name) {
foreach ($config_prefixes as $config_prefix) {
if (strpos($config_name, $config_prefix) === 0) {
unset($names[$config_name]);
}
}
}
}
return $names;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Nothing to submit.
}
}

View file

@ -0,0 +1,427 @@
<?php
namespace Drupal\config\Form;
use Drupal\Component\Serialization\Exception\InvalidDataTypeException;
use Drupal\config\StorageReplaceDataWrapper;
use Drupal\Core\Config\ConfigImporter;
use Drupal\Core\Config\ConfigImporterException;
use Drupal\Core\Config\ConfigManagerInterface;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
use Drupal\Core\Config\StorageComparer;
use Drupal\Core\Config\StorageInterface;
use Drupal\Core\Config\TypedConfigManagerInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Extension\ModuleInstallerInterface;
use Drupal\Core\Extension\ThemeHandlerInterface;
use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Lock\LockBackendInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* Provides a form for importing a single configuration file.
*
* @internal
*/
class ConfigSingleImportForm extends ConfirmFormBase {
/**
* The entity manager.
*
* @var \Drupal\Core\Entity\EntityManagerInterface
*/
protected $entityManager;
/**
* The config storage.
*
* @var \Drupal\Core\Config\StorageInterface
*/
protected $configStorage;
/**
* The renderer service.
*
* @var \Drupal\Core\Render\RendererInterface
*/
protected $renderer;
/**
* The event dispatcher.
*
* @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
*/
protected $eventDispatcher;
/**
* The configuration manager.
*
* @var \Drupal\Core\Config\ConfigManagerInterface
*/
protected $configManager;
/**
* The database lock object.
*
* @var \Drupal\Core\Lock\LockBackendInterface
*/
protected $lock;
/**
* The typed config manager.
*
* @var \Drupal\Core\Config\TypedConfigManagerInterface
*/
protected $typedConfigManager;
/**
* The module handler.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* The theme handler.
*
* @var \Drupal\Core\Extension\ThemeHandlerInterface
*/
protected $themeHandler;
/**
* The module installer.
*
* @var \Drupal\Core\Extension\ModuleInstallerInterface
*/
protected $moduleInstaller;
/**
* If the config exists, this is that object. Otherwise, FALSE.
*
* @var \Drupal\Core\Config\Config|\Drupal\Core\Config\Entity\ConfigEntityInterface|bool
*/
protected $configExists = FALSE;
/**
* The submitted data needing to be confirmed.
*
* @var array
*/
protected $data = [];
/**
* Constructs a new ConfigSingleImportForm.
*
* @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
* The entity manager.
* @param \Drupal\Core\Config\StorageInterface $config_storage
* The config storage.
* @param \Drupal\Core\Render\RendererInterface $renderer
* The renderer service.
* @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
* The event dispatcher used to notify subscribers of config import events.
* @param \Drupal\Core\Config\ConfigManagerInterface $config_manager
* The configuration manager.
* @param \Drupal\Core\Lock\LockBackendInterface $lock
* The lock backend to ensure multiple imports do not occur at the same time.
* @param \Drupal\Core\Config\TypedConfigManagerInterface $typed_config
* The typed configuration manager.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
* @param \Drupal\Core\Extension\ModuleInstallerInterface $module_installer
* The module installer.
* @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler
* The theme handler.
*/
public function __construct(EntityManagerInterface $entity_manager, StorageInterface $config_storage, RendererInterface $renderer, EventDispatcherInterface $event_dispatcher, ConfigManagerInterface $config_manager, LockBackendInterface $lock, TypedConfigManagerInterface $typed_config, ModuleHandlerInterface $module_handler, ModuleInstallerInterface $module_installer, ThemeHandlerInterface $theme_handler) {
$this->entityManager = $entity_manager;
$this->configStorage = $config_storage;
$this->renderer = $renderer;
// Services necessary for \Drupal\Core\Config\ConfigImporter.
$this->eventDispatcher = $event_dispatcher;
$this->configManager = $config_manager;
$this->lock = $lock;
$this->typedConfigManager = $typed_config;
$this->moduleHandler = $module_handler;
$this->moduleInstaller = $module_installer;
$this->themeHandler = $theme_handler;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity.manager'),
$container->get('config.storage'),
$container->get('renderer'),
$container->get('event_dispatcher'),
$container->get('config.manager'),
$container->get('lock.persistent'),
$container->get('config.typed'),
$container->get('module_handler'),
$container->get('module_installer'),
$container->get('theme_handler')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'config_single_import_form';
}
/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return new Url('config.import_single');
}
/**
* {@inheritdoc}
*/
public function getQuestion() {
if ($this->data['config_type'] === 'system.simple') {
$name = $this->data['config_name'];
$type = $this->t('simple configuration');
}
else {
$definition = $this->entityManager->getDefinition($this->data['config_type']);
$name = $this->data['import'][$definition->getKey('id')];
$type = $definition->getLowercaseLabel();
}
$args = [
'%name' => $name,
'@type' => strtolower($type),
];
if ($this->configExists) {
$question = $this->t('Are you sure you want to update the %name @type?', $args);
}
else {
$question = $this->t('Are you sure you want to create a new %name @type?', $args);
}
return $question;
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
// When this is the confirmation step fall through to the confirmation form.
if ($this->data) {
return parent::buildForm($form, $form_state);
}
$entity_types = [];
foreach ($this->entityManager->getDefinitions() as $entity_type => $definition) {
if ($definition->entityClassImplements(ConfigEntityInterface::class)) {
$entity_types[$entity_type] = $definition->getLabel();
}
}
// Sort the entity types by label, then add the simple config to the top.
uasort($entity_types, 'strnatcasecmp');
$config_types = [
'system.simple' => $this->t('Simple configuration'),
] + $entity_types;
$form['config_type'] = [
'#title' => $this->t('Configuration type'),
'#type' => 'select',
'#options' => $config_types,
'#required' => TRUE,
];
$form['config_name'] = [
'#title' => $this->t('Configuration name'),
'#description' => $this->t('Enter the name of the configuration file without the <em>.yml</em> extension. (e.g. <em>system.site</em>)'),
'#type' => 'textfield',
'#states' => [
'required' => [
':input[name="config_type"]' => ['value' => 'system.simple'],
],
'visible' => [
':input[name="config_type"]' => ['value' => 'system.simple'],
],
],
];
$form['import'] = [
'#title' => $this->t('Paste your configuration here'),
'#type' => 'textarea',
'#rows' => 24,
'#required' => TRUE,
];
$form['advanced'] = [
'#type' => 'details',
'#title' => $this->t('Advanced'),
];
$form['advanced']['custom_entity_id'] = [
'#title' => $this->t('Custom Entity ID'),
'#type' => 'textfield',
'#description' => $this->t('Specify a custom entity ID. This will override the entity ID in the configuration above.'),
];
$form['actions'] = ['#type' => 'actions'];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Import'),
'#button_type' => 'primary',
];
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
// The confirmation step needs no additional validation.
if ($this->data) {
return;
}
try {
// Decode the submitted import.
$data = Yaml::decode($form_state->getValue('import'));
}
catch (InvalidDataTypeException $e) {
$form_state->setErrorByName('import', $this->t('The import failed with the following message: %message', ['%message' => $e->getMessage()]));
}
// Validate for config entities.
if ($form_state->getValue('config_type') !== 'system.simple') {
$definition = $this->entityManager->getDefinition($form_state->getValue('config_type'));
$id_key = $definition->getKey('id');
// If a custom entity ID is specified, override the value in the
// configuration data being imported.
if (!$form_state->isValueEmpty('custom_entity_id')) {
$data[$id_key] = $form_state->getValue('custom_entity_id');
}
$entity_storage = $this->entityManager->getStorage($form_state->getValue('config_type'));
// If an entity ID was not specified, set an error.
if (!isset($data[$id_key])) {
$form_state->setErrorByName('import', $this->t('Missing ID key "@id_key" for this @entity_type import.', ['@id_key' => $id_key, '@entity_type' => $definition->getLabel()]));
return;
}
$config_name = $definition->getConfigPrefix() . '.' . $data[$id_key];
// If there is an existing entity, ensure matching ID and UUID.
if ($entity = $entity_storage->load($data[$id_key])) {
$this->configExists = $entity;
if (!isset($data['uuid'])) {
$form_state->setErrorByName('import', $this->t('An entity with this machine name already exists but the import did not specify a UUID.'));
return;
}
if ($data['uuid'] !== $entity->uuid()) {
$form_state->setErrorByName('import', $this->t('An entity with this machine name already exists but the UUID does not match.'));
return;
}
}
// If there is no entity with a matching ID, check for a UUID match.
elseif (isset($data['uuid']) && $entity_storage->loadByProperties(['uuid' => $data['uuid']])) {
$form_state->setErrorByName('import', $this->t('An entity with this UUID already exists but the machine name does not match.'));
}
}
else {
$config_name = $form_state->getValue('config_name');
$config = $this->config($config_name);
$this->configExists = !$config->isNew() ? $config : FALSE;
}
// Use ConfigImporter validation.
if (!$form_state->getErrors()) {
$source_storage = new StorageReplaceDataWrapper($this->configStorage);
$source_storage->replaceData($config_name, $data);
$storage_comparer = new StorageComparer(
$source_storage,
$this->configStorage,
$this->configManager
);
if (!$storage_comparer->createChangelist()->hasChanges()) {
$form_state->setErrorByName('import', $this->t('There are no changes to import.'));
}
else {
$config_importer = new ConfigImporter(
$storage_comparer,
$this->eventDispatcher,
$this->configManager,
$this->lock,
$this->typedConfigManager,
$this->moduleHandler,
$this->moduleInstaller,
$this->themeHandler,
$this->getStringTranslation()
);
try {
$config_importer->validate();
$form_state->set('config_importer', $config_importer);
}
catch (ConfigImporterException $e) {
// There are validation errors.
$item_list = [
'#theme' => 'item_list',
'#items' => $config_importer->getErrors(),
'#title' => $this->t('The configuration cannot be imported because it failed validation for the following reasons:'),
];
$form_state->setErrorByName('import', $this->renderer->render($item_list));
}
}
}
// Store the decoded version of the submitted import.
$form_state->setValueForElement($form['import'], $data);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// If this form has not yet been confirmed, store the values and rebuild.
if (!$this->data) {
$form_state->setRebuild();
$this->data = $form_state->getValues();
return;
}
/** @var \Drupal\Core\Config\ConfigImporter $config_importer */
$config_importer = $form_state->get('config_importer');
if ($config_importer->alreadyImporting()) {
$this->messenger()->addError($this->t('Another request may be importing configuration already.'));
}
else {
try {
$sync_steps = $config_importer->initialize();
$batch = [
'operations' => [],
'finished' => [ConfigSync::class, 'finishBatch'],
'title' => $this->t('Importing configuration'),
'init_message' => $this->t('Starting configuration import.'),
'progress_message' => $this->t('Completed @current step of @total.'),
'error_message' => $this->t('Configuration import has encountered an error.'),
];
foreach ($sync_steps as $sync_step) {
$batch['operations'][] = [[ConfigSync::class, 'processBatch'], [$config_importer, $sync_step]];
}
batch_set($batch);
}
catch (ConfigImporterException $e) {
// There are validation errors.
$this->messenger()->addError($this->t('The configuration import failed for the following reasons:'));
foreach ($config_importer->getErrors() as $message) {
$this->messenger()->addError($message);
}
}
}
}
}

View file

@ -0,0 +1,399 @@
<?php
namespace Drupal\config\Form;
use Drupal\Core\Config\ConfigImporterException;
use Drupal\Core\Config\ConfigImporter;
use Drupal\Core\Config\Importer\ConfigImporterBatch;
use Drupal\Core\Config\TypedConfigManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Extension\ModuleInstallerInterface;
use Drupal\Core\Extension\ThemeHandlerInterface;
use Drupal\Core\Config\ConfigManagerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Config\StorageInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Lock\LockBackendInterface;
use Drupal\Core\Config\StorageComparer;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Url;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Construct the storage changes in a configuration synchronization form.
*
* @internal
*/
class ConfigSync extends FormBase {
/**
* The database lock object.
*
* @var \Drupal\Core\Lock\LockBackendInterface
*/
protected $lock;
/**
* The sync configuration object.
*
* @var \Drupal\Core\Config\StorageInterface
*/
protected $syncStorage;
/**
* The active configuration object.
*
* @var \Drupal\Core\Config\StorageInterface
*/
protected $activeStorage;
/**
* The snapshot configuration object.
*
* @var \Drupal\Core\Config\StorageInterface
*/
protected $snapshotStorage;
/**
* Event dispatcher.
*
* @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
*/
protected $eventDispatcher;
/**
* The configuration manager.
*
* @var \Drupal\Core\Config\ConfigManagerInterface
*/
protected $configManager;
/**
* The typed config manager.
*
* @var \Drupal\Core\Config\TypedConfigManagerInterface
*/
protected $typedConfigManager;
/**
* The module handler.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* The theme handler.
*
* @var \Drupal\Core\Extension\ThemeHandlerInterface
*/
protected $themeHandler;
/**
* The module installer.
*
* @var \Drupal\Core\Extension\ModuleInstallerInterface
*/
protected $moduleInstaller;
/**
* The renderer.
*
* @var \Drupal\Core\Render\RendererInterface
*/
protected $renderer;
/**
* Constructs the object.
*
* @param \Drupal\Core\Config\StorageInterface $sync_storage
* The source storage.
* @param \Drupal\Core\Config\StorageInterface $active_storage
* The target storage.
* @param \Drupal\Core\Config\StorageInterface $snapshot_storage
* The snapshot storage.
* @param \Drupal\Core\Lock\LockBackendInterface $lock
* The lock object.
* @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
* Event dispatcher.
* @param \Drupal\Core\Config\ConfigManagerInterface $config_manager
* Configuration manager.
* @param \Drupal\Core\Config\TypedConfigManagerInterface $typed_config
* The typed configuration manager.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
* @param \Drupal\Core\Extension\ModuleInstallerInterface $module_installer
* The module installer.
* @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler
* The theme handler.
* @param \Drupal\Core\Render\RendererInterface $renderer
* The renderer.
*/
public function __construct(StorageInterface $sync_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) {
$this->syncStorage = $sync_storage;
$this->activeStorage = $active_storage;
$this->snapshotStorage = $snapshot_storage;
$this->lock = $lock;
$this->eventDispatcher = $event_dispatcher;
$this->configManager = $config_manager;
$this->typedConfigManager = $typed_config;
$this->moduleHandler = $module_handler;
$this->moduleInstaller = $module_installer;
$this->themeHandler = $theme_handler;
$this->renderer = $renderer;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('config.storage.sync'),
$container->get('config.storage'),
$container->get('config.storage.snapshot'),
$container->get('lock.persistent'),
$container->get('event_dispatcher'),
$container->get('config.manager'),
$container->get('config.typed'),
$container->get('module_handler'),
$container->get('module_installer'),
$container->get('theme_handler'),
$container->get('renderer')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'config_admin_import_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['actions'] = ['#type' => 'actions'];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Import all'),
];
$source_list = $this->syncStorage->listAll();
$storage_comparer = new StorageComparer($this->syncStorage, $this->activeStorage, $this->configManager);
if (empty($source_list) || !$storage_comparer->createChangelist()->hasChanges()) {
$form['no_changes'] = [
'#type' => 'table',
'#header' => [$this->t('Name'), $this->t('Operations')],
'#rows' => [],
'#empty' => $this->t('There are no configuration changes to import.'),
];
$form['actions']['#access'] = FALSE;
return $form;
}
elseif (!$storage_comparer->validateSiteUuid()) {
$this->messenger()->addError($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.'));
$form['actions']['#access'] = FALSE;
return $form;
}
// 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 = [];
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);
$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,
],
];
$this->messenger()->addWarning($this->renderer->renderPlain($message));
}
}
// Store the comparer for use in the submit.
$form_state->set('storage_comparer', $storage_comparer);
// Add the AJAX library to the form for dialog support.
$form['#attached']['library'][] = 'core/drupal.dialog.ajax';
foreach ($storage_comparer->getAllCollectionNames() as $collection) {
if ($collection != StorageInterface::DEFAULT_COLLECTION) {
$form[$collection]['collection_heading'] = [
'#type' => 'html_tag',
'#tag' => 'h2',
'#value' => $this->t('@collection configuration collection', ['@collection' => $collection]),
];
}
foreach ($storage_comparer->getChangelist(NULL, $collection) as $config_change_type => $config_names) {
if (empty($config_names)) {
continue;
}
// @todo A table caption would be more appropriate, but does not have the
// visual importance of a heading.
$form[$collection][$config_change_type]['heading'] = [
'#type' => 'html_tag',
'#tag' => 'h3',
];
switch ($config_change_type) {
case 'create':
$form[$collection][$config_change_type]['heading']['#value'] = $this->formatPlural(count($config_names), '@count new', '@count new');
break;
case 'update':
$form[$collection][$config_change_type]['heading']['#value'] = $this->formatPlural(count($config_names), '@count changed', '@count changed');
break;
case 'delete':
$form[$collection][$config_change_type]['heading']['#value'] = $this->formatPlural(count($config_names), '@count removed', '@count removed');
break;
case 'rename':
$form[$collection][$config_change_type]['heading']['#value'] = $this->formatPlural(count($config_names), '@count renamed', '@count renamed');
break;
}
$form[$collection][$config_change_type]['list'] = [
'#type' => 'table',
'#header' => [$this->t('Name'), $this->t('Operations')],
];
foreach ($config_names as $config_name) {
if ($config_change_type == 'rename') {
$names = $storage_comparer->extractRenameNames($config_name);
$route_options = ['source_name' => $names['old_name'], 'target_name' => $names['new_name']];
$config_name = $this->t('@source_name to @target_name', ['@source_name' => $names['old_name'], '@target_name' => $names['new_name']]);
}
else {
$route_options = ['source_name' => $config_name];
}
if ($collection != StorageInterface::DEFAULT_COLLECTION) {
$route_name = 'config.diff_collection';
$route_options['collection'] = $collection;
}
else {
$route_name = 'config.diff';
}
$links['view_diff'] = [
'title' => $this->t('View differences'),
'url' => Url::fromRoute($route_name, $route_options),
'attributes' => [
'class' => ['use-ajax'],
'data-dialog-type' => 'modal',
'data-dialog-options' => json_encode([
'width' => 700,
]),
],
];
$form[$collection][$config_change_type]['list']['#rows'][] = [
'name' => $config_name,
'operations' => [
'data' => [
'#type' => 'operations',
'#links' => $links,
],
],
];
}
}
}
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$config_importer = new ConfigImporter(
$form_state->get('storage_comparer'),
$this->eventDispatcher,
$this->configManager,
$this->lock,
$this->typedConfigManager,
$this->moduleHandler,
$this->moduleInstaller,
$this->themeHandler,
$this->getStringTranslation()
);
if ($config_importer->alreadyImporting()) {
$this->messenger()->addStatus($this->t('Another request may be synchronizing configuration already.'));
}
else {
try {
$sync_steps = $config_importer->initialize();
$batch = [
'operations' => [],
'finished' => [ConfigImporterBatch::class, 'finish'],
'title' => t('Synchronizing configuration'),
'init_message' => t('Starting configuration synchronization.'),
'progress_message' => t('Completed step @current of @total.'),
'error_message' => t('Configuration synchronization has encountered an error.'),
];
foreach ($sync_steps as $sync_step) {
$batch['operations'][] = [[ConfigImporterBatch::class, 'process'], [$config_importer, $sync_step]];
}
batch_set($batch);
}
catch (ConfigImporterException $e) {
// There are validation errors.
$this->messenger()->addError($this->t('The configuration cannot be imported because it failed validation for the following reasons:'));
foreach ($config_importer->getErrors() as $message) {
$this->messenger()->addError($message);
}
}
}
}
/**
* Processes the config import batch and persists the importer.
*
* @param \Drupal\Core\Config\ConfigImporter $config_importer
* The batch config importer object to persist.
* @param string $sync_step
* The synchronization step to do.
* @param array $context
* The batch context.
*
* @deprecated in Drupal 8.6.0 and will be removed before 9.0.0. Use
* \Drupal\Core\Config\Importer\ConfigImporterBatch::process() instead.
*
* @see https://www.drupal.org/node/2897299
*/
public static function processBatch(ConfigImporter $config_importer, $sync_step, &$context) {
@trigger_error('\Drupal\config\Form\ConfigSync::processBatch() deprecated in Drupal 8.6.0 and will be removed before 9.0.0. Use \Drupal\Core\Config\Importer\ConfigImporterBatch::process() instead. See https://www.drupal.org/node/2897299');
ConfigImporterBatch::process($config_importer, $sync_step, $context);
}
/**
* Finish batch.
*
* This function is a static function to avoid serializing the ConfigSync
* object unnecessarily.
*
* @deprecated in Drupal 8.6.0 and will be removed before 9.0.0. Use
* \Drupal\Core\Config\Importer\ConfigImporterBatch::finish() instead.
*
* @see https://www.drupal.org/node/2897299
*/
public static function finishBatch($success, $results, $operations) {
@trigger_error('\Drupal\config\Form\ConfigSync::finishBatch() deprecated in Drupal 8.6.0 and will be removed before 9.0.0. Use \Drupal\Core\Config\Importer\ConfigImporterBatch::finish() instead. See https://www.drupal.org/node/2897299');
ConfigImporterBatch::finish($success, $results, $operations);
}
}

View file

@ -0,0 +1,203 @@
<?php
namespace Drupal\config;
use Drupal\Core\Config\StorageInterface;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
/**
* Wraps a configuration storage to allow replacing specific configuration data.
*/
class StorageReplaceDataWrapper implements StorageInterface {
use DependencySerializationTrait;
/**
* The configuration storage to be wrapped.
*
* @var \Drupal\Core\Config\StorageInterface
*/
protected $storage;
/**
* The configuration replacement data, keyed by configuration object name.
*
* @var array
*/
protected $replacementData = [];
/**
* The storage collection.
*
* @var string
*/
protected $collection;
/**
* Constructs a new StorageReplaceDataWrapper.
*
* @param \Drupal\Core\Config\StorageInterface $storage
* A configuration storage to be used to read and write configuration.
* @param string $collection
* (optional) The collection to store configuration in. Defaults to the
* default collection.
*/
public function __construct(StorageInterface $storage, $collection = StorageInterface::DEFAULT_COLLECTION) {
$this->storage = $storage;
$this->collection = $collection;
$this->replacementData[$collection] = [];
}
/**
* {@inheritdoc}
*/
public function exists($name) {
return isset($this->replacementData[$this->collection][$name]) || $this->storage->exists($name);
}
/**
* {@inheritdoc}
*/
public function read($name) {
if (isset($this->replacementData[$this->collection][$name])) {
return $this->replacementData[$this->collection][$name];
}
return $this->storage->read($name);
}
/**
* {@inheritdoc}
*/
public function readMultiple(array $names) {
$data = $this->storage->readMultiple(($names));
foreach ($names as $name) {
if (isset($this->replacementData[$this->collection][$name])) {
$data[$name] = $this->replacementData[$this->collection][$name];
}
}
return $data;
}
/**
* {@inheritdoc}
*/
public function write($name, array $data) {
if (isset($this->replacementData[$this->collection][$name])) {
unset($this->replacementData[$this->collection][$name]);
}
return $this->storage->write($name, $data);
}
/**
* {@inheritdoc}
*/
public function delete($name) {
if (isset($this->replacementData[$this->collection][$name])) {
unset($this->replacementData[$this->collection][$name]);
}
return $this->storage->delete($name);
}
/**
* {@inheritdoc}
*/
public function rename($name, $new_name) {
if (isset($this->replacementData[$this->collection][$name])) {
$this->replacementData[$this->collection][$new_name] = $this->replacementData[$this->collection][$name];
unset($this->replacementData[$this->collection][$name]);
}
return $this->storage->rename($name, $new_name);
}
/**
* {@inheritdoc}
*/
public function encode($data) {
return $this->storage->encode($data);
}
/**
* {@inheritdoc}
*/
public function decode($raw) {
return $this->storage->decode($raw);
}
/**
* {@inheritdoc}
*/
public function listAll($prefix = '') {
$names = $this->storage->listAll($prefix);
$additional_names = [];
if ($prefix === '') {
$additional_names = array_keys($this->replacementData[$this->collection]);
}
else {
foreach (array_keys($this->replacementData[$this->collection]) as $name) {
if (strpos($name, $prefix) === 0) {
$additional_names[] = $name;
}
}
}
if (!empty($additional_names)) {
$names = array_unique(array_merge($names, $additional_names));
}
return $names;
}
/**
* {@inheritdoc}
*/
public function deleteAll($prefix = '') {
if ($prefix === '') {
$this->replacementData[$this->collection] = [];
}
else {
foreach (array_keys($this->replacementData[$this->collection]) as $name) {
if (strpos($name, $prefix) === 0) {
unset($this->replacementData[$this->collection][$name]);
}
}
}
return $this->storage->deleteAll($prefix);
}
/**
* {@inheritdoc}
*/
public function createCollection($collection) {
return new static(
$this->storage->createCollection($collection),
$collection
);
}
/**
* {@inheritdoc}
*/
public function getAllCollectionNames() {
return $this->storage->getAllCollectionNames();
}
/**
* {@inheritdoc}
*/
public function getCollectionName() {
return $this->collection;
}
/**
* Replaces the configuration object data with the supplied data.
*
* @param $name
* The configuration object name whose data to replace.
* @param array $data
* The configuration data.
*
* @return $this
*/
public function replaceData($name, array $data) {
$this->replacementData[$this->collection][$name] = $data;
return $this;
}
}

View file

@ -0,0 +1,44 @@
<?php
namespace Drupal\config\Tests;
@trigger_error('The ' . __NAMESPACE__ . '\AssertConfigEntityImportTrait is deprecated in Drupal 8.4.1 and will be removed before Drupal 9.0.0. Instead, use \Drupal\Tests\config\Traits\AssertConfigEntityImportTrait. See https://www.drupal.org/node/2916197.', E_USER_DEPRECATED);
use Drupal\Core\Config\Entity\ConfigEntityInterface;
/**
* Provides test assertions for testing config entity synchronization.
*
* Can be used by test classes that extend \Drupal\simpletest\WebTestBase or
* \Drupal\KernelTests\KernelTestBase.
*
* @deprecated in Drupal 8.4.1 and will be removed before Drupal 9.0.0.
* Use \Drupal\Tests\config\Traits\AssertConfigEntityImportTrait.
*
* @see https://www.drupal.org/node/2916197
*/
trait AssertConfigEntityImportTrait {
/**
* Asserts that a config entity can be imported without changing it.
*
* @param \Drupal\Core\Config\Entity\ConfigEntityInterface $entity
* The config entity to test importing.
*/
public function assertConfigEntityImport(ConfigEntityInterface $entity) {
// Save original config information.
$entity_uuid = $entity->uuid();
$entity_type_id = $entity->getEntityTypeId();
$original_data = $entity->toArray();
// Copy everything to sync.
$this->copyConfig(\Drupal::service('config.storage'), \Drupal::service('config.storage.sync'));
// Delete the configuration from active. Don't worry about side effects of
// deleting config like fields cleaning up field storages. The coming import
// should recreate everything as necessary.
$entity->delete();
$this->configImporter()->reset()->import();
$imported_entity = \Drupal::entityManager()->loadEntityByUuid($entity_type_id, $entity_uuid);
$this->assertIdentical($original_data, $imported_entity->toArray());
}
}

View file

@ -0,0 +1,14 @@
<?php
namespace Drupal\config\Tests;
/**
* Provides a class for checking configuration schema.
*
* @deprecated as of 8.3.x, will be removed in before Drupal 9.0.0.
*/
trait SchemaCheckTestTrait {
use \Drupal\Tests\SchemaCheckTestTrait;
}