Passed
Push — master ( 200f25...95aa98 )
by Robson
01:25
created

DataLayer::toCamelCase()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 5
rs 10
cc 1
nc 1
nop 1
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
        return ($this->data->$name ?? null);
103
    }
104
105
    /**
106
     * @return object|null
107
     */
108
    public function data(): ?object
109
    {
110
        return $this->data;
111
    }
112
113
    /**
114
     * @return PDOException|Exception|null
115
     */
116
    public function fail()
117
    {
118
        return $this->fail;
119
    }
120
121
    /**
122
     * @param string|null $terms
123
     * @param string|null $params
124
     * @param string $columns
125
     * @return DataLayer
126
     */
127
    public function find(?string $terms = null, ?string $params = null, string $columns = "*"): DataLayer
128
    {
129
        if ($terms) {
130
            $this->statement = "SELECT {$columns} FROM {$this->entity} WHERE {$terms}";
131
            parse_str($params, $this->params);
0 ignored issues
show
Bug introduced by
$this->params of type string is incompatible with the type array|null expected by parameter $arr 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

131
            parse_str($params, /** @scrutinizer ignore-type */ $this->params);
Loading history...
132
            return $this;
133
        }
134
135
        $this->statement = "SELECT {$columns} FROM {$this->entity}";
136
        return $this;
137
    }
138
139
    /**
140
     * @param int $id
141
     * @param string $columns
142
     * @return DataLayer|null
143
     */
144
    public function findById(int $id, string $columns = "*"): ?DataLayer
145
    {
146
        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...
147
    }
148
149
    /**
150
     * @param string $column
151
     * @return DataLayer|null
152
     */
153
    public function group(string $column): ?DataLayer
154
    {
155
        $this->group = " GROUP BY {$column}";
156
        return $this;
157
    }
158
159
    /**
160
     * @param string $columnOrder
161
     * @return DataLayer|null
162
     */
163
    public function order(string $columnOrder): ?DataLayer
164
    {
165
        $this->order = " ORDER BY {$columnOrder}";
166
        return $this;
167
    }
168
169
    /**
170
     * @param int $limit
171
     * @return DataLayer|null
172
     */
173
    public function limit(int $limit): ?DataLayer
174
    {
175
        $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...
176
        return $this;
177
    }
178
179
    /**
180
     * @param int $offset
181
     * @return DataLayer|null
182
     */
183
    public function offset(int $offset): ?DataLayer
184
    {
185
        $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...
186
        return $this;
187
    }
188
189
    /**
190
     * @param bool $all
191
     * @return array|mixed|null
192
     */
193
    public function fetch(bool $all = false)
194
    {
195
        try {
196
            $stmt = Connect::getInstance()->prepare($this->statement . $this->group . $this->order . $this->limit . $this->offset);
197
            $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 $input_parameters 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

197
            $stmt->execute(/** @scrutinizer ignore-type */ $this->params);
Loading history...
198
199
            if (!$stmt->rowCount()) {
200
                return null;
201
            }
202
203
            if ($all) {
204
                return $stmt->fetchAll(PDO::FETCH_CLASS, static::class);
205
            }
206
207
            return $stmt->fetchObject(static::class);
208
        } catch (PDOException $exception) {
209
            $this->fail = $exception;
210
            return null;
211
        }
212
    }
213
214
    /**
215
     * @return int
216
     */
217
    public function count(): int
218
    {
219
        $stmt = Connect::getInstance()->prepare($this->statement);
220
        $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 $input_parameters 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

220
        $stmt->execute(/** @scrutinizer ignore-type */ $this->params);
Loading history...
221
        return $stmt->rowCount();
222
    }
223
224
    /**
225
     * @return bool
226
     */
227
    public function save(): bool
228
    {
229
        $primary = $this->primary;
230
        $id = null;
231
232
        try {
233
            if (!$this->required()) {
234
                throw new Exception("Preencha os campos necessários");
235
            }
236
237
            /** Update */
238
            if (!empty($this->data->$primary)) {
239
                $id = $this->data->$primary;
240
                $this->update($this->safe(), $this->primary . " = :id", "id={$id}");
241
            }
242
243
            /** Create */
244
            if (empty($this->data->$primary)) {
245
                $id = $this->create($this->safe());
246
            }
247
248
            if (!$id) {
249
                return false;
250
            }
251
252
            $this->data = $this->findById($id)->data();
253
            return true;
254
        } catch (Exception $exception) {
255
            $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...
256
            return false;
257
        }
258
    }
259
260
    /**
261
     * @return bool
262
     */
263
    public function destroy(): bool
264
    {
265
        $primary = $this->primary;
266
        $id = $this->data->$primary;
267
268
        if (empty($id)) {
269
            return false;
270
        }
271
272
        return $this->delete($this->primary . " = :id", "id={$id}");
273
    }
274
275
    /**
276
     * @return bool
277
     */
278
    protected function required(): bool
279
    {
280
        $data = (array)$this->data();
281
        foreach ($this->required as $field) {
282
            if (empty($data[$field])) {
283
                return false;
284
            }
285
        }
286
        return true;
287
    }
288
289
    /**
290
     * @return array|null
291
     */
292
    protected function safe(): ?array
293
    {
294
        $safe = (array)$this->data;
295
        unset($safe[$this->primary]);
296
        return $safe;
297
    }
298
299
300
    /**
301
     * @param string $string
302
     * @return string
303
     */
304
    protected function toCamelCase(string $string): string
305
    {
306
        $camelCase = str_replace(' ', '', ucwords(str_replace('_', ' ', $string)));
307
        $camelCase[0] = strtolower($camelCase[0]);
308
        return $camelCase;
309
    }
310
}
311