76 lines
2.7 KiB
PHP
76 lines
2.7 KiB
PHP
<?php
|
|
|
|
namespace Komponent\Component\Testquestions\Administrator\Model;
|
|
|
|
defined('_JEXEC') or die;
|
|
|
|
use Joomla\CMS\Factory;
|
|
use Joomla\CMS\MVC\Model\BaseDatabaseModel;
|
|
|
|
class ResultModel extends BaseDatabaseModel
|
|
{
|
|
public function getItem($pk = null)
|
|
{
|
|
$id = (int) ($pk ?: Factory::getApplication()->getInput()->getInt('id'));
|
|
$db = Factory::getContainer()->get('DatabaseDriver');
|
|
$item = $db->setQuery(
|
|
$db->getQuery(true)
|
|
->select(['r.*', 's.title AS set_title', 'sub.title AS subject_title'])
|
|
->from($db->quoteName('#__testquestions_results', 'r'))
|
|
->leftJoin($db->quoteName('#__testquestions_sets', 's') . ' ON s.id = r.set_id')
|
|
->leftJoin($db->quoteName('#__testquestions_subjects', 'sub') . ' ON sub.id = s.subject_id')
|
|
->where('r.id = ' . $id)
|
|
)->loadObject();
|
|
|
|
if (!$item) {
|
|
return null;
|
|
}
|
|
|
|
$item->answers = json_decode((string) $item->answers, true) ?: [];
|
|
$ids = array_map('intval', array_keys($item->answers));
|
|
$item->questions = [];
|
|
|
|
if ($ids) {
|
|
$item->questions = $db->setQuery(
|
|
$db->getQuery(true)
|
|
->select(['id', 'question_type', 'question', 'answer_a', 'answer_b', 'answer_c', 'answer_d', 'answer_open', 'correct_answer', 'points'])
|
|
->from($db->quoteName('#__testquestions_questions'))
|
|
->where('id IN (' . implode(',', $ids) . ')')
|
|
)->loadObjectList('id');
|
|
}
|
|
|
|
return $item;
|
|
}
|
|
|
|
public function saveAssessment(int $id, array $awardedPoints, array $comments): bool
|
|
{
|
|
$item = $this->getItem($id);
|
|
|
|
if (!$item) {
|
|
return false;
|
|
}
|
|
|
|
foreach ($item->answers as $questionId => &$answer) {
|
|
$key = (string) $questionId;
|
|
$maxPoints = (int) ($item->questions[(int) $questionId]->points ?? 0);
|
|
$answer['awarded_points'] = min($maxPoints, max(0, (int) ($awardedPoints[$key] ?? 0)));
|
|
$answer['comment'] = trim((string) ($comments[$key] ?? ''));
|
|
}
|
|
unset($answer);
|
|
|
|
$correctionPoints = 0;
|
|
foreach ($item->answers as $answer) {
|
|
$correctionPoints += (int) ($answer['awarded_points'] ?? 0);
|
|
}
|
|
|
|
$db = Factory::getContainer()->get('DatabaseDriver');
|
|
$row = (object) [
|
|
'id' => $id,
|
|
'answers' => json_encode($item->answers, JSON_UNESCAPED_UNICODE),
|
|
'points_after' => (int) $item->points_before + $correctionPoints,
|
|
];
|
|
|
|
return (bool) $db->updateObject('#__testquestions_results', $row, 'id');
|
|
}
|
|
}
|