course_certificate.module in Course 3.x
File
modules/course_certificate/course_certificate.module
View source
<?php
use Drupal\Core\Link;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\course\Entity\Course;
function course_certificate_course_outline_completion_links_alter(&$links, Course $course, AccountInterface $account) {
if ($course
->access('certificate', $account)) {
$links['certificate'] = Link::createFromRoute(t('Download certificate'), 'certificate.course', [
'course' => $course
->id(),
], [
'title' => t('Download a PDF of your certificate.'),
]);
}
}
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();
foreach ($entity
->getObjects() as $courseObject) {
if ($courseObject
->getComponent() == 'certificate') {
$has_object = TRUE;
break;
}
}
if (!$has_object) {
$access_result = AccessResult::forbidden('No certificate object provided.');
}
$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);
if ($admin || $view_all || $enrollment
->isComplete()) {
$access_result = AccessResult::allowed();
}
}
return $access_result;
}
}