function course_commerce_course_access in Course 3.x
Implements hook_course_access().
Block the user from enrolling in a paid course.
File
- modules/
course_commerce/ course_commerce.module, line 451
Code
function course_commerce_course_access(Course $course, $op, AccountProxy $account) {
if ($op == 'enroll') {
if ($course
->hasField('commerce_product') && !$course
->get('commerce_product')
->isEmpty()) {
/* @var $product Product */
if ($product = $course
->get('commerce_product')
->referencedEntities()[0]) {
$variation = $product
->get('variations')
->referencedEntities()[0];
if (!$product
->get('variations')
->isEmpty()) {
// Course has a product.
if (!course_commerce_check_purchased($course, $account)) {
return [
'course_must_purchase' => AccessResult::forbidden('You must checkout to enroll in this course.'),
];
return array(
'course_must_purchase' => array(
'success' => FALSE,
'header' => t('Checkout required'),
'message' => t('You must checkout to enroll in this course.'),
'weight' => 1000,
),
);
}
// Now we have to check that even if the course has a price, that the
// payment object is first (to block enrollments). If the course is $0 and
// there are no payment objects, we assume the enrollment is blocked.
$courseObjects = $course
->getObjects();
$first = reset($courseObjects);
foreach ($courseObjects as $courseObject) {
$first_object = $courseObject
->id() == $first
->id();
$is_payment = $courseObject
->getComponent() == 'commerce';
if ($is_payment && $first_object) {
$product = course_get_attached($courseObject
->getCourse());
$complete = $courseObject
->getFulfillment($account)
->isComplete();
if (!$product
->get('variations')
->isEmpty() && !$complete) {
// Force purchase.
if (!$course
->isEnrolled($account)) {
return [
'course_must_purchase' => AccessResult::forbidden('You must purchase this course.'),
];
}
}
}
}
}
}
}
}
}