You are here

function access_unpublished_entity_access in Access unpublished 8

Implements hook_entity_access().

1 call to access_unpublished_entity_access()
LatestRevisionCheck::access in src/Access/LatestRevisionCheck.php
Checks that there is a pending revision available.

File

./access_unpublished.module, line 18
Contains access_unpublished implementations.

Code

function access_unpublished_entity_access(EntityInterface $entity, $operation, AccountInterface $account) {

  /** @var \Drupal\access_unpublished\TokenGetter $tokenGetter */
  $tokenGetter = \Drupal::service('access_unpublished.token_getter');
  $permission = 'access_unpublished ' . $entity
    ->getEntityTypeId() . ($entity
    ->getEntityType()
    ->hasKey('bundle') ? ' ' . $entity
    ->bundle() : '');
  $config = \Drupal::config('access_unpublished.settings');
  $result = AccessResult::neutral()
    ->addCacheContexts([
    'url.query_args:' . $config
      ->get('hash_key'),
  ])
    ->cachePerPermissions()
    ->addCacheableDependency($config)
    ->addCacheableDependency($entity);
  if ($operation == 'view' && ($token = $tokenGetter
    ->getToken()) && AccessUnpublished::applicableEntityType($entity
    ->getEntityType()) && $account
    ->hasPermission($permission) && !$entity
    ->isPublished()) {
    $tokens = \Drupal::entityTypeManager()
      ->getStorage('access_token')
      ->loadByProperties([
      'entity_type' => $entity
        ->getEntityType()
        ->id(),
      'entity_id' => $entity
        ->id(),
      'value' => $token,
    ]);
    if ($tokens) {
      $tokenEntity = reset($tokens);
      $result
        ->addCacheableDependency($tokenEntity);
      if (!$tokenEntity
        ->isExpired()) {
        $result = AccessResult::allowed()
          ->setCacheMaxAge($tokenEntity
          ->get('expire')->value - \Drupal::time()
          ->getRequestTime())
          ->inheritCacheability($result);
      }
    }
  }
  return $result;
}