Passed
Push — master ( 2c89eb...c74887 )
by Robson
02:02 queued 26s
created

DataLayer::save()   B

Complexity

Conditions 7
Paths 18

Size

Total Lines 32
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 7
eloc 18
c 4
b 0
f 0
nc 18
nop 0
dl 0
loc 32
rs 8.8333
1
<?php
2
3
namespace CoffeeCode\DataLayer;
4
5
use Exception;
6
use PDO;
7
use PDOException;
8
use stdClass;
9
10
/**
11
 * Class DataLayer
12
 * @package CoffeeCode\DataLayer
13
 */
14
abstract class DataLayer
15
{
16
    use CrudTrait;
17
18
    /** @var string $entity database table */
19
    private $entity;
20
21
    /** @var string $primary table primary key field */
22
    private $primary;
23
24
    /** @var array $required table required fields */
25
    private $required;
26
27
    /** @var string $timestamps control created and updated at */
28
    private $timestamps;
29
30
    /** @var string */
31
    protected $statement;
32
33
    /** @var string */
34
    protected $params;
35
36
    /** @var string */
37
    protected $group;
38
39
    /** @var string */
40
    protected $order;
41
42
    /** @var int */
43
    protected $limit;
44
45
    /** @var int */
46
    protected $offset;
47
48
    /** @var \PDOException|null */
49
    protected $fail;
50
51
    /** @var object|null */
52
    protected $data;
53
54
    /**
55
     * DataLayer constructor.
56
     * @param string $entity
57
     * @param array $required
58
     * @param string $primary
59
     * @param bool $timestamps
60
     */
61
    public function __construct(string $entity, array $required, string $primary = 'id', bool $timestamps = true)
62
    {
63
        $this->entity = $entity;
64
        $this->primary = $primary;
65
        $this->required = $required;
66
        $this->timestamps = $timestamps;
0 ignored issues
show
Documentation Bug introduced by
The property $timestamps was declared of type string, but $timestamps is of type boolean. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
67
    }
68
69
    /**
70
     * @param $name
71
     * @param $value
72
     */
73
    public function __set($name, $value)
74
    {
75
        if (empty($this->data)) {
76
            $this->data = new stdClass();
77
        }
78
79
        $this->data->$name = $value;
80
    }
81
82
    /**
83
     * @param $name
84
     * @return bool
85
     */
86
    public function __isset($name)
87
    {
88
        return isset($this->data->$name);
89
    }
90
91
    /**
92
     * @param $name
93
     * @return string|null
94
     */
95
    public function __get($name)
96
    {
97
        $method = $this->toCamelCase($name);
98
        if (method_exists($this, $method)) {
99
            return $this->$method();
100
        }
101
102
        if (method_exists($this, $name)) {
103
            return $this->$name();
104
        }
105
106
        return ($this->data->$name ?? null);
107
    }
108
109
    /*
110
    * @return PDO mode
111
    */
112
    public function columns($mode = PDO::FETCH_OBJ)
113
    {
114
        $stmt = Connect::getInstance()->prepare("DESCRIBE {$this->entity}");
115
        $stmt->execute($this->params);
0 ignored issues
show
Bug introduced by
$this->params of type string is incompatible with the type array expected by parameter $params of PDOStatement::execute(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

115
        $stmt->execute(/** @scrutinizer ignore-type */ $this->params);
Loading history...
116
        return $stmt->fetchAll($mode);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $stmt->fetchAll($mode) returns the type array which is incompatible with the documented return type PDO.
Loading history...
117
    }
118
119
120
    /**
121
     * @return object|null
122
     */
123
    public function data(): ?object
124
    {
125
        return $this->data;
126
    }
127
128
    /**
129
     * @return PDOException|Exception|null
130
     */
131
    public function fail()
132
    {
133
        return $this->fail;
134
    }
135
136
    /**
137
     * @param string|null $terms
138
     * @param string|null $params
139
     * @param string $columns
140
     * @return DataLayer
141
     */
142
    public function find(?string $terms = null, ?string $params = null, string $columns = "*"): DataLayer
143
    {
144
        if ($terms) {
145
            $this->statement = "SELECT {$columns} FROM {$this->entity} WHERE {$terms}";
146
            parse_str($params, $this->params);
0 ignored issues
show
Bug introduced by
$this->params of type string is incompatible with the type array expected by parameter $result of parse_str(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

146
            parse_str($params, /** @scrutinizer ignore-type */ $this->params);
Loading history...
Bug introduced by
It seems like $params can also be of type null; however, parameter $string of parse_str() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

146
            parse_str(/** @scrutinizer ignore-type */ $params, $this->params);
Loading history...
147
            return $this;
148
        }
149
150
        $this->statement = "SELECT {$columns} FROM {$this->entity}";
151
        return $this;
152
    }
153
154
    /**
155
     * @param int $id
156
     * @param string $columns
157
     * @return DataLayer|null
158
     */
159
    public function findById(int $id, string $columns = "*"): ?DataLayer
160
    {
161
        return $this->find("{$this->primary} = :id", "id={$id}", $columns)->fetch();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->find($this...$id, $columns)->fetch() could return the type array which is incompatible with the type-hinted return CoffeeCode\DataLayer\DataLayer|null. Consider adding an additional type-check to rule them out.
Loading history...
162
    }
163
164
    /**
165
     * @param string $column
166
     * @return DataLayer|null
167
     */
168
    public function group(string $column): ?DataLayer
169
    {
170
        $this->group = " GROUP BY {$column}";
171
        return $this;
172
    }
173
174
    /**
175
     * @param string $columnOrder
176
     * @return DataLayer|null
177
     */
178
    public function order(string $columnOrder): ?DataLayer
179
    {
180
        $this->order = " ORDER BY {$columnOrder}";
181
        return $this;
182
    }
183
184
    /**
185
     * @param int $limit
186
     * @return DataLayer|null
187
     */
188
    public function limit(int $limit): ?DataLayer
189
    {
190
        $this->limit = " LIMIT {$limit}";
0 ignored issues
show
Documentation Bug introduced by
The property $limit was declared of type integer, but ' LIMIT '.$limit is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
191
        return $this;
192
    }
193
194
    /**
195
     * @param int $offset
196
     * @return DataLayer|null
197
     */
198
    public function offset(int $offset): ?DataLayer
199
    {
200
        $this->offset = " OFFSET {$offset}";
0 ignored issues
show
Documentation Bug introduced by
The property $offset was declared of type integer, but ' OFFSET '.$offset is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
201
        return $this;
202
    }
203
204
    /**
205
     * @param bool $all
206
     * @return array|mixed|null
207
     */
208
    public function fetch(bool $all = false)
209
    {
210
        try {
211
            $stmt = Connect::getInstance()->prepare($this->statement . $this->group . $this->order . $this->limit . $this->offset);
212
            $stmt->execute($this->params);
0 ignored issues
show
Bug introduced by
$this->params of type string is incompatible with the type array expected by parameter $params of PDOStatement::execute(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

212
            $stmt->execute(/** @scrutinizer ignore-type */ $this->params);
Loading history...
213
214
            if (!$stmt->rowCount()) {
215
                return null;
216
            }
217
218
            if ($all) {
219
                return $stmt->fetchAll(PDO::FETCH_CLASS, static::class);
220
            }
221
222
            return $stmt->fetchObject(static::class);
223
        } catch (PDOException $exception) {
224
            $this->fail = $exception;
225
            return null;
226
        }
227
    }
228
229
    /**
230
     * @return int
231
     */
232
    public function count(): int
233
    {
234
        $stmt = Connect::getInstance()->prepare($this->statement);
235
        $stmt->execute($this->params);
0 ignored issues
show
Bug introduced by
$this->params of type string is incompatible with the type array expected by parameter $params of PDOStatement::execute(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

235
        $stmt->execute(/** @scrutinizer ignore-type */ $this->params);
Loading history...
236
        return $stmt->rowCount();
237
    }
238
239
    /**
240
     * @return bool
241
     */
242
    public function save(): bool
243
    {
244
        $primary = $this->primary;
245
        $id = null;
246
247
        try {
248
            if (!$this->required()) {
249
                throw new Exception("Preencha os campos necessários");
250
            }
251
252
            /** Update */
253
            if (!empty($this->data->$primary)) {
254
                $id = $this->data->$primary;
255
                if(!$this->update($this->safe(), "{$this->primary} = :id", "id={$id}")) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->update($this->saf...ry.' = :id', 'id='.$id) of type integer|null is loosely compared to false; this is ambiguous if the integer can be 0. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
256
                    return false;
257
                }
258
            }
259
260
            /** Create */
261
            if (empty($this->data->$primary)) {
262
                $id = $this->create($this->safe());
263
            }
264
265
            if (!$id) {
266
                return false;
267
            }
268
269
            $this->data = $this->findById($id)->data();
270
            return true;
271
        } catch (Exception $exception) {
272
            $this->fail = $exception;
0 ignored issues
show
Documentation Bug introduced by
$exception is of type Exception, but the property $fail was declared to be of type PDOException|null. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
273
            return false;
274
        }
275
    }
276
277
    /**
278
     * @return bool
279
     */
280
    public function destroy(): bool
281
    {
282
        $primary = $this->primary;
283
        $id = $this->data->$primary;
284
285
        if (empty($id)) {
286
            return false;
287
        }
288
289
        return $this->delete("{$this->primary} = :id", "id={$id}");
290
    }
291
292
    /**
293
     * @return bool
294
     */
295
    protected function required(): bool
296
    {
297
        $data = (array)$this->data();
298
        foreach ($this->required as $field) {
299
            if (empty($data[$field])) {
300
                if(!is_int($data[$field])){
301
                    return false;
302
                }
303
            }
304
        }
305
        return true;
306
    }
307
308
    /**
309
     * @return array|null
310
     */
311
    protected function safe(): ?array
312
    {
313
        $safe = (array)$this->data;
314
        unset($safe[$this->primary]);
315
        return $safe;
316
    }
317
318
319
    /**
320
     * @param string $string
321
     * @return string
322
     */
323
    protected function toCamelCase(string $string): string
324
    {
325
        $camelCase = str_replace(' ', '', ucwords(str_replace('_', ' ', $string)));
326
        $camelCase[0] = strtolower($camelCase[0]);
327
        return $camelCase;
328
    }
329
}
330