@param SelectionQuestion $question

@return array
163724
public function expectAnswer(AbstractItem $question)
    {
        switch ($question->getMode()) {
           case $question::MODE_FIND:
               $selections = $question->getSelections()->toArray();

               return array_filter($selections, function ($selection) {
                   return $selection->getScore() > 0;
               });
           case $question::MODE_SELECT:
              $selections = $question->getSelections()->toArray();

              return array_filter($selections, function ($selection) {
                  return $selection->getScore() > 0;
              });
           case $question::MODE_HIGHLIGHT:
               return array_map(function (Selection $selection) {
                   $best = null;
                   $bestScore = 0;

                   foreach ($selection->getColorSelections() as $colorSelection) {
                       if ($colorSelection->getScore() > $bestScore) {
                           $bestScore = $colorSelection->getScore();
                           $best = $colorSelection;
                       }
                   }

                   return $best;
               }, $question->getSelections()->toArray());
        }
    }
1006900
public function getRandomQuestions($category, $limit, $questionsLevel = array(), $excludeQuestions = array())
    {
        $query = $this->createQueryBuilder('q')
            ->addSelect('RAND() as HIDDEN rand, q, c, a')
            ->leftJoin('q.category', 'c')
            ->leftJoin('q.answers', 'a')
            ->where('q.category = :category')
            ->andWhere('q.enabled = 1')
            ->setParameter('category', $category)
            ->orderBy('rand');

        if (!empty($questionsLevel)) {
            $query->andWhere('q.level IN(:level)')
                ->setParameter('level', $questionsLevel);
        }

        if (!empty($excludeQuestions)) {
            $query->andWhere('q.id NOT IN(:questions)')
                ->setParameter('questions', $excludeQuestions);
        }

        $questions = array_slice($query->getQuery()->getResult(), 0, $limit);

        return $questions;
    }
815271
protected function validateSolutions(array $question)
    {
        $errors = [];

        // check solution IDs are consistent with cells IDs
        $cellIds = array_map(function (array $cell) {
            return $cell['id'];
        }, $question['cells']);

        foreach ($question['solutions'] as $index => $solution) {
            if (!in_array($solution['cellId'], $cellIds)) {
                $errors[] = [
                    'path' => "/solutions[{$index}]",
                    'message' => "id {$solution['cellId']} doesn't match any cell id",
                ];
            }
            // Validates cell choices
            $errors = array_merge(
              $errors,
              $this->keywordValidator->validateCollection($solution['answers'], [Validation::NO_SCHEMA, Validation::VALIDATE_SCORE])
            );
        }

        return $errors;
    }
809610
private function deserializeChoices(BooleanQuestion $question, array $choices, array $solutions, array $options = [])
    {
        $choiceEntities = $question->getChoices()->toArray();

        foreach ($choices as $choiceData) {
            $choice = null;

            // Searches for an existing choice entity.
            foreach ($choiceEntities as $entityIndex => $entityChoice) {
                /** @var BooleanChoice $entityChoice */
                if ($entityChoice->getUuid() === $choiceData['id']) {
                    $choice = $entityChoice;
                    unset($choiceEntities[$entityIndex]);
                    break;
                }
            }

            $choice = $choice ?: new BooleanChoice();
            $choice->setUuid($choiceData['id']);

            // Deserialize choice content
            $choice = $this->contentSerializer->deserialize($choiceData, $choice, $options);

            // Set choice score and feedback
            $choice->setScore(0);

            foreach ($solutions as $solution) {
                if ($solution['id'] === $choiceData['id']) {
                    $choice->setScore($solution['score']);

                    if (isset($solution['feedback'])) {
                        $choice->setFeedback($solution['feedback']);
                    }

                    break;
                }
            }

            $question->addChoice($choice);
        }

        // Remaining choices are no longer in the Question
        foreach ($choiceEntities as $choiceToRemove) {
            $question->removeChoice($choiceToRemove);
        }
    }
1169757
protected function get_array_of_choices($question) {
        $subquestions = $question->options->answers;
        $count = 0;
        foreach ($subquestions as $key => $subquestion) {
            $answers[$count]['id'] = $subquestion->id;
            $answers[$count]['answer'] = $subquestion->answer;
            $answers[$count]['fraction'] = $subquestion->fraction;
            $answers[$count] += $this->feedback_to_choice_options($subquestion->feedback);
            $answers[$count]['choice'] = $count + 1;
            ++$count;
        }
        return $answers;
    }
