QuestionEditModel::editQuestion()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 26
rs 9.504
c 0
b 0
f 0
cc 4
nc 4
nop 4
1
<?php
2
3
namespace Egzaminer\Model;
4
5
use PDO;
6
7
class QuestionEditModel extends AbstractModel
8
{
9
    public function edit(int $questionID, array $post, array $thumbUpload, string $rootDir): bool
10
    {
11
        return $this->editQuestion($questionID, $post['question'], $thumbUpload, $rootDir)
12
        && $this->editAnswers($post['answers']);
13
    }
14
15
    private function editQuestion(int $questionID, array $question, array $thumbUpload, string $rootDir)
16
    {
17
        $stmt = $this->db->prepare('UPDATE questions SET content = :content,
18
            correct = :correct WHERE id = :id');
19
        $stmt->bindValue(':content', trim($question['content']));
20
        $stmt->bindValue(':correct', $question['correct'], PDO::PARAM_INT);
21
        $stmt->bindValue(':id', $questionID, PDO::PARAM_INT);
22
        $status = $stmt->execute();
23
24
        if (isset($question['delete-img'])) {
25
            array_map('unlink', glob($rootDir.'/public/storage/'.$questionID.'_*'));
26
            $stmt = $this->db->prepare('UPDATE questions SET image = \'\' WHERE id = ?');
27
            $stmt->execute([$questionID]);
28
        } elseif (!empty($thumbUpload['name'])) {
29
            if (is_uploaded_file($thumbUpload['tmp_name'])) {
30
                array_map('unlink', glob($rootDir.'/public/storage/'.$questionID.'_*'));
31
                $file = $rootDir.'/public/storage/'.$questionID.'_'.$thumbUpload['name'];
32
                move_uploaded_file($thumbUpload['tmp_name'], $file);
33
            }
34
35
            $stmt = $this->db->prepare('UPDATE questions SET image = ? WHERE id = ?');
36
            $stmt->execute([$thumbUpload['name'], $questionID]);
37
        }
38
39
        return $status;
40
    }
41
42
    private function editAnswers(array $answers): bool
43
    {
44
        $stmt = $this->db->prepare('UPDATE answers SET content = :content
45
            WHERE id = :id');
46
        $this->db->beginTransaction();
47
48
        foreach ($answers as $key => $value) {
49
            $stmt->bindValue(':content', trim($value));
50
            $stmt->bindValue(':id', $key, PDO::PARAM_INT);
51
            $stmt->execute();
52
        }
53
54
        return $this->db->commit();
55
    }
56
}
57