Completed
Push — master ( 524978...6b5c49 )
by Mikael
03:08
created

ActiveRecordModel::checkDb()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 4
c 0
b 0
f 0
ccs 3
cts 3
cp 1
rs 10
cc 2
nc 2
nop 0
crap 2
1
<?php
2
3
namespace Anax\DatabaseActiveRecord;
4
5
use Anax\DatabaseActiveRecord\Exception\ActiveRecordException;
6
use Anax\DatabaseQueryBuilder\DatabaseQueryBuilder;
7
8
/**
9
 * An implementation of the Active Record pattern to be used as
10
 * base class for database driven models.
11
 */
12
class ActiveRecordModel
13
{
14
    /**
15
     * @var DatabaseQueryBuilder $db the object for persistent
16
     *                               storage.
17
     */
18
    protected $db = null;
19
20
21
22
    /**
23
     * @var string $tableName name of the database table.
24
     */
25
    protected $tableName = null;
26
27
28
29
    /**
30
     * @var string $tableIdColumn name of the id column in the database table.
31
     */
32
    protected $tableIdColumn = "id";
33
34
35
36
    /**
37
     * Set the database object to use for accessing storage.
38
     *
39
     * @param DatabaseQueryBuilder $db as database access object.
40
     *
41
     * @return void
42
     */
43 6
    public function setDb(DatabaseQueryBuilder $db)
44
    {
45 6
        $this->db = $db;
46 6
    }
47
48
49
50
    /**
51
     * Check if database is injected or throw an exception.
52
     *
53
     * @throws ActiveRecordException when database is not set.
54
     *
55
     * @return void
56
     */
57 7
    protected function checkDb()
58
    {
59 7
        if (!$this->db) {
60 1
            throw new ActiveRecordException("Missing \$db, did you forget to inject/set is?");
61
        }
62 6
    }
63
64
65
66
    /**
67
     * Get essential object properties.
68
     *
69
     * @return array with object properties.
70
     */
71 6
    protected function getProperties()
72
    {
73 6
        $properties = get_object_vars($this);
74
        unset(
75 6
            $properties['tableName'],
76 6
            $properties['db'],
77 6
            $properties['di'],
78 6
            $properties['tableIdColumn']
79
        );
80 6
        return $properties;
81
    }
82
83
84
85
    /**
86
     * Find and return first object found by search criteria and use
87
     * its data to populate this instance.
88
     *
89
     * @param string $column to use in where statement.
90
     * @param mixed  $value  to use in where statement.
91
     *
92
     * @return this
93
     */
94 1
    public function find($column, $value)
95
    {
96 1
        return $this->findWhere("$column = ?", $value);
97
    }
98
99
100
101
    /**
102
     * Find and return first object by its tableIdColumn and use
103
     * its data to populate this instance.
104
     *
105
     * @param integer $id to find or use $this->{$this->tableIdColumn}
106
     *                    as default.
107
     *
108
     * @return this
109
     */
110 4
    public function findById($id = null)
111
    {
112 4
        $id = $id ?: $this->{$this->tableIdColumn};
113 4
        return $this->findWhere("{$this->tableIdColumn} = ?", $id);
114
    }
115
116
117
118
    /**
119
     * Find and return first object found by search criteria and use
120
     * its data to populate this instance.
121
     *
122
     * The search criteria `$where` of can be set up like this:
123
     *  `id = ?`
124
     *  `id1 = ? and id2 = ?`
125
     *
126
     * The `$value` can be a single value or an array of values.
127
     *
128
     * @param string $where to use in where statement.
129
     * @param mixed  $value to use in where statement.
130
     *
131
     * @return this
132
     */
133 4
    public function findWhere($where, $value)
134
    {
135 4
        $this->checkDb();
136 4
        $params = is_array($value) ? $value : [$value];
137 4
        $this->db->connect()
138 4
                 ->select()
139 4
                 ->from($this ->tableName)
140 4
                 ->where($where)
141 4
                 ->execute($params)
142 4
                 ->fetchInto($this);
143 4
    }
144
145
146
147
    /**
148
     * Find and return all.
149
     *
150
     * @return array of object of this class
151
     */
152 1
    public function findAll()
153
    {
154 1
        $this->checkDb();
155 1
        return $this->db->connect()
156 1
                        ->select()
157 1
                        ->from($this->tableName)
158 1
                        ->execute()
159 1
                        ->fetchAllClass(get_class($this));
160
    }
161
162
163
164
    /**
165
     * Find and return all matching the search criteria.
166
     *
167
     * The search criteria `$where` of can be set up like this:
168
     *  `id = ?`
169
     *  `id IN [?, ?]`
170
     *
171
     * The `$value` can be a single value or an array of values.
172
     *
173
     * @param string $where to use in where statement.
174
     * @param mixed  $value to use in where statement.
175
     *
176
     * @return array of object of this class
177
     */
178 1
    public function findAllWhere($where, $value)
179
    {
180 1
        $this->checkDb();
181 1
        $params = is_array($value) ? $value : [$value];
182 1
        return $this->db->connect()
183 1
                        ->select()
184 1
                        ->from($this->tableName)
185 1
                        ->where($where)
186 1
                        ->execute($params)
187 1
                        ->fetchAllClass(get_class($this));
188
    }
189
190
191
192
    /**
193
     * Save current object/row, insert if id is missing and do an
194
     * update if the id exists.
195
     *
196
     * @return void
197
     */
198 7
    public function save()
199
    {
200 7
        if (isset($this->{$this->tableIdColumn})) {
201 2
            return $this->update();
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->update() targeting Anax\DatabaseActiveRecor...veRecordModel::update() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
202
        }
203
204 7
        return $this->create();
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->create() targeting Anax\DatabaseActiveRecor...veRecordModel::create() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
205
    }
206
207
208
209
    /**
210
     * Save/update current object/row using a custom where-statement.
211
     *
212
     * The criteria `$where` of can be set up like this:
213
     *  `id = ?`
214
     *  `id1 = ? AND id2 = ?`
215
     *
216
     * The `$value` can be a single value or an array of values.
217
     *
218
     * @param string $where to use in where statement.
219
     * @param mixed  $value to use in where statement.
220
     *
221
     * @return void
222
     */
223 1
    public function saveWhere($where, $value)
224
    {
225 1
        return $this->updateWhere($where, $value);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->updateWhere($where, $value) targeting Anax\DatabaseActiveRecor...ordModel::updateWhere() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
226
    }
227
228
229
230
    /**
231
     * Create new row.
232
     *
233
     * @return void
234
     */
235 7
    protected function create()
236
    {
237 7
        $this->checkDb();
238 6
        $properties = $this->getProperties();
239 6
        unset($properties[$this->tableIdColumn]);
240 6
        $columns = array_keys($properties);
241 6
        $values  = array_values($properties);
242
243 6
        $this->db->connect()
244 6
                 ->insert($this->tableName, $columns)
245 6
                 ->execute($values);
246
247 6
        $this->{$this->tableIdColumn} = $this->db->lastInsertId();
248 6
    }
249
250
251
252
    /**
253
     * Update row using $tableIdColumn as where.
254
     *
255
     * @return void
256
     */
257 2
    protected function update()
258
    {
259 2
        $this->checkDb();
260 2
        $properties = $this->getProperties();
261 2
        unset($properties[$this->tableIdColumn]);
262 2
        $columns = array_keys($properties);
263 2
        $values  = array_values($properties);
264 2
        $values[] = $this->{$this->tableIdColumn};
265
266 2
        $this->db->connect()
267 2
                 ->update($this->tableName, $columns)
268 2
                 ->where("{$this->tableIdColumn} = ?")
269 2
                 ->execute($values);
270 2
    }
271
272
273
274
    /**
275
     * Update row using a custom where-statement.
276
     *
277
     * The criteria `$where` of can be set up like this:
278
     *  `id = ?`
279
     *  `id1 = ? AND id2 = ?`
280
     *  `id IN (?, ?)`
281
     *
282
     * The `$value` can be a single value or an array of values.
283
     *
284
     * @param string $where to use in where statement.
285
     * @param mixed  $value to use in where statement.
286
     *
287
     * @return void
288
     */
289 1
    protected function updateWhere($where, $value)
290
    {
291 1
        $this->checkDb();
292 1
        $properties = $this->getProperties();
293 1
        $columns = array_keys($properties);
294 1
        $values  = array_values($properties);
295 1
        $values1 = is_array($value)
296 1
            ? $value
297 1
            : [$value];
298 1
        $values = array_merge($values, $values1);
299
300 1
        $this->db->connect()
301 1
                 ->update($this->tableName, $columns)
302 1
                 ->where($where)
303 1
                 ->execute($values);
304 1
    }
305
306
307
308
    /**
309
     * Update row using $tableIdColumn as where and clear value of
310
     * `$tableIdColumn`.
311
     *
312
     * @param integer $id to delete or use $this->{$this->tableIdColumn}
313
     *                    as default.
314
     *
315
     * @return void
316
     */
317 2
    public function delete($id = null)
318
    {
319 2
        $this->checkDb();
320 2
        $id = $id ?: $this->{$this->tableIdColumn};
321
322 2
        $this->db->connect()
323 2
                 ->deleteFrom($this->tableName)
324 2
                 ->where("{$this->tableIdColumn} = ?")
325 2
                 ->execute([$id]);
326
327 2
        $this->{$this->tableIdColumn} = null;
328 2
    }
329
330
331
332
    /**
333
     * Delete row using a custom where-statement and leave value of
334
     * `$tableIdColumn` as it is.
335
     *
336
     * The criteria `$where` of can be set up like this:
337
     *  `id = ?`
338
     *  `id1 = ? AND id2 = ?`
339
     *  `id IN (?, ?)`
340
     *
341
     * The `$value` can be a single value or an array of values.
342
     *
343
     * @param string $where to use in where statement.
344
     * @param mixed  $value to use in where statement.
345
     *
346
     * @return void
347
     */
348 1
    public function deleteWhere($where, $value)
349
    {
350 1
        $this->checkDb();
351 1
        $values = is_array($value) ? $value : [$value];
352
353 1
        $this->db->connect()
354 1
                 ->deleteFrom($this->tableName)
355 1
                 ->where($where)
356 1
                 ->execute($values);
357 1
    }
358
}
359