1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Egzaminer\Model; |
4
|
|
|
|
5
|
|
|
use PDO; |
6
|
|
|
|
7
|
|
|
class QuestionAddModel extends AbstractModel |
8
|
|
|
{ |
9
|
|
|
public function add(int $examID, array $post): int |
10
|
|
|
{ |
11
|
|
|
if (!isset($post['question']['correct'])) { |
12
|
|
|
$post['question']['correct'] = 0; |
13
|
|
|
} |
14
|
|
|
$qid = $this->addQuestion($examID, $post['question']); |
15
|
|
|
$cid = $this->addAnswers($examID, $qid, $post['question']['correct'], $post['answers']); |
16
|
|
|
$this->addCorrectAnswerToQuestion($qid, $cid); |
17
|
|
|
|
18
|
|
|
return $qid; |
19
|
|
|
} |
20
|
|
|
|
21
|
|
View Code Duplication |
private function addQuestion(int $examID, array $question): int |
|
|
|
|
22
|
|
|
{ |
23
|
|
|
$stmt = $this->db->prepare('INSERT INTO questions (exam_id, content) |
24
|
|
|
VALUES (:exam_id, :content)'); |
25
|
|
|
$stmt->bindValue(':exam_id', $examID, PDO::PARAM_INT); |
26
|
|
|
$stmt->bindValue(':content', trim($question['content'])); |
27
|
|
|
$stmt->execute(); |
28
|
|
|
|
29
|
|
|
return $this->db->lastInsertId(); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
View Code Duplication |
private function addCorrectAnswerToQuestion(int $questionID, int $correct): bool |
|
|
|
|
33
|
|
|
{ |
34
|
|
|
$stmt = $this->db->prepare('UPDATE questions SET correct = :correct |
35
|
|
|
WHERE id = :id'); |
36
|
|
|
$stmt->bindValue(':correct', $correct, PDO::PARAM_INT); |
37
|
|
|
$stmt->bindValue(':id', $questionID, PDO::PARAM_INT); |
38
|
|
|
|
39
|
|
|
return $stmt->execute(); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
private function addAnswers(int $examID, int $questionID, int $correct, array $answers): int |
43
|
|
|
{ |
44
|
|
|
$stmt = $this->db->prepare('INSERT INTO answers (exam_id, question_id, content) |
45
|
|
|
VALUES (:exam_id, :question_id, :content) |
46
|
|
|
'); |
47
|
|
|
$this->db->beginTransaction(); |
48
|
|
|
|
49
|
|
|
foreach ($answers as $key => $value) { |
50
|
|
|
$stmt->bindValue(':exam_id', $examID, PDO::PARAM_INT); |
51
|
|
|
$stmt->bindValue(':question_id', $questionID, PDO::PARAM_INT); |
52
|
|
|
$stmt->bindValue(':content', trim($value)); |
53
|
|
|
$stmt->execute(); |
54
|
|
|
|
55
|
|
|
if ($correct === $key) { |
56
|
|
|
$correctId = $this->db->lastInsertId(); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
if (!isset($correctId)) { |
61
|
|
|
$correctId = 0; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
$this->db->commit(); |
65
|
|
|
|
66
|
|
|
return $correctId; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.