You are here

public function OpignoModule::getRandomActivity in Opigno module 8

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

Returns random activity.

File

src/Entity/OpignoModule.php, line 743

Class

OpignoModule
Defines the Module entity.

Namespace

Drupal\opigno_module\Entity

Code

public function getRandomActivity(UserModuleStatusInterface $attempt) {

  // Need to get activity that was not answered yet in this attempt.
  // Take all the activities.
  $activities = $this
    ->getModuleActivities();
  $activities_storage = static::entityTypeManager()
    ->getStorage('opigno_activity');
  $randomization = $this
    ->getRandomization();
  $random_count = $this
    ->getRandomActivitiesCount();
  $answered_random = 0;

  // Take answers within attempt.
  $user_answers = $this
    ->userAnswers(\Drupal::currentUser(), $attempt);
  if (!empty($user_answers)) {
    foreach ($user_answers as $answer) {
      $answer_activity = $answer
        ->getActivity();

      // Unset answered activity if answer already exist.
      if (isset($activities[$answer_activity
        ->id()])) {
        if ($randomization == 2) {
          $answered_random++;
        }
        unset($activities[$answer_activity
          ->id()]);
      }
    }
  }
  if ($randomization == 2) {
    $assigned_random = $activities;
    $activities = [];
    if (!empty($assigned_random) && $random_count > $answered_random) {
      $required_random = $random_count - $answered_random;
      $random_activities = array_rand($assigned_random, $required_random);
      if (is_array($random_activities)) {
        foreach ($random_activities as $random_activity) {
          $activities[$random_activity] = $assigned_random[$random_activity];
        }
      }
      else {
        $activities[$random_activities] = $assigned_random[$random_activities];
      }
    }
  }
  return !empty($activities) ? $activities_storage
    ->load(array_rand($activities, 1)) : FALSE;
}