QuestionEditModel   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 8
c 0
b 0
f 0
lcom 1
cbo 1
dl 0
loc 50
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A edit() 0 5 2
A editQuestion() 0 26 4
A editAnswers() 0 14 2
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