1225507
public function askWithCompletion($question, array $choices, $default = null, $attempts = null, $strict = false)
    {
        $question = new Question($question, $default);
        $question->setMaxAttempts($attempts)->setAutocompleterValues($choices);

        if ($strict) {
            $question->setValidator(function($result) use ($choices) {
                if (!in_array($result, $choices)) {
                    throw new \InvalidArgumentException(sprintf(
                        'The provided answer is ambiguous. Value should be one of %s',
                        implode(' or ', $choices)));
                }

                return $result;
            });
        }

        return $this->askQuestion($question);
    }
453918
public function choose($question, array $options, $default, $error_message)
	{
		/** @var QuestionHelper $helper */
		$helper = $this->_helperSet->get('question');
		$choice_question = new ChoiceQuestion('<question>' . $question . '</question> ', $options, $default);
		$choice_question->setErrorMessage($error_message);

		return $helper->ask($this->_input, $this->_output, $choice_question);
	}
519891
protected function select(string $question, array $options): int
	{
		return (new Select($this->input, $this->output))->ask($question, $options);
	}
621674
protected function get_correct_answers($question) {
        $arrayofchoices = $this->get_array_of_choices($question);
        $arrayofplaceholdeers = $this->get_array_of_placeholders($question);

        $correctplayers = array();
        foreach ($arrayofplaceholdeers as $ph) {
            foreach ($arrayofchoices as $key => $choice) {
                if ($key + 1 == $ph) {
                    $correctplayers[] = $choice;
                }
            }
        }
        return $correctplayers;
    }
1039425
private function serializeTags(Item $question)
    {
        $event = new GenericDataEvent([
            'class' => Item::class,
            'ids' => [$question->getUuid()],
        ]);
        $this->eventDispatcher->dispatch('claroline_retrieve_used_tags_by_class_and_ids', $event);

        return $event->getResponse();
    }
1181982
private function pullQuestion($questionId, array $questions, array $decodedQuestions = [])
    {
        if (empty($decodedQuestions[$questionId])) {
            foreach ($questions as $index => $question) {
                if ($question->getId() === (int) $questionId && !empty($question->getMimeType())) {
                    $decodedQuestions[$questionId] = $this->itemSerializer->serialize($question, [Transfer::INCLUDE_SOLUTIONS]);
                    unset($questions[$index]);
                    break;
                }
            }
        }

        return !empty($decodedQuestions[$questionId]) ? $decodedQuestions[$questionId] : null;
    }
1293171
public function process_matching($quest, &$questions) {

        // Blackboard matching questions can't be imported in core Moodle without a loss in data,
        // as core match question don't allow HTML in subanswers. The contributed ddmatch
        // question type support HTML in subanswers.
        // The ddmatch question type is not part of core, so we need to check if it is defined.
        $ddmatchisinstalled = question_bank::is_qtype_installed('ddmatch');

        $question = $this->process_common($quest);
        $question = $this->add_blank_combined_feedback($question);
        $question->valid = true;
        if ($ddmatchisinstalled) {
            $question->qtype = 'ddmatch';
        } else {
            $question->qtype = 'match';
        }
        // Construction of the array holding mappings between subanswers and subquestions.
        foreach ($quest->RESPONSE_BLOCK->subquestions as $qid => $subq) {
            foreach ($quest->responses as $rid => $resp) {
                if (isset($resp->ident) && $resp->ident == $subq->ident) {
                    $correct = $resp->correct;
                }
            }

            foreach ($subq->choices as $cid => $choice) {
                if ($choice == $correct) {
                    $mappings[$subq->ident] = $cid;
                }
            }
        }

        foreach ($subq->choices as $choiceid => $choice) {
            $subanswertext = $quest->RIGHT_MATCH_BLOCK->matchinganswerset[$choiceid]->text;
            if ($ddmatchisinstalled) {
                $subanswer = $this->cleaned_text_field($subanswertext);
            } else {
                $subanswertext = html_to_text($this->cleaninput($subanswertext), 0);
                $subanswer = $subanswertext;
            }

            if ($subanswertext != '') { // Only import non empty subanswers.
                $subquestion = '';

                $fiber = array_keys ($mappings, $choiceid);
                foreach ($fiber as $correctanswerid) {
                    // We have found a correspondance for this subanswer so we need to take the associated subquestion.
                    foreach ($quest->RESPONSE_BLOCK->subquestions as $qid => $subq) {
                        $currentsubqid = $subq->ident;
                        if (strcmp ($currentsubqid, $correctanswerid) == 0) {
                            $subquestion = $subq->text;
                            break;
                        }
                    }
                    $question->subquestions[] = $this->cleaned_text_field($subquestion);
                    $question->subanswers[] = $subanswer;
                }

                if ($subquestion == '') { // Then in this case, $choice is a distractor.
                    $question->subquestions[] = $this->text_field('');
                    $question->subanswers[] = $subanswer;
                }
            }
        }

        // Verify that this matching question has enough subquestions and subanswers.
        $subquestioncount = 0;
        $subanswercount = 0;
        $subanswers = $question->subanswers;
        foreach ($question->subquestions as $key => $subquestion) {
            $subquestion = $subquestion['text'];
            $subanswer = $subanswers[$key];
            if ($subquestion != '') {
                $subquestioncount++;
            }
            $subanswercount++;
        }
        if ($subquestioncount < 2 || $subanswercount < 3) {
                $this->error(get_string('notenoughtsubans', 'qformat_blackboard_six', $question->questiontext));
        } else {
            $questions[] = $question;
        }
    }
