You are here

class DefaultController in Style Switcher 3.0.x

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

Default controller for the styleswitcher module.

Hierarchy

Expanded class hierarchy of DefaultController

File

src/Controller/DefaultController.php, line 15

Namespace

Drupal\styleswitcher\Controller
View source
class DefaultController extends ControllerBase {

  /**
   * The Datetime service.
   *
   * @var \Drupal\Component\Datetime\TimeInterface
   */
  protected $time;

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

  /**
   * Constructs a new DefaultController.
   *
   * @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler
   *   The theme handler.
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   The DateTime service.
   */
  public function __construct(ThemeHandlerInterface $theme_handler, TimeInterface $time) {
    $this->themeHandler = $theme_handler;
    $this->time = $time;
  }

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

  /**
   * Switches style when JS is disabled.
   *
   * @param array $style
   *   New active style. The structure of an array is the same as returned from
   *   styleswitcher_style_load().
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   Response object.
   *
   * @see styleswitcher_style_load()
   */
  public function styleswitcherSwitch(array $style) {
    if ($style['status']) {
      $this
        ->saveUserPreference($style['theme'], $style['name']);
    }
    return $this
      ->redirect('<front>');
  }

  /**
   * Redirects to CSS file of currently active style.
   *
   * @param string $theme
   *   Name of the theme to find the active style for. This argument is needed
   *   to know what the page user came from and what theme was used there.
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   Response object.
   */
  public function styleswitcherCss($theme) {

    // Prevent resource incorrect interpretation.
    $headers = [
      'Content-Type' => 'text/css',
    ];
    $path = $this
      ->activeStylePath($theme);
    if (isset($path)) {
      return new TrustedRedirectResponse(file_create_url($path), 302, $headers);
    }
    else {
      return new Response('', 200, $headers);
    }
  }

  /**
   * Finds the style active for current user and returns its path.
   *
   * This function is called at every page request before styleswitcherSwitch()
   * or JS' Drupal.styleSwitcher.switchStyle() so we can update old user cookies
   * here once and not bother about it in other places.
   *
   * @param string $theme
   *   Name of the theme to find the active style for.
   *
   * @return string|null
   *   The path property of active style. It can be NULL if active style is the
   *   blank one.
   *
   * @see \Drupal\styleswitcher\Controller\DefaultController::styleswitcherSwitch()
   * @see Drupal.styleSwitcher.switchStyle()
   */
  protected function activeStylePath($theme) {
    if (isset($_COOKIE['styleswitcher'])) {
      $cookie = $_COOKIE['styleswitcher'];
      if (!is_array($cookie)) {

        // This style with its settings belongs to the theme which was default
        // before styleswitcher_update_7206(). If there's no variable, try the
        // default theme, it could still be the same one.
        $style_theme = $this
          ->config('styleswitcher.settings')
          ->get('7206_theme_default') ?? $this->themeHandler
          ->getDefault();
        if (strpos($cookie, '/')) {
          if (styleswitcher_style_load($cookie, $style_theme)) {
            $name = $cookie;
          }
        }
        elseif (($style = styleswitcher_style_load($cookie, $style_theme, 'theme')) || ($style = styleswitcher_style_load($cookie, $style_theme, 'custom'))) {
          $name = $style['name'];
        }

        // Remove this old cookie.
        setcookie('styleswitcher', '', 0, base_path());
        $cookie = [];
        if (isset($name)) {

          // And save the new one.
          $this
            ->saveUserPreference($style_theme, $name);
          $cookie[$style_theme] = $name;
        }
      }
      if (isset($cookie[$theme])) {
        $active = styleswitcher_style_load($cookie[$theme], $theme);
      }
    }
    elseif (isset($_COOKIE['styleSwitcher'])) {
      $name = 'theme/' . _styleswitcher_style_name($_COOKIE['styleSwitcher']);

      // Remove this old cookie.
      setcookie('styleSwitcher', '', 0, base_path());

      // We actually do not know what theme was used (it was a global $theme)
      // when user switched to this style. So let us just set this style as
      // active for every theme which has a style with this name.
      $themes = array_keys($this->themeHandler
        ->listInfo());
      foreach ($themes as $style_theme) {
        if ($style = styleswitcher_style_load($name, $style_theme)) {
          $this
            ->saveUserPreference($style_theme, $name);
          if ($theme == $style_theme) {
            $active = $style;
          }
        }
      }
    }
    if (empty($active)) {
      $active = styleswitcher_style_load(styleswitcher_default_style_key($theme), $theme);
    }
    return $active['path'];
  }

  /**
   * Saves the style key to the cookie.
   *
   * @param string $theme_key
   *   Name of the theme to save the style for.
   * @param string $style_key
   *   Style key to save.
   */
  protected function saveUserPreference($theme_key, $style_key) {
    $request_time = $this->time
      ->getRequestTime();
    setcookie('styleswitcher[' . $theme_key . ']', $style_key, $request_time + STYLESWITCHER_COOKIE_EXPIRE, base_path());
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route.
ControllerBase::state protected function Returns the state storage service.
DefaultController::$themeHandler protected property The theme handler service.
DefaultController::$time protected property The Datetime service.
DefaultController::activeStylePath protected function Finds the style active for current user and returns its path.
DefaultController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
DefaultController::saveUserPreference protected function Saves the style key to the cookie.
DefaultController::styleswitcherCss public function Redirects to CSS file of currently active style.
DefaultController::styleswitcherSwitch public function Switches style when JS is disabled.
DefaultController::__construct public function Constructs a new DefaultController.
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.