Passed
Push — master ( f5e02c...2a0dcd )
by Nícollas
01:54
created

CRUD   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 28
dl 0
loc 51
rs 10
c 0
b 0
f 0
wmc 9

2 Methods

Rating   Name   Duplication   Size   Complexity  
A delete() 0 8 2
B update() 0 28 7
1
<?php
2
3
namespace SimplePHP\Model;
4
5
trait CRUD {
6
7
    /**
8
     * @param int $primary
9
     * @return bool
10
     */
11
    public function delete(int $primary): ?bool
12
    {
13
        try {
14
            $sql = $this->conn->prepare("DELETE FROM {$this->table} WHERE {$this->primary} = :primary");
15
            $sql->bindParam(':primary', $primary);
16
            return $sql->execute();
17
        } catch(PDOException $exception) {
0 ignored issues
show
Bug introduced by
The type SimplePHP\Model\PDOException was not found. Did you mean PDOException? If so, make sure to prefix the type with \.
Loading history...
18
            return null;
19
        }
20
    }
21
22
    /**
23
     * @param string $params
24
     * @param array $values
25
     * @param int $primary
26
     * @return bool
27
     */
28
    public function update(String $params, Array $values, Int $primary): bool
29
    {
30
        $params = explode(',', $params);
31
        $data = [];
32
        $countParams = count($params);
33
        for($i = 0; $i < $countParams; $i++) {
34
            $data[$i] = ":".$params[$i][0].$params[$i][1].$params[$i][2].", ";
35
        }
36
        $result = '';
37
        $final = array_map(null, $params, $data);
38
        foreach($final as $key => $vals) {
39
            foreach($vals as $chave => $val) {
40
                $result .= str_replace(':', ' = :', $val);
41
            }
42
        }
43
        $result = rtrim($result, ', ');
44
        $sql = $this->conn->prepare("UPDATE {$this->table} SET {$result} WHERE {$this->primary} = '{$primary}'");
45
        for($i = 0; $i < $countParams; $i++) {
46
            $data[$i] = ":".$params[$i][0].$params[$i][1].$params[$i][2];
47
        }
48
        $countData = count($data);
49
        for($i = 0; $i < $countData; $i++) {
50
            $sql->bindParam($data[$i], $values[$i]);
51
        }
52
        if($sql->execute()) {
53
            return true;
54
        } else {
55
            return false;
56
        }
57
    }
58
}