766008
public function evaluateQuestion(array $question, PhpStringParser $parser, GeneratorDataObject $generator)
    {
        $iterator       = $this->iteratorValidator->retrieveValidIteration($question, $generator, $parser);
        $iteratorParser = clone $parser;

        foreach ($iterator as $iteration) {
            $iteratorParser->addVariable('iteration', $iteration);

            $origine            = $iteratorParser->parse($question['iteration']['retrieveBy']);
            $responseCollection = new PredefinedResponseCollection();

            foreach ($question['iteration']['response']['predefined'] as $predefinedResponse) {
                $responseCollection->append(
                    new PredefinedResponse(
                        $predefinedResponse['response'],
                        $iteratorParser->parse($predefinedResponse['text']),
                        $predefinedResponse['response']
                    )
                );
            }

            $questionWithPredefinedResponse = new QuestionWithPredefinedResponse(
                $iteratorParser->parse($question['iteration']['text']),
                'set_predefined_' . ucfirst($question['dtoAttribute']) . $origine,
                $responseCollection
            );

            $questionWithPredefinedResponse->setDefaultResponse(
                (isset($question['iteration']['response']['default']) === true) ?
                    $iteratorParser->parse($question['iteration']['response']['default']) : null
            )->setRequired($question['required'])
             ->setResponseType(new QuestionResponseTypeEnum($question['iteration']['response']['type']));

            $response = $this->context->askCollection($questionWithPredefinedResponse);

            $questionName = $question['setter'];
            if ($response !== null) {
                $generator->getDto()->$questionName($origine, $response);
            }
        }

        return $generator;
    }
1280203
public function choice($question, array $choices, $default = null, $attempts = null, $multiple = null)
    {
        $helper = $this->getHelperSet()->get('question');

        $question = new ChoiceQuestion("<question>$question</question> ", $choices, $default);

        $question->setMaxAttempts($attempts)->setMultiselect($multiple);

        return $helper->ask($this->input, $this->output, $question);
    }
502502
private function getCorrectAnswerForSumCellsMode(AbstractItem $question, $answer)
    {
        $corrected = new CorrectedAnswer();

        if (!is_null($answer)) {
            foreach ($answer as $gridAnswer) {
                $cell = $question->getCell($gridAnswer['cellId']);
                $choice = $cell->getChoice($gridAnswer['text']);

                if (!empty($choice)) {
                    if (0 < $choice->getScore()) {
                        $corrected->addExpected($choice);
                    } else {
                        $corrected->addUnexpected($choice);
                    }
                } else {
                    // Retrieve the best answer for the cell
                    $corrected->addMissing($this->findCellExpectedAnswer($cell));
                }
            }
        } else {
            $cells = $question->getCells();

            foreach ($cells as $cell) {
                if ($cell->isInput()) {
                    $corrected->addMissing($this->findCellExpectedAnswer($cell));
                }
            }
        }

        return $corrected;
    }
517695
private function serializeHints(Item $question, array $options = [])
    {
        return array_map(function (Hint $hint) use ($options) {
            return $this->hintSerializer->serialize($hint, $options);
        }, $question->getHints()->toArray());
    }
1117511
public function correctAnswer(AbstractItem $question, $answer = [])
    {
        $corrected = new CorrectedAnswer();

        foreach ($question->getChoices() as $choice) {
            if (is_array($answer) && in_array($choice->getUuid(), $answer)) {
                // Choice has been selected by the user
                if (0 < $choice->getScore()) {
                    $corrected->addExpected($choice);
                } else {
                    $corrected->addUnexpected($choice);
                }
            } elseif (0 < $choice->getScore()) {
                // The choice is not selected but it's part of the correct answer
                $corrected->addMissing($choice);
            } else {
                // The choice is not selected as expected in correct answer
                $corrected->addExpectedMissing($choice);
            }
        }

        return $corrected;
    }