Completed
Push — master ( ac011d...56c397 )
by Mikołaj
03:19
created

ExamController::showAction()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 39
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 39
rs 8.439
cc 5
eloc 23
nc 7
nop 1
1
<?php
2
3
namespace Egzaminer\Controller;
4
5
use Egzaminer\Exam\CalculateScore;
6
use Egzaminer\Exam\CompareUserAnswersWithQuestions;
7
use Egzaminer\Model\AnswersModel;
8
use Egzaminer\Model\ExamModel;
9
use Egzaminer\Model\QuestionsModel;
10
use Exception;
11
12
class ExamController extends AbstractController
13
{
14
    /**
15
     * Exam page with questions.
16
     *
17
     * GET /exam/[i:id]
18
     *
19
     * @param int $examID Exam ID
20
     *
21
     * @return void
22
     */
23
    public function showAction($examID)
24
    {
25
        $examInfo = (new ExamModel($this->get('dbh')))->getInfo($examID);
26
27
        if (false === $examInfo) {
28
            throw new Exception('Exam not exists!');
29
        }
30
31
        $questions = (new QuestionsModel($this->get('dbh')))->getByExamId($examID);
32
        $answers = (new AnswersModel($this->get('dbh')))->getAnswersByQuestions($questions);
33
34
        // if form was send
35
        if (!empty($this->getFromRequest('post'))) {
36
            $compareAnswers = new CompareUserAnswersWithQuestions(
37
                $this->getFromRequest('post'),
38
                $questions
39
            );
40
            $questions = $compareAnswers->getCompared();
41
42
            $score = new CalculateScore($examInfo, $questions);
43
            $scoreInfo = $score->getScoreInfo();
44
        } else {
45
            $scoreInfo = null;
46
        }
47
48
        // put answers to questions
49
        foreach ($questions as $qkey => $qvalue) {
50
            foreach ($answers[$qvalue['id']] as $akey => $avalue) {
51
                $questions[$qkey]['answers'][] = $avalue;
52
            }
53
        }
54
55
        $this->render('front/exam', [
56
            'title'     => $examInfo['title'],
57
            'exam'      => $examInfo,
58
            'questions' => $questions,
59
            'score'     => $scoreInfo,
60
        ]);
61
    }
62
}
63