BlockAccessControlHandler.php 5.84 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\block;

5
use Drupal\Component\Plugin\Exception\ContextException;
6
use Drupal\Core\Access\AccessResult;
7 8
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableDependencyInterface;
9
use Drupal\Core\Condition\ConditionAccessResolverTrait;
10
use Drupal\Core\Entity\EntityAccessControlHandler;
11
use Drupal\Core\Entity\EntityHandlerInterface;
12
use Drupal\Core\Entity\EntityInterface;
13 14
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Plugin\Context\ContextHandlerInterface;
15
use Drupal\Core\Plugin\Context\ContextRepositoryInterface;
16
use Drupal\Core\Plugin\ContextAwarePluginInterface;
17
use Drupal\Core\Session\AccountInterface;
18
use Symfony\Component\DependencyInjection\ContainerInterface;
19 20

/**
21 22 23
 * Defines the access control handler for the block entity type.
 *
 * @see \Drupal\block\Entity\Block
24
 */
25 26 27 28 29 30 31 32 33 34 35
class BlockAccessControlHandler extends EntityAccessControlHandler implements EntityHandlerInterface {

  use ConditionAccessResolverTrait;

  /**
   * The plugin context handler.
   *
   * @var \Drupal\Core\Plugin\Context\ContextHandlerInterface
   */
  protected $contextHandler;

36 37 38 39 40 41 42
  /**
   * The context manager service.
   *
   * @var \Drupal\Core\Plugin\Context\ContextRepositoryInterface
   */
  protected $contextRepository;

43 44 45 46 47 48
  /**
   * {@inheritdoc}
   */
  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
    return new static(
      $entity_type,
49 50
      $container->get('context.handler'),
      $container->get('context.repository')
51 52 53 54 55 56 57 58 59 60
    );
  }

  /**
   * Constructs the block access control handler instance
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type definition.
   * @param \Drupal\Core\Plugin\Context\ContextHandlerInterface $context_handler
   *   The ContextHandler for applying contexts to conditions properly.
61 62
   * @param \Drupal\Core\Plugin\Context\ContextRepositoryInterface $context_repository
   *   The lazy context repository service.
63
   */
64
  public function __construct(EntityTypeInterface $entity_type, ContextHandlerInterface $context_handler, ContextRepositoryInterface $context_repository) {
65 66
    parent::__construct($entity_type);
    $this->contextHandler = $context_handler;
67
    $this->contextRepository = $context_repository;
68 69
  }

70 71

  /**
72
   * {@inheritdoc}
73
   */
74
  protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
75
    /** @var \Drupal\block\BlockInterface $entity */
76
    if ($operation != 'view') {
77
      return parent::checkAccess($entity, $operation, $account);
78
    }
79

80
    // Don't grant access to disabled blocks.
81
    if (!$entity->status()) {
82
      return AccessResult::forbidden()->addCacheableDependency($entity);
83 84
    }
    else {
85
      $conditions = [];
86
      $missing_context = FALSE;
87 88 89
      foreach ($entity->getVisibilityConditions() as $condition_id => $condition) {
        if ($condition instanceof ContextAwarePluginInterface) {
          try {
90
            $contexts = $this->contextRepository->getRuntimeContexts(array_values($condition->getContextMapping()));
91 92 93
            $this->contextHandler->applyContextMapping($condition, $contexts);
          }
          catch (ContextException $e) {
94
            $missing_context = TRUE;
95 96 97 98
          }
        }
        $conditions[$condition_id] = $condition;
      }
99 100 101 102 103 104 105 106 107 108 109 110 111

      if ($missing_context) {
        // 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. For example, blocks that have a node type
        // condition will have a missing context on any non-node route like the
        // frontpage.
        // @todo Avoid setting max-age 0 for some or all cases, for example by
        //   treating available contexts without value differently in
        //   https://www.drupal.org/node/2521956.
        $access = AccessResult::forbidden()->setCacheMaxAge(0);
      }
      elseif ($this->resolveConditions($conditions, 'and') !== FALSE) {
112
        // Delegate to the plugin.
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
        $block_plugin = $entity->getPlugin();
        try {
          if ($block_plugin instanceof ContextAwarePluginInterface) {
            $contexts = $this->contextRepository->getRuntimeContexts(array_values($block_plugin->getContextMapping()));
            $this->contextHandler->applyContextMapping($block_plugin, $contexts);
          }
          $access = $block_plugin->access($account, TRUE);
        }
        catch (ContextException $e) {
          // Setting access to forbidden if any context is missing for the same
          // reasons as with conditions (described in the comment above).
          // @todo Avoid setting max-age 0 for some or all cases, for example by
          //   treating available contexts without value differently in
          //   https://www.drupal.org/node/2521956.
          $access = AccessResult::forbidden()->setCacheMaxAge(0);
        }
129 130 131 132
      }
      else {
        $access = AccessResult::forbidden();
      }
133 134 135 136

      $this->mergeCacheabilityFromConditions($access, $conditions);

      // Ensure that access is evaluated again when the block changes.
137
      return $access->addCacheableDependency($entity);
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
    }
  }

  /**
   * Merges cacheable metadata from conditions onto the access result object.
   *
   * @param \Drupal\Core\Access\AccessResult $access
   *   The access result object.
   * @param \Drupal\Core\Condition\ConditionInterface[] $conditions
   *   List of visibility conditions.
   */
  protected function mergeCacheabilityFromConditions(AccessResult $access, array $conditions) {
    foreach ($conditions as $condition) {
      if ($condition instanceof CacheableDependencyInterface) {
        $access->addCacheTags($condition->getCacheTags());
        $access->addCacheContexts($condition->getCacheContexts());
        $access->setCacheMaxAge(Cache::mergeMaxAges($access->getCacheMaxAge(), $condition->getCacheMaxAge()));
      }
156
    }
157 158 159
  }

}