3 namespace Drupal\config\Form;
5 use Drupal\Core\Archiver\ArchiveTar;
6 use Drupal\Core\Config\StorageInterface;
7 use Drupal\Core\Form\FormBase;
8 use Drupal\Core\Form\FormStateInterface;
9 use Symfony\Component\DependencyInjection\ContainerInterface;
12 * Defines the configuration import form.
16 class ConfigImportForm extends FormBase {
19 * The configuration storage.
21 * @var \Drupal\Core\Config\StorageInterface
23 protected $configStorage;
26 * Constructs a new ConfigImportForm.
28 * @param \Drupal\Core\Config\StorageInterface $config_storage
29 * The configuration storage.
31 public function __construct(StorageInterface $config_storage) {
32 $this->configStorage = $config_storage;
38 public static function create(ContainerInterface $container) {
40 $container->get('config.storage.sync')
47 public function getFormId() {
48 return 'config_import_form';
54 public function buildForm(array $form, FormStateInterface $form_state) {
55 $directory = config_get_config_directory(CONFIG_SYNC_DIRECTORY);
56 $directory_is_writable = is_writable($directory);
57 if (!$directory_is_writable) {
58 $this->messenger()->addError($this->t('The directory %directory is not writable.', ['%directory' => $directory]));
60 $form['import_tarball'] = [
62 '#title' => $this->t('Configuration archive'),
63 '#description' => $this->t('Allowed types: @extensions.', ['@extensions' => 'tar.gz tgz tar.bz2']),
68 '#value' => $this->t('Upload'),
69 '#disabled' => !$directory_is_writable,
77 public function validateForm(array &$form, FormStateInterface $form_state) {
78 $all_files = $this->getRequest()->files->get('files', []);
79 if (!empty($all_files['import_tarball'])) {
80 $file_upload = $all_files['import_tarball'];
81 if ($file_upload->isValid()) {
82 $form_state->setValue('import_tarball', $file_upload->getRealPath());
87 $form_state->setErrorByName('import_tarball', $this->t('The file could not be uploaded.'));
93 public function submitForm(array &$form, FormStateInterface $form_state) {
94 if ($path = $form_state->getValue('import_tarball')) {
95 $this->configStorage->deleteAll();
97 $archiver = new ArchiveTar($path, 'gz');
99 foreach ($archiver->listContent() as $file) {
100 $files[] = $file['filename'];
102 $archiver->extractList($files, config_get_config_directory(CONFIG_SYNC_DIRECTORY));
103 $this->messenger()->addStatus($this->t('Your configuration files were successfully uploaded and are ready for import.'));
104 $form_state->setRedirect('config.sync');
106 catch (\Exception $e) {
107 $this->messenger()->addError($this->t('Could not extract the contents of the tar file. The error message is <em>@message</em>', ['@message' => $e->getMessage()]));
109 drupal_unlink($path);