UncacheableEntityAccessControlHandler.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 uncacheable entity permissions.
  10. *
  11. * @see \Drupal\entity\UncacheableEntityPermissionProvider
  12. *
  13. * Note: this access control handler will cause pages to be cached per user.
  14. */
  15. class UncacheableEntityAccessControlHandler extends EntityAccessControlHandlerBase {
  16. /**
  17. * {@inheritdoc}
  18. */
  19. public function __construct(EntityTypeInterface $entity_type) {
  20. parent::__construct($entity_type);
  21. if (!$entity_type->hasHandlerClass('permission_provider') || !is_a($entity_type->getHandlerClass('permission_provider'), UncacheableEntityPermissionProvider::class, TRUE)) {
  22. throw new \Exception('\Drupal\entity\UncacheableEntityAccessControlHandler requires the \Drupal\entity\UncacheableEntityPermissionProvider permission provider.');
  23. }
  24. }
  25. /**
  26. * {@inheritdoc}
  27. */
  28. protected function checkEntityOwnerPermissions(EntityInterface $entity, $operation, AccountInterface $account) {
  29. /** @var \Drupal\user\EntityOwnerInterface $entity */
  30. if ($operation === 'view' && $entity instanceof EntityPublishedInterface && !$entity->isPublished()) {
  31. if ($account->id() != $entity->getOwnerId()) {
  32. // There's no permission for viewing other user's unpublished entity.
  33. return AccessResult::neutral()->cachePerUser();
  34. }
  35. $permissions = [
  36. "view own unpublished {$entity->getEntityTypeId()}",
  37. ];
  38. $result = AccessResult::allowedIfHasPermissions($account, $permissions)->cachePerUser();
  39. }
  40. else {
  41. $result = parent::checkEntityOwnerPermissions($entity, $operation, $account);
  42. }
  43. return $result;
  44. }
  45. }