You are here

function course_certificate_entity_access in Course 3.x

Implements hook_entity_access().

Control access to a certificate on this course.

Parameters

EntityInterface $entity:

type $operation:

AccountInterface $account:

Return value

type

File

modules/course_certificate/course_certificate.module, line 31

Code

function course_certificate_entity_access(EntityInterface $entity, $operation, AccountInterface $user) {
  $currentUser = Drupal::currentUser();
  $requestedUser = $user ?? $currentUser;
  $admin = $currentUser
    ->hasPermission('administer certificates');
  $view_all = $currentUser
    ->hasPermission('view all user certificates');
  if ($entity
    ->getEntityTypeId() == 'course' && $operation == 'certificate') {
    $has_object = FALSE;
    $access_result = AccessResult::neutral();

    // Does the course have a certificate object?
    foreach ($entity
      ->getObjects() as $courseObject) {
      if ($courseObject
        ->getComponent() == 'certificate') {
        $has_object = TRUE;
        break;
      }
    }
    if (!$has_object) {
      $access_result = AccessResult::forbidden('No certificate object provided.');
    }

    // Are they enrolled?
    $enrollments = Drupal::entityTypeManager()
      ->getStorage('course_enrollment')
      ->loadByProperties([
      'uid' => $requestedUser
        ->id(),
      'cid' => $entity
        ->id(),
    ]);
    if (empty($enrollments)) {
      $access_result = AccessResult::forbidden('User is not enrolled');
    }
    else {
      $enrollment = reset($enrollments);

      // Are they an admin or have they completed the course?
      if ($admin || $view_all || $enrollment
        ->isComplete()) {
        $access_result = AccessResult::allowed();
      }
    }
    return $access_result;
  }
}