You are here

function commerce_file_file_access in Commerce File 8.2

Implements hook_ENTITY_TYPE_access() for files.

File

./commerce_file.module, line 33
Extends Commerce License with the ability to sell access to files.

Code

function commerce_file_file_access(EntityInterface $entity, $operation, AccountInterface $account) {
  if (!in_array($operation, [
    'download',
    'view',
  ])) {
    return AccessResult::neutral();
  }
  if ($account
    ->hasPermission('bypass license control') || $account
    ->hasPermission('administer commerce_license')) {
    return AccessResult::neutral();
  }
  assert($entity instanceof FileInterface);

  /** @var \Drupal\commerce_file\LicenseFileManagerInterface $license_file_manager */
  $license_file_manager = \Drupal::service('commerce_file.license_file_manager');

  // This file is not licensable, no opinion on access.
  if (!$license_file_manager
    ->isLicensable($entity)) {
    return AccessResult::neutral();
  }
  $active_licenses = $license_file_manager
    ->getActiveLicenses($entity, $account);

  // We forbid access to the file if it's licensable and no active license
  // that can be downloaded for the current user exists.
  $active_licenses = array_filter($active_licenses, function (LicenseInterface $license) use ($license_file_manager, $entity, $account) {
    return $license_file_manager
      ->canDownload($license, $entity, $account);
  });
  return AccessResult::forbiddenIf(!$active_licenses);
}