EntityAccessControlHandler.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace Drupal\entity;
  3. use Drupal\Core\Access\AccessResult;
  4. use Drupal\Core\Entity\EntityInterface;
  5. use Drupal\Core\Entity\EntityPublishedInterface;
  6. use Drupal\Core\Entity\EntityTypeInterface;
  7. use Drupal\Core\Session\AccountInterface;
  8. /**
  9. * Controls access based on the generic entity permissions.
  10. *
  11. * @see \Drupal\entity\UncacheableEntityPermissionProvider
  12. */
  13. class EntityAccessControlHandler extends EntityAccessControlHandlerBase {
  14. /**
  15. * {@inheritdoc}
  16. */
  17. public function __construct(EntityTypeInterface $entity_type) {
  18. parent::__construct($entity_type);
  19. if (!$entity_type->hasHandlerClass('permission_provider') || !is_a($entity_type->getHandlerClass('permission_provider'), EntityPermissionProvider::class, TRUE)) {
  20. throw new \Exception('\Drupal\entity\EntityAccessControlHandler requires the \Drupal\entity\EntityPermissionProvider permission provider.');
  21. }
  22. }
  23. /**
  24. * {@inheritdoc}
  25. */
  26. protected function checkEntityOwnerPermissions(EntityInterface $entity, $operation, AccountInterface $account) {
  27. /** @var \Drupal\user\EntityOwnerInterface $entity */
  28. if ($operation === 'view') {
  29. if ($entity instanceof EntityPublishedInterface && !$entity->isPublished()) {
  30. if ($account->id() != $entity->getOwnerId()) {
  31. // There's no permission for viewing other user's unpublished entity.
  32. return AccessResult::neutral()->cachePerUser();
  33. }
  34. $permissions = [
  35. "view own unpublished {$entity->getEntityTypeId()}",
  36. ];
  37. $result = AccessResult::allowedIfHasPermissions($account, $permissions)->cachePerUser();
  38. }
  39. else {
  40. $result = AccessResult::allowedIfHasPermissions($account, [
  41. "view {$entity->getEntityTypeId()}",
  42. "view {$entity->bundle()} {$entity->getEntityTypeId()}",
  43. ], 'OR');
  44. }
  45. }
  46. else {
  47. $result = parent::checkEntityOwnerPermissions($entity, $operation, $account);
  48. }
  49. return $result;
  50. }
  51. }