TrueFalseActivityAnswer.php in Opigno module 8
File
src/Plugin/ActivityAnswer/TrueFalseActivityAnswer.php
View source
<?php
namespace Drupal\opigno_module\Plugin\ActivityAnswer;
use Drupal\opigno_module\ActivityAnswerPluginBase;
use Drupal\opigno_module\Entity\OpignoActivityInterface;
use Drupal\opigno_module\Entity\OpignoAnswerInterface;
class TrueFalseActivityAnswer extends ActivityAnswerPluginBase {
public function evaluatedOnSave(OpignoActivityInterface $activity) {
return TRUE;
}
public function getScore(OpignoAnswerInterface $answer) {
$db_connection = \Drupal::service('database');
$score = 0;
$activity = $answer
->getActivity();
if ($answer
->hasField('field_true_false') && $activity
->hasField('field_true_false') && $answer
->get('field_true_false')->value == $activity
->get('field_true_false')->value) {
$module = $answer
->getModule();
$score_query = $db_connection
->select('opigno_module_relationship', 'omr')
->fields('omr', [
'max_score',
])
->condition('omr.parent_id', $module
->id())
->condition('omr.parent_vid', $module
->getRevisionId())
->condition('omr.child_id', $activity
->id())
->condition('omr.child_vid', $activity
->getRevisionId());
$score_result = $score_query
->execute()
->fetchObject();
if ($score_result) {
$score = $score_result->max_score;
}
}
return $score;
}
public function getAnswerResultItemHeaders(OpignoAnswerInterface $answer) {
return [
$this
->t('Your answer'),
$this
->t('Choice'),
$this
->t('Correct?'),
];
}
public function getAnswerResultItemData(OpignoAnswerInterface $answer) {
$data = [];
$user_answer = $answer
->hasField('field_true_false') ? $answer
->get('field_true_false')->value : NULL;
$activity = $answer
->getActivity();
$correct_answer = $activity
->hasField('field_true_false') ? $activity
->get('field_true_false')->value : NULL;
$data[] = [
'answer' => $user_answer !== NULL && $user_answer == 1 ? '->' : '',
'choice' => $this
->t('True'),
'correct' => $correct_answer !== NULL && $correct_answer == 1 ? '+' : '',
];
$data[] = [
'answer' => $user_answer !== NULL && $user_answer == 0 ? '->' : '',
'choice' => t('False'),
'correct' => $correct_answer !== NULL && $correct_answer == 0 ? '+' : '',
];
return $data;
}
}