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.
14 class ConfigImportForm extends FormBase {
17 * The configuration storage.
19 * @var \Drupal\Core\Config\StorageInterface
21 protected $configStorage;
24 * Constructs a new ConfigImportForm.
26 * @param \Drupal\Core\Config\StorageInterface $config_storage
27 * The configuration storage.
29 public function __construct(StorageInterface $config_storage) {
30 $this->configStorage = $config_storage;
36 public static function create(ContainerInterface $container) {
38 $container->get('config.storage.sync')
45 public function getFormId() {
46 return 'config_import_form';
52 public function buildForm(array $form, FormStateInterface $form_state) {
53 $directory = config_get_config_directory(CONFIG_SYNC_DIRECTORY);
54 $directory_is_writable = is_writable($directory);
55 if (!$directory_is_writable) {
56 drupal_set_message($this->t('The directory %directory is not writable.', ['%directory' => $directory]), 'error');
58 $form['import_tarball'] = [
60 '#title' => $this->t('Configuration archive'),
61 '#description' => $this->t('Allowed types: @extensions.', ['@extensions' => 'tar.gz tgz tar.bz2']),
66 '#value' => $this->t('Upload'),
67 '#disabled' => !$directory_is_writable,
75 public function validateForm(array &$form, FormStateInterface $form_state) {
76 $all_files = $this->getRequest()->files->get('files', []);
77 if (!empty($all_files['import_tarball'])) {
78 $file_upload = $all_files['import_tarball'];
79 if ($file_upload->isValid()) {
80 $form_state->setValue('import_tarball', $file_upload->getRealPath());
85 $form_state->setErrorByName('import_tarball', $this->t('The file could not be uploaded.'));
91 public function submitForm(array &$form, FormStateInterface $form_state) {
92 if ($path = $form_state->getValue('import_tarball')) {
93 $this->configStorage->deleteAll();
95 $archiver = new ArchiveTar($path, 'gz');
97 foreach ($archiver->listContent() as $file) {
98 $files[] = $file['filename'];
100 $archiver->extractList($files, config_get_config_directory(CONFIG_SYNC_DIRECTORY));
101 drupal_set_message($this->t('Your configuration files were successfully uploaded and are ready for import.'));
102 $form_state->setRedirect('config.sync');
104 catch (\Exception $e) {
105 drupal_set_message($this->t('Could not extract the contents of the tar file. The error message is <em>@message</em>', ['@message' => $e->getMessage()]), 'error');
107 drupal_unlink($path);