You are here

function opigno_tincan_courses_user_module_status_presave in Opigno TinCan API 8

Same name and namespace in other branches
  1. 3.x modules/opigno_tincan_courses/opigno_tincan_courses.module \opigno_tincan_courses_user_module_status_presave()

Implements hook_ENTITY_TYPE_presave().

Throws

\Exception

File

modules/opigno_tincan_courses/opigno_tincan_courses.module, line 40
Contains opigno_tincan_courses.module.

Code

function opigno_tincan_courses_user_module_status_presave(EntityInterface $entity) {

  // Check if Tincan PHP library is installed.
  $has_library = opigno_tincan_api_tincanphp_is_installed();
  if (!$has_library) {
    return;
  }
  $route = \Drupal::routeMatch();

  // Must work only after user answer on all questions.
  if ($route
    ->getRouteName() == 'opigno_module.take_module') {

    /* @var $user_module_status UserModuleStatus */
    $user_module_status = $entity;
    $is_finished = $user_module_status
      ->get('finished')
      ->getValue()[0]['value'];
    if (!$is_finished) {

      // Module is not finished yet.
      return;
    }

    // Get training context.
    $gid = OpignoGroupContext::getCurrentGroupId();
    $cid = OpignoGroupContext::getCurrentGroupContentId();
    if (!$gid || !$cid) {
      return;
    }
    $user = \Drupal::currentUser();

    // Load group steps.
    $group_steps = opigno_learning_path_get_steps($gid, $user
      ->id());

    // Load group courses substeps.
    array_walk($group_steps, function ($step) use ($cid, $user, $gid) {
      if ($step['typology'] === 'Course') {
        $course_steps = opigno_learning_path_get_steps($step['id'], $user
          ->id());

        // Last course module.
        $last_course_step = end($course_steps);
        if ($last_course_step['cid'] == $cid) {
          _opigno_tincan_courses_create_and_send_course_statements($gid, $step);
        }
      }
    });
  }
  return $entity;
}