3 namespace Drupal\block_content;
5 use Drupal\block_content\Access\DependentAccessInterface;
6 use Drupal\block_content\Event\BlockContentGetDependencyEvent;
7 use Drupal\Core\Access\AccessResult;
8 use Drupal\Core\Entity\EntityHandlerInterface;
9 use Drupal\Core\Entity\EntityInterface;
10 use Drupal\Core\Entity\EntityAccessControlHandler;
11 use Drupal\Core\Entity\EntityTypeInterface;
12 use Drupal\Core\Session\AccountInterface;
13 use Symfony\Component\DependencyInjection\ContainerInterface;
14 use Symfony\Component\EventDispatcher\EventDispatcherInterface;
17 * Defines the access control handler for the custom block entity type.
19 * @see \Drupal\block_content\Entity\BlockContent
21 class BlockContentAccessControlHandler extends EntityAccessControlHandler implements EntityHandlerInterface {
24 * The event dispatcher.
26 * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
28 protected $eventDispatcher;
31 * BlockContentAccessControlHandler constructor.
33 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
35 * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher
36 * The event dispatcher.
38 public function __construct(EntityTypeInterface $entity_type, EventDispatcherInterface $dispatcher) {
39 parent::__construct($entity_type);
40 $this->eventDispatcher = $dispatcher;
46 public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
49 $container->get('event_dispatcher')
56 protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
57 if ($operation === 'view') {
58 $access = AccessResult::allowedIf($entity->isPublished())
59 ->orIf(AccessResult::allowedIfHasPermission($account, 'administer blocks'));
62 $access = parent::checkAccess($entity, $operation, $account);
64 // Add the entity as a cacheable dependency because access will at least be
65 // determined by whether the block is reusable.
66 $access->addCacheableDependency($entity);
67 /** @var \Drupal\block_content\BlockContentInterface $entity */
68 if ($entity->isReusable() === FALSE) {
69 if (!$entity instanceof DependentAccessInterface) {
70 throw new \LogicException("Non-reusable block entities must implement \Drupal\block_content\Access\DependentAccessInterface for access control.");
72 $dependency = $entity->getAccessDependency();
73 if (empty($dependency)) {
74 // If an access dependency has not been set let modules set one.
75 $event = new BlockContentGetDependencyEvent($entity);
76 $this->eventDispatcher->dispatch(BlockContentEvents::BLOCK_CONTENT_GET_DEPENDENCY, $event);
77 $dependency = $event->getAccessDependency();
78 if (empty($dependency)) {
79 return AccessResult::forbidden("Non-reusable blocks must set an access dependency for access control.");
82 /** @var \Drupal\Core\Entity\EntityInterface $dependency */
83 $access = $access->andIf($dependency->access($operation, $account, TRUE));