ispim-1.0.x-dev/src/PreviewImage/AccessControlHandler.php
src/PreviewImage/AccessControlHandler.php
<?php
declare(strict_types=1);
namespace Drupal\ispim\PreviewImage;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Access\AccessResultInterface;
use Drupal\Core\Entity\EntityAccessControlHandler;
use Drupal\Core\Entity\EntityHandlerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class AccessControlHandler extends EntityAccessControlHandler implements EntityHandlerInterface {
/**
* {@inheritdoc}
*
* @return static
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
// @phpstan-ignore-next-line
return new static($entity_type);
}
/**
* {@inheritdoc}
*
* @phpstan-param array<string, mixed> $context
* @phpstan-param ?string $entity_bundle
*/
protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL): AccessResultInterface {
$return = parent::checkCreateAccess($account, $context, $entity_bundle);
if (!$return->isNeutral()) {
return $return;
}
return AccessResult::allowedIfHasPermissions(
$account,
$this->getPermissions('create', $entity_bundle),
'OR',
);
}
/**
* {@inheritdoc}
*/
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
$return = parent::checkAccess($entity, $operation, $account);
if (!$return->isNeutral()) {
return $return;
}
return match ($operation) {
'update',
'view',
'delete' => AccessResult::allowedIfHasPermissions(
$account,
$this->getPermissions($operation, $entity->bundle()),
'OR',
),
default => AccessResult::neutral(),
};
}
/**
* The permission IDs based on the operation and the entity type definition.
*
* @return string[]
*/
protected function getPermissions(string $operation, string $bundle = ''): array {
$provider = $this->entityType->getProvider();
$bundle = $bundle ?: '_all';
return array_unique(array_filter([
(string) $this->entityType->getAdminPermission(),
"$provider.{$this->entityTypeId}._all",
"$provider.{$this->entityTypeId}._all.$operation",
"$provider.{$this->entityTypeId}.$bundle",
"$provider.{$this->entityTypeId}.$bundle.$operation",
]));
}
}
