You are here

class UpdateConfigurationForm in Config Direct Save 8

Same name and namespace in other branches
  1. 8.2 src/Form/UpdateConfigurationForm.php \Drupal\config_direct_save\Form\UpdateConfigurationForm

Provide the settings form for updating configurations.

@package Drupal\config_direct_save\Form

Hierarchy

Expanded class hierarchy of UpdateConfigurationForm

1 string reference to 'UpdateConfigurationForm'
config_direct_save.routing.yml in ./config_direct_save.routing.yml
config_direct_save.routing.yml

File

src/Form/UpdateConfigurationForm.php, line 18

Namespace

Drupal\config_direct_save\Form
View source
class UpdateConfigurationForm extends FormBase {

  /**
   * The target storage.
   *
   * @var \Drupal\Core\Config\StorageInterface
   */
  protected $targetStorage;

  /**
   * The source storage.
   *
   * @var \Drupal\Core\Config\StorageInterface
   */

  /**
   * The configuration manager.
   *
   * @var \Drupal\Core\Config\ConfigManagerInterface
   */
  protected $configManager;

  /**
   * Constructs a ConfigController object.
   *
   * @param \Drupal\Core\Config\StorageInterface $target_storage
   *   The target storage.
   * @param \Drupal\Core\Config\ConfigManagerInterface $config_manager
   *   Gets the config factory.
   */
  public function __construct(StorageInterface $target_storage, ConfigManagerInterface $config_manager) {
    $this->targetStorage = $target_storage;
    $this->configManager = $config_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.storage'), $container
      ->get('config.manager'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'config_update_form';
  }

  /**
   * Form constructor.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array
   *   The form structure.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['config_directory'] = [
      '#type' => 'select',
      '#required' => TRUE,
      '#title' => $this
        ->t('Config source'),
      '#description' => $this
        ->t('Select config source directory'),
      '#options' => array_flip([
        'sync' => Settings::get('config_sync_directory'),
      ]),
    ];
    $form['backup'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Backup'),
      '#description' => $this
        ->t('Check to make a backup for a specific config source(sync for example.)'),
    ];
    $form['update'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Update configuration'),
    ];
    return $form;
  }

  /**
   * Form submission handler.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Create config files.
    $this
      ->createConfigFiles($form, $form_state);
  }

  /**
   * Override the old configurations.
   */
  public function createConfigFiles(array &$form, FormStateInterface $form_state) {

    // Get the name of config source( sync, text, etc...).
    $config_directory_selected = $form_state
      ->getValue('config_directory');
    $config_files_names = $this->configManager
      ->getConfigFactory()
      ->listAll();

    // If the user check to make a backup, a directory will be created.
    if ($form_state
      ->getValue('backup')) {
      $current_date = date('d-m-Y-H-i-s');
      $folder_backup = $config_directory_selected . "-" . $current_date;
      $this
        ->recurseCopy($config_directory_selected, $folder_backup);
    }

    // Delete old configurations files( except .htaccess).
    $this
      ->unlinkRecursive($config_directory_selected, 'yml');
    foreach ($config_files_names as $name) {

      // Data associated to file.
      $data = Yaml::encode($this->configManager
        ->getConfigFactory()
        ->get($name)
        ->getRawData());

      // Create new files.
      file_put_contents($config_directory_selected . "/{$name}.yml", $data);
    }

    // Get all override data from the remaining collections.
    foreach ($this->targetStorage
      ->getAllCollectionNames() as $collection) {
      $target = str_replace('.', '/', $collection);
      $this
        ->unlinkRecursive($config_directory_selected . "/" . $target . "/", 'yml');
      if (!is_dir($config_directory_selected . "/" . $target . "/")) {
        mkdir($config_directory_selected . "/" . $target . "/", 0775, TRUE);
      }
      $collection_storage = $this->targetStorage
        ->createCollection($collection);
      foreach ($collection_storage
        ->listAll() as $name) {
        $target = str_replace('.', '/', $collection);
        file_put_contents($config_directory_selected . "/" . $target . "/{$name}.yml", Yaml::encode($collection_storage
          ->read($name)));
      }
    }
    $this
      ->messenger()
      ->addMessage($this
      ->t("The configuration has been uploaded."));
  }

  /**
   * Copy the directory of.
   */
  public function recurseCopy($src, $dst) {
    $dir = opendir($src);
    @mkdir($dst);
    while (FALSE !== ($file = readdir($dir))) {
      if ($file != '.' && $file != '..') {
        if (is_dir($src . '/' . $file)) {
          $this
            ->recurseCopy($src . '/' . $file, $dst . '/' . $file);
        }
        else {
          copy($src . '/' . $file, $dst . '/' . $file);
        }
      }
    }
    closedir($dir);
  }

  /**
   * Delete all configurations.
   */
  public function unlinkRecursive($dir_name, $ext) {

    // Exit if there's no such directory.
    if (!file_exists($dir_name)) {
      return FALSE;
    }

    // Open the target directory.
    $dir_handle = dir($dir_name);

    // Take entries in the directory one at a time.
    while (FALSE !== ($entry = $dir_handle
      ->read())) {
      if ($entry == '.' || $entry == '..') {
        continue;
      }
      $abs_name = "{$dir_name}/{$entry}";
      if (is_file($abs_name) && preg_match("/^.+\\.{$ext}\$/", $entry)) {
        if (unlink($abs_name)) {
          continue;
        }
        return FALSE;
      }

      // Recurse on the children if the current entry
      // happens to be a "directory".
      if (is_dir($abs_name) || is_link($abs_name)) {
        $this
          ->unlinkRecursive($abs_name, $ext);
      }
    }
    $dir_handle
      ->close();
    return TRUE;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UpdateConfigurationForm::$configManager protected property The configuration manager.
UpdateConfigurationForm::$targetStorage protected property The target storage.
UpdateConfigurationForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
UpdateConfigurationForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
UpdateConfigurationForm::createConfigFiles public function Override the old configurations.
UpdateConfigurationForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
UpdateConfigurationForm::recurseCopy public function Copy the directory of.
UpdateConfigurationForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
UpdateConfigurationForm::unlinkRecursive public function Delete all configurations.
UpdateConfigurationForm::__construct public function Constructs a ConfigController object.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.