You are here

class ThemeExperimentalConfirmForm in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/system/src/Form/ThemeExperimentalConfirmForm.php \Drupal\system\Form\ThemeExperimentalConfirmForm

Builds a confirmation form for enabling experimental themes.

@internal

Hierarchy

Expanded class hierarchy of ThemeExperimentalConfirmForm

1 file declares its use of ThemeExperimentalConfirmForm
ThemeController.php in core/modules/system/src/Controller/ThemeController.php

File

core/modules/system/src/Form/ThemeExperimentalConfirmForm.php, line 19

Namespace

Drupal\system\Form
View source
class ThemeExperimentalConfirmForm extends ConfirmFormBase {

  /**
   * An extension discovery instance.
   *
   * @var \Drupal\Core\Extension\ThemeExtensionList
   */
  protected $themeList;

  /**
   * The theme installer service.
   *
   * @var \Drupal\Core\Extension\ThemeInstallerInterface
   */
  protected $themeInstaller;

  /**
   * Constructs a ThemeExperimentalConfirmForm object.
   *
   * @param \Drupal\Core\Extension\ThemeExtensionList $theme_list
   *   The theme extension list.
   * @param \Drupal\Core\Extension\ThemeInstallerInterface $theme_installer
   *   The theme installer.
   */
  public function __construct(ThemeExtensionList $theme_list, ThemeInstallerInterface $theme_installer) {
    $this->themeList = $theme_list;
    $this->themeInstaller = $theme_installer;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('extension.list.theme'), $container
      ->get('theme_installer'));
  }

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    return $this
      ->t('Are you sure you wish to install an experimental theme?');
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    return new Url('system.themes_page');
  }

  /**
   * {@inheritdoc}
   */
  public function getConfirmText() {
    return $this
      ->t('Continue');
  }

  /**
   * {@inheritdoc}
   */
  public function getDescription() {
    return $this
      ->t('Would you like to continue with the above?');
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $theme = $form_state
      ->getBuildInfo()['args'][0] ? $form_state
      ->getBuildInfo()['args'][0] : NULL;
    $all_themes = $this->themeList
      ->getList();
    if (!isset($all_themes[$theme])) {
      return $this
        ->redirect('system.themes_page');
    }
    $this
      ->messenger()
      ->addWarning($this
      ->t('Experimental themes are provided for testing purposes only. Use at your own risk.'));
    $dependencies = array_keys($all_themes[$theme]->requires);
    $themes = array_merge([
      $theme,
    ], $dependencies);
    $is_experimental = function ($theme) use ($all_themes) {
      return isset($all_themes[$theme]) && isset($all_themes[$theme]->info['experimental']) && $all_themes[$theme]->info['experimental'];
    };
    $get_label = function ($theme) use ($all_themes) {
      return $all_themes[$theme]->info['name'];
    };
    $items = [];
    if (!empty($dependencies)) {

      // Display a list of required themes that have to be installed as well.
      $items[] = $this
        ->formatPlural(count($dependencies), 'You must enable the @required theme to install @theme.', 'You must enable the @required themes to install @theme.', [
        '@theme' => $get_label($theme),
        // It is safe to implode this because theme names are not translated
        // markup and so will not be double-escaped.
        '@required' => implode(', ', array_map($get_label, $dependencies)),
      ]);
    }

    // Add the list of experimental themes after any other messages.
    $items[] = $this
      ->t('The following themes are experimental: @themes', [
      '@themes' => implode(', ', array_map($get_label, array_filter($themes, $is_experimental))),
    ]);
    $form['message'] = [
      '#theme' => 'item_list',
      '#items' => $items,
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $args = $form_state
      ->getBuildInfo()['args'];
    $theme = isset($args[0]) ? $args[0] : NULL;
    $set_default = isset($args[1]) ? $args[1] : FALSE;
    $themes = $this->themeList
      ->getList();
    $config = $this
      ->configFactory()
      ->getEditable('system.theme');
    try {
      if ($this->themeInstaller
        ->install([
        $theme,
      ])) {
        if ($set_default) {

          // Set the default theme.
          $config
            ->set('default', $theme)
            ->save();

          // The status message depends on whether an admin theme is currently
          // in use: an empty string means the admin theme is set to be the
          // default theme.
          $admin_theme = $config
            ->get('admin');
          if (!empty($admin_theme) && $admin_theme !== $theme) {
            $this
              ->messenger()
              ->addStatus($this
              ->t('Please note that the administration theme is still set to the %admin_theme theme; consequently, the theme on this page remains unchanged. All non-administrative sections of the site, however, will show the selected %selected_theme theme by default.', [
              '%admin_theme' => $themes[$admin_theme]->info['name'],
              '%selected_theme' => $themes[$theme]->info['name'],
            ]));
          }
          else {
            $this
              ->messenger()
              ->addStatus($this
              ->t('%theme is now the default theme.', [
              '%theme' => $themes[$theme]->info['name'],
            ]));
          }
        }
        else {
          $this
            ->messenger()
            ->addStatus($this
            ->t('The %theme theme has been installed.', [
            '%theme' => $themes[$theme]->info['name'],
          ]));
        }
      }
      else {
        $this
          ->messenger()
          ->addError($this
          ->t('The %theme theme was not found.', [
          '%theme' => $theme,
        ]));
      }
    } catch (PreExistingConfigException $e) {
      $config_objects = $e
        ->flattenConfigObjects($e
        ->getConfigObjects());
      $this
        ->messenger()
        ->addError($this
        ->formatPlural(count($config_objects), 'Unable to install @extension, %config_names already exists in active configuration.', 'Unable to install @extension, %config_names already exist in active configuration.', [
        '%config_names' => implode(', ', $config_objects),
        '@extension' => $theme,
      ]));
    } catch (UnmetDependenciesException $e) {
      $this
        ->messenger()
        ->addError($e
        ->getTranslatedMessage($this
        ->getStringTranslation(), $theme));
    }
    $form_state
      ->setRedirectUrl($this
      ->getCancelUrl());
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfirmFormBase::getCancelText public function Returns a caption for the link which cancels the action. Overrides ConfirmFormInterface::getCancelText 1
ConfirmFormBase::getFormName public function Returns the internal name used to refer to the confirmation item. Overrides ConfirmFormInterface::getFormName
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.
ThemeExperimentalConfirmForm::$themeInstaller protected property The theme installer service.
ThemeExperimentalConfirmForm::$themeList protected property An extension discovery instance.
ThemeExperimentalConfirmForm::buildForm public function Form constructor. Overrides ConfirmFormBase::buildForm
ThemeExperimentalConfirmForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
ThemeExperimentalConfirmForm::getCancelUrl public function Returns the route to go to if the user cancels the action. Overrides ConfirmFormInterface::getCancelUrl
ThemeExperimentalConfirmForm::getConfirmText public function Returns a caption for the button that confirms the action. Overrides ConfirmFormBase::getConfirmText
ThemeExperimentalConfirmForm::getDescription public function Returns additional text to display as a description. Overrides ConfirmFormBase::getDescription
ThemeExperimentalConfirmForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ThemeExperimentalConfirmForm::getQuestion public function Returns the question to ask the user. Overrides ConfirmFormInterface::getQuestion
ThemeExperimentalConfirmForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
ThemeExperimentalConfirmForm::__construct public function Constructs a ThemeExperimentalConfirmForm 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.