/**
  * Function to create a question.
  *
  * @param questionnaire $questionnaire
  * @param array|stdClass $record
  * @param array|stdClass $data - accompanying data for question - e.g. choices
  * @return \mod_questionnaire\question\base the question object
  */
 public function create_question(questionnaire $questionnaire, $record = null, $data = null)
 {
     global $DB;
     // Increment the question count.
     $this->questioncount++;
     $record = (array) $record;
     $record['position'] = count($questionnaire->questions);
     if (!isset($record['survey_id'])) {
         throw new coding_exception('survey_id must be present in phpunit_util::create_question() $record');
     }
     if (!isset($record['name'])) {
         throw new coding_exception('name must be present in phpunit_util::create_question() $record');
     }
     if (!isset($record['type_id'])) {
         throw new coding_exception('typeid must be present in phpunit_util::create_question() $record');
     }
     if (!isset($record['content'])) {
         $record['content'] = 'Random ' . $this->type_str($record['type_id']) . ' ' . uniqid();
     }
     // Get question type.
     $typeid = $record['type_id'];
     if ($typeid === QUESRATE && !isset($record['length'])) {
         $record['length'] = 5;
     }
     if ($typeid !== QUESPAGEBREAK && $typeid !== QUESSECTIONTEXT) {
         $qtype = $DB->get_record('questionnaire_question_type', ['id' => $typeid]);
         if (!$qtype) {
             throw new coding_exception('Could not find question type with id ' . $typeid);
         }
         // Throw an error if this requires choices and it hasn't got them.
         $this->validate_question($qtype->typeid, $data);
     }
     $record = (object) $record;
     // Add the question.
     $record->id = $DB->insert_record('questionnaire_question', $record);
     $typename = \mod_questionnaire\question\base::qtypename($record->type_id);
     $question = questionnaire::question_factory($typename, $record->id, $record);
     // Add the question choices if required.
     if ($typeid !== QUESPAGEBREAK && $typeid !== QUESSECTIONTEXT) {
         if ($question->has_choices()) {
             $this->add_question_choices($question, $data);
             $record->opts = $data;
         }
     }
     // Update questionnaire.
     $questionnaire->add_questions();
     return $question;
 }