You are here

public function ThemeSwitcherNegotiator::applies in Theme Switcher Rules 8

Whether this theme negotiator should be used to set the theme.

Parameters

\Drupal\Core\Routing\RouteMatchInterface $route_match: The current route match object.

Return value

bool TRUE if this negotiator should be used or FALSE to let other negotiators decide.

Overrides ThemeNegotiatorInterface::applies

File

src/Theme/ThemeSwitcherNegotiator.php, line 80

Class

ThemeSwitcherNegotiator
Negotiate the current theme based on theme_switcher_rules rules.

Namespace

Drupal\theme_switcher\Theme

Code

public function applies(RouteMatchInterface $route_match) {
  $storage = $this->entityTypeManager
    ->getStorage('theme_switcher_rule');
  $configEntities = $storage
    ->getQuery()
    ->sort('weight', 'ASC')
    ->execute();
  $rules = $storage
    ->loadMultiple($configEntities);
  foreach ($rules as $rule) {

    /** @var \Drupal\theme_switcher\Entity\ThemeSwitcherRule $rule */

    // Check whether the rule is enabled and one of the themes is set.
    if ($rule
      ->status() && (!empty($rule
      ->getTheme()) || !empty($rule
      ->getAdminTheme()))) {
      $conditions = [];
      foreach ($rule
        ->getVisibilityConditions() as $condition_id => $condition) {
        if ($condition instanceof ContextAwarePluginInterface) {
          try {
            $contexts = $this->contextRepository
              ->getRuntimeContexts(array_values($condition
              ->getContextMapping()));
            $this->contextHandler
              ->applyContextMapping($condition, $contexts);
          } catch (MissingValueContextException|ContextException $e) {

            // MissingValueContextException: If any context is missing then
            // we might be missing cacheable metadata, and don't know based
            // on what conditions the block is accessible or not. Make sure
            // the result cannot be cached.
            //
            // ContextException: The contexts exist but have no value. Deny
            // access without disabling caching. For example the node type
            // condition will have a missing context on any non-node route
            // like the frontpage.
            return FALSE;
          }
        }
        $conditions[$condition_id] = $condition;
      }

      // Check whether the conditions are resolved positively.
      if ($this
        ->resolveConditions($conditions, 'and') !== FALSE) {

        // Are we in a admin route?
        $route = $route_match
          ->getRouteObject();
        $is_admin_route = $this->adminContext
          ->isAdminRoute($route);
        $this->theme = !$is_admin_route ? $rule
          ->getTheme() : $rule
          ->getAdminTheme();
        return !empty($this->theme) ? TRUE : FALSE;
      }
    }
  }
  return FALSE;
}