Passed
Push — master ( 2c321e...f12c68 )
by Henri
01:20
created

CrudTrait::delete()   A

Complexity

Conditions 3
Paths 6

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 14
c 1
b 0
f 0
nc 6
nop 2
dl 0
loc 21
rs 9.7998
1
<?php
2
3
namespace HnrAzevedo\Datamanager;
4
5
use HnrAzevedo\Datamanager\DatamanagerException;
6
use Exception;
7
use PDO;
8
9
trait CrudTrait{
10
11
    protected ?DatamanagerException $fail = null;
12
    protected string $lastQuery = '';
13
    protected array $lastData = [];
14
15
    protected function check_fail()
16
    {
17
        if(!is_null($this->fail)){
18
            throw $this->fail;
19
        }
20
    }
21
22
    protected function transaction(string $transaction): ?bool
23
    {
24
        if(array_key_exists($transaction,['begin','commit','rollback'])){
25
            throw new DatamanagerException("{$transaction} é um estado inválido para transações.");
26
        }
27
28
        if(!Connect::getInstance()->inTransaction()){
29
           return Connect::getInstance()->beginTransaction();
30
        }
31
32
        switch ($transaction) {
33
            case 'commit': return Connect::getInstance()->commit();
34
            case 'rollback': return Connect::getInstance()->rollBack();
35
        }
36
        return false;
37
    }
38
39
    protected function select(string $query,array $data): ?array
40
    {
41
        try{
42
            $stmt = Connect::getInstance()->prepare("{$query}");
43
44
            $this->lastQuery = "{$query}";
45
            $this->lastData = $data;
46
47
            $stmt->execute($data);
48
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
49
        }catch(Exception $exception){
50
            $this->fail = new DatamanagerException($exception->getMessage(), $exception->getCode(), $exception);
51
        }
52
        return [];
53
    }
54
55
    protected function describe(): array
56
    {
57
        try{
58
            $stmt = Connect::getInstance()->prepare("DESCRIBE {$this->table}");
59
60
            $this->lastQuery = "DESCRIBE {$this->table}";
61
            $this->lastData = [];
62
63
            $stmt->execute();
64
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
65
        }catch(Exception $exception){
66
            $this->fail = new DatamanagerException($exception->getMessage(), $exception->getCode(), $exception);
67
            return [];
68
        }
69
    }
70
71
    protected function insert(array $data): ?string
72
    {
73
        try {
74
            $columns = implode(", ", array_keys($data));
75
            $values = ":" . implode(", :", array_keys($data));
76
77
            $stmt = Connect::getInstance()->prepare("INSERT INTO {$this->table} ({$columns}) VALUES ({$values})");
78
79
            $dataInsert = $this->filter($data);
80
81
            $this->lastQuery = "INSERT INTO {$this->table} ({$columns}) VALUES ({$values})";
82
            $this->lastData = $dataInsert;
83
84
            $stmt->execute($dataInsert);
85
86
            return Connect::getInstance()->lastInsertId();
87
        } catch (Exception $exception) {
88
            $this->fail = new DatamanagerException($exception->getMessage(), $exception->getCode(), $exception);
89
            return null;
90
        }
91
    }
92
93
    protected function update(array $data, string $terms, string $params): ?int
94
    {
95
        try {
96
            $dateSet = [];
97
            foreach ($data as $bind => $value) {
98
                $dateSet[] = "{$bind} = :{$bind}";
99
            }
100
            $dateSet = implode(", ", $dateSet);
101
102
            parse_str($params, $arr);
103
104
            $dataUpdate = $this->filter(array_merge($data, $arr));
105
106
            $stmt = Connect::getInstance()->prepare("UPDATE {$this->table} SET {$dateSet} WHERE {$terms}");
107
108
            $this->lastQuery = "UPDATE {$this->table} SET {$dateSet} WHERE {$terms}";
109
            $this->lastData = $dataUpdate;
110
111
            $stmt->execute($dataUpdate);
112
113
            return ($stmt->rowCount() ?? 1);
114
        } catch (Exception $exception) {
115
            $this->fail = new DatamanagerException($exception->getMessage(), $exception->getCode(), $exception);
116
            return null;
117
        }
118
    }
119
120
    public function delete(string $terms, ?string $params): bool
121
    {
122
        try {
123
            $stmt = Connect::getInstance()->prepare("DELETE FROM {$this->table} WHERE {$terms}");
124
125
            $this->lastQuery = "DELETE FROM {$this->table} WHERE {$terms}";
126
            $this->lastData = [];
127
128
            if($params){
129
                parse_str($params, $arr);
130
                $this->lastData = $arr;
131
132
                $stmt->execute($arr);
133
                return true;
134
            }
135
136
            $stmt->execute();
137
            return true;
138
        } catch (Exception $exception) {
139
            $this->fail = new DatamanagerException($exception->getMessage(), $exception->getCode(), $exception);
140
            return false;
141
        }
142
    }
143
144
    private function filter(array $data): ?array
145
    {
146
        $filter = [];
147
        foreach ($data as $key => $value) {
148
            $filter[$key] = (is_null($value) ? null : filter_var($value, FILTER_DEFAULT));
149
        }
150
        return $filter;
151
    }
152
153
}
154