You are here

class StyleswitcherConfigTheme in Style Switcher 3.0.x

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

Configure theme-specific styles settings.

Hierarchy

Expanded class hierarchy of StyleswitcherConfigTheme

1 string reference to 'StyleswitcherConfigTheme'
styleswitcher.routing.yml in ./styleswitcher.routing.yml
styleswitcher.routing.yml

File

src/Form/StyleswitcherConfigTheme.php, line 14

Namespace

Drupal\styleswitcher\Form
View source
class StyleswitcherConfigTheme extends FormBase {

  /**
   * The theme handler.
   *
   * @var \Drupal\Core\Extension\ThemeHandlerInterface
   */
  protected $themeHandler;

  /**
   * Constructs the StyleswitcherConfigTheme.
   *
   * @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler
   *   The theme handler.
   */
  public function __construct(ThemeHandlerInterface $theme_handler) {
    $this->themeHandler = $theme_handler;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('theme_handler'));
  }

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

  /**
   * 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.
   * @param string $theme
   *   Name of the theme to configure styles for.
   *
   * @return array
   *   The form structure.
   */
  public function buildForm(array $form, FormStateInterface $form_state, $theme = '') {
    if (!$this->themeHandler
      ->hasUi($theme)) {
      throw new NotFoundHttpException();
    }
    $styles = styleswitcher_style_load_multiple($theme);
    uasort($styles, 'styleswitcher_sort');
    $options = array_fill_keys(array_keys($styles), '');
    $form['theme_name'] = [
      '#type' => 'value',
      '#value' => $theme,
    ];
    $form['settings'] = [
      '#theme' => 'styleswitcher_admin_styles_table',
      '#tree' => TRUE,
    ];
    foreach ($styles as $name => $style) {
      $form['settings']['weight'][$name] = [
        '#type' => 'weight',
        '#title' => $this
          ->t('Weight for @label', [
          '@label' => $style['label'],
        ]),
        '#title_display' => 'invisible',
        '#delta' => $this
          ->weightDelta($theme),
        '#default_value' => $style['weight'],
        '#weight' => $style['weight'],
        // Set special class for drag and drop updating.
        '#attributes' => [
          'class' => [
            'styleswitcher-style-weight',
          ],
        ],
      ];
      $form['settings']['name'][$name] = [
        '#theme' => 'styleswitcher_admin_style_overview',
        '#style' => $style,
      ];
      $form['settings']['label'][$name] = [
        '#markup' => $style['label'],
      ];
    }
    $form['settings']['enabled'] = [
      '#type' => 'checkboxes',
      '#title' => $this
        ->t('Enabled'),
      '#title_display' => 'invisible',
      '#options' => $options,
      '#default_value' => array_keys(styleswitcher_style_load_multiple($theme, [
        'status' => TRUE,
      ])),
    ];
    $form['settings']['default'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Default'),
      '#title_display' => 'invisible',
      '#options' => $options,
      '#default_value' => styleswitcher_default_style_key($theme),
    ];
    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save configuration'),
      '#button_type' => 'primary',
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $theme = $form_state
      ->getValue('theme_name');
    $values = $form_state
      ->getValue('settings');

    // Automatically enable the default style and the style which was default
    // previously because we will not get the value from that disabled checkbox.
    $values['enabled'][$values['default']] = 1;
    $values['enabled'][styleswitcher_default_style_key($theme)] = 1;
    $form_state
      ->setValueForElement($form['settings'], $values);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $theme = $form_state
      ->getValue('theme_name');
    $values = $form_state
      ->getValue('settings');
    $theme_settings = [];
    foreach (array_keys(styleswitcher_style_load_multiple($theme)) as $name) {
      $theme_settings[$name] = [
        'weight' => $values['weight'][$name],
        'status' => !empty($values['enabled'][$name]),
        'is_default' => $values['default'] == $name,
      ];
    }

    // Get all settings (for all themes).
    $config = $this
      ->configFactory()
      ->getEditable('styleswitcher.styles_settings');
    $settings = $config
      ->get('settings') ?? [];
    $settings[$theme] = $theme_settings;
    $config
      ->set('settings', $settings)
      ->save();
    $this
      ->messenger()
      ->addStatus($this
      ->t('The configuration options have been saved.'));
  }

  /**
   * Calculates #delta for style's weight element.
   *
   * @param string $theme
   *   Name of the theme for which styles the delta is calculated.
   *
   * @return int
   *   Optimal #delta value.
   */
  protected function weightDelta($theme) {
    foreach (styleswitcher_style_load_multiple($theme) as $style) {
      $weights[] = $style['weight'];
    }
    return max(abs(min($weights)), max($weights), floor(count($weights) / 2));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 3
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. 3
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.
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.
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. 27
MessengerTrait::messenger public function Gets the messenger. 27
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. 4
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.
StyleswitcherConfigTheme::$themeHandler protected property The theme handler.
StyleswitcherConfigTheme::buildForm public function Form constructor. Overrides FormInterface::buildForm
StyleswitcherConfigTheme::create public static function Instantiates a new instance of this class. Overrides FormBase::create
StyleswitcherConfigTheme::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
StyleswitcherConfigTheme::submitForm public function Form submission handler. Overrides FormInterface::submitForm
StyleswitcherConfigTheme::validateForm public function Form validation handler. Overrides FormBase::validateForm
StyleswitcherConfigTheme::weightDelta protected function Calculates #delta for style's weight element.
StyleswitcherConfigTheme::__construct public function Constructs the StyleswitcherConfigTheme.