You are here

function course_commerce_enroll_user_in_ordered_courses in Course 3.x

Loops through items in an Ubercart order and enrolls the user in courses purchased.

Parameters

Order $order:

1 call to course_commerce_enroll_user_in_ordered_courses()
course_commerce_commerce_order_update in modules/course_commerce/course_commerce.module
Implements hook_uc_order_update().

File

modules/course_commerce/course_commerce.module, line 338

Code

function course_commerce_enroll_user_in_ordered_courses(Order $order) {
  foreach ($order
    ->getItems() as $order_item) {
    $product = $order_item
      ->getPurchasedEntity();
    $result = Drupal::entityQuery('course')
      ->condition('commerce_product', $product
      ->id())
      ->execute();
    $course = Course::load(reset($result));

    // Load a different user if purchasing a course for another user.
    // @todo for commerce, not sure where we put this yet
    if (!empty($order_item
      ->getData('uid'))) {
      $account = User::load($order_item
        ->getData('uid'));
    }
    else {
      $account = $order
        ->getCustomer();
    }
    $course_enrollment = $course
      ->enroll($account, [
      'enrollmenttype' => 'commerce',
    ]);

    // Fill out questions
    if (!empty($data['course_enrollment'])) {

      // Attach enrollment bundle fields.
      foreach ($data['course_enrollment'] as $field => $value) {
        $course_enrollment->{$field} = $value;
      }
      $course_enrollment
        ->save();
    }
    if ($course = course_determine_context('commerce', $course
      ->id())) {

      // This product is also a course object, other than the first one.
      // Satisfy it!
      $courseObjects = $course
        ->getObjects();
      foreach ($course
        ->getObjects() as $courseObject) {
        if ($courseObject
          ->getComponent() == 'commerce' && $courseObject
          ->getInstanceId() == $course
          ->id()) {

          // Found the course object that matched the instance (product).
          $courseObject
            ->getFulfillment($account)
            ->setComplete(TRUE)
            ->save();
        }
      }
    }
  }
}