Passed
Push — master ( 07917c...07b1c4 )
by Robson
01:22
created

DataLayer::save()   A

Complexity

Conditions 5
Paths 13

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 26
rs 9.4555
cc 5
nc 13
nop 0
1
<?php
2
3
namespace CoffeeCode\DataLayer;
4
5
use PDO;
6
use PDOException;
7
use stdClass;
8
9
class DataLayer
10
{
11
    use CrudTrait;
12
13
    private $entity;
14
    private $primary;
15
    private $required;
16
17
    protected $statement;
18
19
    protected $params;
20
    protected $order;
21
    protected $limit;
22
    protected $offset;
23
24
    protected $fail;
25
    protected $data;
26
27
    public function __construct(string $entity, array $requiredFileds, string $primaryKey = 'id')
28
    {
29
        $this->entity = $entity;
30
        $this->primary = $primaryKey;
31
        $this->required = $requiredFileds;
32
    }
33
34
    public function __set($name, $value)
35
    {
36
        if (empty($this->data)) {
37
            $this->data = new stdClass();
38
        }
39
40
        $this->data->$name = $value;
41
    }
42
43
    public function __isset($name)
44
    {
45
        return isset($this->data->$name);
46
    }
47
48
    public function __get($name)
49
    {
50
        return ($this->data->$name ?? null);
51
    }
52
53
    public function data(): ?object
54
    {
55
        return $this->data;
56
    }
57
58
    public function fail(): ?PDOException
59
    {
60
        return $this->fail;
61
    }
62
63
    public function find(?string $terms = null, ?string $params = null, string $columns = "*"): DataLayer
64
    {
65
        if ($terms) {
66
            $this->statement = "SELECT {$columns} FROM {$this->entity} WHERE {$terms}";
67
            parse_str($params, $this->params);
68
            return $this;
69
        }
70
71
        $this->statement = "SELECT {$columns} FROM {$this->entity}";
72
        return $this;
73
    }
74
75
    public function findById(int $id, string $columns = "*"): ?DataLayer
76
    {
77
        $find = $this->find($this->primary . " = :id", "id={$id}", $columns);
78
        return $find->fetch();
79
    }
80
81
    public function order(string $columnOrder): ?DataLayer
82
    {
83
        $this->order = " ORDER BY {$columnOrder}";
84
        return $this;
85
    }
86
87
    public function limit(int $limit): ?DataLayer
88
    {
89
        $this->limit = " LIMIT {$limit}";
90
        return $this;
91
    }
92
93
    public function offset(int $offset): ?DataLayer
94
    {
95
        $this->offset = " OFFSET {$offset}";
96
        return $this;
97
    }
98
99
    public function fetch(bool $all = false)
100
    {
101
        try {
102
            $stmt = Connect::getInstance()->prepare($this->statement . $this->order . $this->limit . $this->offset);
103
            $stmt->execute($this->params);
104
105
            if (!$stmt->rowCount()) {
106
                return null;
107
            }
108
109
            if ($all) {
110
                return $stmt->fetchAll(PDO::FETCH_CLASS, static::class);
111
            }
112
113
            return $stmt->fetchObject(static::class);
114
        } catch (PDOException $exception) {
115
            $this->fail = $exception;
116
            return null;
117
        }
118
    }
119
120
    public function count(): int
121
    {
122
        $stmt = Connect::getInstance()->prepare($this->statement);
123
        $stmt->execute($this->params);
124
        return $stmt->rowCount();
125
    }
126
127
    public function save(): bool
128
    {
129
        $id = null;
130
        $primary = $this->primary;
131
132
        try {
133
            if (!$this->required()) {
134
                throw new PDOException("Preencha os campos necessários");
135
            }
136
137
            /** Update */
138
            if (!empty($this->id)) {
0 ignored issues
show
Bug Best Practice introduced by
The property id does not exist on CoffeeCode\DataLayer\DataLayer. Since you implemented __get, consider adding a @property annotation.
Loading history...
139
                $id = $this->data->$primary;
140
                $this->update($this->safe(), $this->primary . " = :id", "id={$id}");
141
            }
142
143
            /** Create */
144
            if (empty($this->id)) {
145
                $id = $this->create($this->safe());
146
            }
147
148
            $this->data = $this->findById($id)->data();
149
            return true;
150
        } catch (PDOException $exception) {
151
            $this->fail = $exception;
152
            return false;
153
        }
154
    }
155
156
    protected function required(): bool
157
    {
158
        $data = (array)$this->data();
159
        foreach ($this->required as $field) {
160
            if (empty($data[$field])) {
161
                return false;
162
            }
163
        }
164
        return true;
165
    }
166
167
    protected function safe(): ?array
168
    {
169
        $safe = (array)$this->data;
170
        foreach ([$this->primary, "updated_at", "created_at"] as $unset) {
171
            unset($safe[$unset]);
172
        }
173
174
        return $safe;
175
    }
176
}