You are here

public function OpignoModule::getModuleAttempts in Opigno module 8

Same name and namespace in other branches
  1. 3.x src/Entity/OpignoModule.php \Drupal\opigno_module\Entity\OpignoModule::getModuleAttempts()

Get loaded statuses for specified user.

2 calls to OpignoModule::getModuleAttempts()
OpignoModule::getBestScore in src/Entity/OpignoModule.php
Get module attempt if user didn't finish training.
OpignoModule::getUserScore in src/Entity/OpignoModule.php
Implements opigno_module_get_user_module_score().

File

src/Entity/OpignoModule.php, line 419

Class

OpignoModule
Defines the Module entity.

Namespace

Drupal\opigno_module\Entity

Code

public function getModuleAttempts(AccountInterface $user, $range = NULL, $latest_cert_date = NULL, $finished = FALSE) {
  $key = $this
    ->id() . '_' . $user
    ->id();
  $key_base = $key;
  if (isset($range)) {
    $key .= '_' . $range;
  }
  if (array_key_exists($key, $this->userAttempts)) {
    return $this->userAttempts[$key];
  }
  $status_storage = static::entityTypeManager()
    ->getStorage('user_module_status');
  $query = $status_storage
    ->getQuery();
  $query
    ->condition('module', $this
    ->id())
    ->condition('user_id', $user
    ->id());
  if ($finished) {
    $query
      ->condition('finished', 0, '>');
  }
  if ($latest_cert_date) {
    $query
      ->condition('started', $latest_cert_date, '>=');
  }
  $status_ids = $query
    ->execute();
  if ($status_ids) {
    $status_entities = $status_storage
      ->loadMultiple($status_ids);
    $this->userAttempts[$key_base] = $status_entities;

    // Figure out the 'last' and 'best' scores in PHP to avoid running three
    // queries for potentially the same entity.
    $max_id = max(array_keys($status_ids));
    $this->userAttempts[$key_base . '_last'] = [
      $max_id => $status_entities[$max_id],
    ];
    $max_score = 0;
    $best_entity = FALSE;
    foreach ($status_entities as $entity) {
      if ($entity
        ->getScore() >= $max_score) {
        $max_score = $entity
          ->getScore();
        $best_entity = $entity;
      }
    }
    if (!$best_entity) {
      $this->userAttempts[$key_base . '_best'] = [];
    }
    else {
      $this->userAttempts[$key_base . '_best'] = [
        $best_entity
          ->id() => $best_entity,
      ];
    }
  }
  else {
    $this->userAttempts[$key_base . '_best'] = [];
    $this->userAttempts[$key_base . '_last'] = [];
  }
  return isset($this->userAttempts[$key]) ? $this->userAttempts[$key] : [];
}