You are here

function _opigno_tincan_learning_path_create_and_send_training_statements in Opigno TinCan API 8

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

Creates and sends training statement.

1 call to _opigno_tincan_learning_path_create_and_send_training_statements()
opigno_tincan_learning_path_user_module_status_presave in modules/opigno_tincan_learning_path/opigno_tincan_learning_path.module
Implements hook_ENTITY_TYPE_presave().

File

modules/opigno_tincan_learning_path/opigno_tincan_learning_path.module, line 73
Contains opigno_tincan_learning_path.module.

Code

function _opigno_tincan_learning_path_create_and_send_training_statements($gid, $cid, $steps, $user) {

  /****
   * - When user finish a training
   * Actor: user
   * Verb: xAPI/passed || xAPI/failed
   * Object: xAPI/course
   * Result: Get final training result
   * Context: Class if there is one
   */

  // Get group entity.
  $group = Group::load($gid);

  // Know if the user has passed or failed this Learning Path.
  $is_passed = opigno_learning_path_is_passed($group, $user
    ->id());

  // Statement creation.
  $statement = OpignoTinCanApiStatements::statementBaseCreation($is_passed ? OpignoTincanApiTinCanVerbs::$passed : OpignoTincanApiTinCanVerbs::$failed, OpignoTincanApiTinCanActivityDefinitionTypes::$course, $group);
  if ($statement === FALSE) {
    return;
  }

  // Context creation.
  $context = new Context();

  // Get classes if exits.
  $classes = $group
    ->getContent('subgroup:opigno_class');
  if (!empty($classes)) {

    // Set parents if exist.
    $parent_ids = [];
    foreach ($classes as $cid => $class) {
      $class_entity = $class
        ->getEntity();
      $parent_ids[] = $class_entity
        ->id();
    }
    OpignoTinCanApiStatements::contextSetGrouping($context, $parent_ids);
  }

  // Set language in context.
  OpignoTinCanApiStatements::contextSetLanguage($context, $group
    ->language()
    ->getId());

  // Get duration, user_score.
  $duration_s = NULL;
  $user_score = 0;
  foreach ($steps as $step) {
    $duration_s += intval($step['time spent']);
    $user_score += intval($step['best score']);
  }

  // Set user_score in persents.
  $user_score = round($user_score / count($steps));

  // Raw score can not be negative.
  $user_score = $user_score > 0 ? $user_score : 0;

  // Set result.
  $response = NULL;
  OpignoTinCanApiStatements::setResult($statement, $user_score, 100, NULL, $is_passed, $response, $duration_s);

  // Set statement context.
  $statement
    ->setContext($context);

  // Send statements for certificate if exits.
  _opigno_tincan_learning_path_send_statemets_certificate($group);

  // Sending statement.
  OpignoTinCanApiStatements::sendStatement($statement);
}