ScriptAccessControlHandler.php in Script Manager 8
File
src/Entity/ScriptAccessControlHandler.php
View source
<?php
namespace Drupal\script_manager\Entity;
use Drupal\Component\Plugin\ContextAwarePluginInterface;
use Drupal\Component\Plugin\Exception\ContextException;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\Core\Condition\ConditionAccessResolverTrait;
use Drupal\Core\Entity\EntityAccessControlHandler;
use Drupal\Core\Entity\EntityHandlerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Plugin\Context\ContextHandlerInterface;
use Drupal\Core\Plugin\Context\ContextRepositoryInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ScriptAccessControlHandler extends EntityAccessControlHandler implements EntityHandlerInterface {
use ConditionAccessResolverTrait;
protected $contextHandler;
protected $contextRepository;
public function __construct(EntityTypeInterface $entity_type, ContextHandlerInterface $context_handler, ContextRepositoryInterface $context_repository) {
parent::__construct($entity_type);
$this->contextHandler = $context_handler;
$this->contextRepository = $context_repository;
}
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static($entity_type, $container
->get('context.handler'), $container
->get('context.repository'));
}
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
if ($operation !== 'view') {
return parent::checkAccess($entity, $operation, $account);
}
try {
$conditions = $this
->getPreparedConditions($entity);
} catch (ContextException $e) {
return AccessResult::forbidden()
->setCacheMaxAge(0);
}
$access = $this
->resolveConditions($conditions, 'and') !== FALSE ? AccessResult::allowed() : AccessResult::forbidden();
$access
->addCacheableDependency($entity);
foreach ($conditions as $condition) {
if ($condition instanceof CacheableDependencyInterface) {
$access
->addCacheableDependency($condition);
}
}
return $access;
}
protected function getPreparedConditions(ScriptInterface $entity) {
$conditions = [];
foreach ($entity
->getVisibilityConditions() as $condition_id => $condition) {
if ($condition instanceof ContextAwarePluginInterface) {
$contexts = $this->contextRepository
->getRuntimeContexts(array_values($condition
->getContextMapping()));
$this->contextHandler
->applyContextMapping($condition, $contexts);
$conditions[$condition_id] = $condition;
}
}
return $conditions;
}
}