View source
<?php
namespace Drupal\entity;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityAccessControlHandler as CoreEntityAccessControlHandler;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\user\EntityOwnerInterface;
class EntityAccessControlHandlerBase extends CoreEntityAccessControlHandler {
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
$account = $this
->prepareUser($account);
$result = parent::checkAccess($entity, $operation, $account);
if ($result
->isNeutral()) {
if ($entity instanceof EntityOwnerInterface) {
$result = $this
->checkEntityOwnerPermissions($entity, $operation, $account);
}
else {
$result = $this
->checkEntityPermissions($entity, $operation, $account);
}
}
return $result
->addCacheableDependency($entity);
}
protected function checkEntityPermissions(EntityInterface $entity, $operation, AccountInterface $account) {
$permissions = [
"{$operation} {$entity->getEntityTypeId()}",
"{$operation} {$entity->bundle()} {$entity->getEntityTypeId()}",
];
return AccessResult::allowedIfHasPermissions($account, $permissions, 'OR');
}
protected function checkEntityOwnerPermissions(EntityInterface $entity, $operation, AccountInterface $account) {
$any_result = AccessResult::allowedIfHasPermissions($account, [
"{$operation} any {$entity->getEntityTypeId()}",
"{$operation} any {$entity->bundle()} {$entity->getEntityTypeId()}",
], 'OR');
if ($any_result
->isAllowed()) {
return $any_result;
}
if ($account
->id() == $entity
->getOwnerId()) {
$own_result = AccessResult::allowedIfHasPermissions($account, [
"{$operation} own {$entity->getEntityTypeId()}",
"{$operation} own {$entity->bundle()} {$entity->getEntityTypeId()}",
], 'OR');
}
else {
$own_result = AccessResult::neutral()
->cachePerPermissions();
}
return $own_result
->cachePerUser();
}
protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {
$result = parent::checkCreateAccess($account, $context, $entity_bundle);
if ($result
->isNeutral()) {
$permissions = [
$this->entityType
->getAdminPermission() ?: 'administer ' . $this->entityTypeId,
'create ' . $this->entityTypeId,
];
if ($entity_bundle) {
$permissions[] = 'create ' . $entity_bundle . ' ' . $this->entityTypeId;
}
$result = AccessResult::allowedIfHasPermissions($account, $permissions, 'OR');
}
return $result;
}
}