ActiveRecordModel   A
last analyzed

Complexity

Total Complexity 23

Size/Duplication

Total Lines 346
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 88
c 1
b 0
f 0
dl 0
loc 346
rs 10
wmc 23

15 Methods

Rating   Name   Duplication   Size   Complexity  
A findAllWhere() 0 10 2
A setDb() 0 3 1
A checkDb() 0 4 2
A delete() 0 11 2
A create() 0 13 1
A findAll() 0 8 1
A updateWhere() 0 15 2
A saveWhere() 0 3 1
A getProperties() 0 10 1
A save() 0 7 2
A find() 0 3 1
A findById() 0 4 2
A update() 0 13 1
A deleteWhere() 0 9 2
A findWhere() 0 11 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
    public function setDb(DatabaseQueryBuilder $db)
44
    {
45
        $this->db = $db;
46
    }
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
    protected function checkDb()
58
    {
59
        if (!$this->db) {
60
            throw new ActiveRecordException("Missing \$db, did you forget to inject/set is?");
61
        }
62
    }
63
64
65
66
    /**
67
     * Get essential object properties.
68
     *
69
     * @return array with object properties.
70
     */
71
    protected function getProperties()
72
    {
73
        $properties = get_object_vars($this);
74
        unset(
75
            $properties['tableName'],
76
            $properties['db'],
77
            $properties['di'],
78
            $properties['tableIdColumn']
79
        );
80
        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
    public function find($column, $value) : object
95
    {
96
        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
    public function findById($id = null) : object
111
    {
112
        $id = $id ?: $this->{$this->tableIdColumn};
113
        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
    public function findWhere($where, $value) : object
134
    {
135
        $this->checkDb();
136
        $params = is_array($value) ? $value : [$value];
137
        $this->db->connect()
138
                 ->select()
139
                 ->from($this ->tableName)
140
                 ->where($where)
141
                 ->execute($params)
142
                 ->fetchInto($this);
143
        return $this;
144
    }
145
146
147
148
    /**
149
     * Find and return all.
150
     *
151
     * @return array of object of this class
152
     */
153
    public function findAll()
154
    {
155
        $this->checkDb();
156
        return $this->db->connect()
157
                        ->select()
158
                        ->from($this->tableName)
159
                        ->execute()
160
                        ->fetchAllClass(get_class($this));
161
    }
162
163
164
165
    /**
166
     * Find and return all matching the search criteria.
167
     *
168
     * The search criteria `$where` of can be set up like this:
169
     *  `id = ?`
170
     *  `id IN [?, ?]`
171
     *
172
     * The `$value` can be a single value or an array of values.
173
     *
174
     * @param string $where to use in where statement.
175
     * @param mixed  $value to use in where statement.
176
     *
177
     * @return array of object of this class
178
     */
179
    public function findAllWhere($where, $value)
180
    {
181
        $this->checkDb();
182
        $params = is_array($value) ? $value : [$value];
183
        return $this->db->connect()
184
                        ->select()
185
                        ->from($this->tableName)
186
                        ->where($where)
187
                        ->execute($params)
188
                        ->fetchAllClass(get_class($this));
189
    }
190
191
192
193
    /**
194
     * Save current object/row, insert if id is missing and do an
195
     * update if the id exists.
196
     *
197
     * @return void
198
     */
199
    public function save()
200
    {
201
        if (isset($this->{$this->tableIdColumn})) {
202
            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...
203
        }
204
205
        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...
206
    }
207
208
209
210
    /**
211
     * Save/update current object/row using a custom where-statement.
212
     *
213
     * The criteria `$where` of can be set up like this:
214
     *  `id = ?`
215
     *  `id1 = ? AND id2 = ?`
216
     *
217
     * The `$value` can be a single value or an array of values.
218
     *
219
     * @param string $where to use in where statement.
220
     * @param mixed  $value to use in where statement.
221
     *
222
     * @return void
223
     */
224
    public function saveWhere($where, $value)
225
    {
226
        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...
227
    }
228
229
230
231
    /**
232
     * Create new row.
233
     *
234
     * @return void
235
     */
236
    protected function create()
237
    {
238
        $this->checkDb();
239
        $properties = $this->getProperties();
240
        unset($properties[$this->tableIdColumn]);
241
        $columns = array_keys($properties);
242
        $values  = array_values($properties);
243
244
        $this->db->connect()
245
                 ->insert($this->tableName, $columns)
246
                 ->execute($values);
247
248
        $this->{$this->tableIdColumn} = $this->db->lastInsertId();
249
    }
250
251
252
253
    /**
254
     * Update row using $tableIdColumn as where.
255
     *
256
     * @return void
257
     */
258
    protected function update()
259
    {
260
        $this->checkDb();
261
        $properties = $this->getProperties();
262
        unset($properties[$this->tableIdColumn]);
263
        $columns = array_keys($properties);
264
        $values  = array_values($properties);
265
        $values[] = $this->{$this->tableIdColumn};
266
267
        $this->db->connect()
268
                 ->update($this->tableName, $columns)
269
                 ->where("{$this->tableIdColumn} = ?")
270
                 ->execute($values);
271
    }
272
273
274
275
    /**
276
     * Update row using a custom where-statement.
277
     *
278
     * The criteria `$where` of can be set up like this:
279
     *  `id = ?`
280
     *  `id1 = ? AND id2 = ?`
281
     *  `id IN (?, ?)`
282
     *
283
     * The `$value` can be a single value or an array of values.
284
     *
285
     * @param string $where to use in where statement.
286
     * @param mixed  $value to use in where statement.
287
     *
288
     * @return void
289
     */
290
    protected function updateWhere($where, $value)
291
    {
292
        $this->checkDb();
293
        $properties = $this->getProperties();
294
        $columns = array_keys($properties);
295
        $values  = array_values($properties);
296
        $values1 = is_array($value)
297
            ? $value
298
            : [$value];
299
        $values = array_merge($values, $values1);
300
301
        $this->db->connect()
302
                 ->update($this->tableName, $columns)
303
                 ->where($where)
304
                 ->execute($values);
305
    }
306
307
308
309
    /**
310
     * Update row using $tableIdColumn as where and clear value of
311
     * `$tableIdColumn`.
312
     *
313
     * @param integer $id to delete or use $this->{$this->tableIdColumn}
314
     *                    as default.
315
     *
316
     * @return void
317
     */
318
    public function delete($id = null)
319
    {
320
        $this->checkDb();
321
        $id = $id ?: $this->{$this->tableIdColumn};
322
323
        $this->db->connect()
324
                 ->deleteFrom($this->tableName)
325
                 ->where("{$this->tableIdColumn} = ?")
326
                 ->execute([$id]);
327
328
        $this->{$this->tableIdColumn} = null;
329
    }
330
331
332
333
    /**
334
     * Delete row using a custom where-statement and leave value of
335
     * `$tableIdColumn` as it is.
336
     *
337
     * The criteria `$where` of can be set up like this:
338
     *  `id = ?`
339
     *  `id1 = ? AND id2 = ?`
340
     *  `id IN (?, ?)`
341
     *
342
     * The `$value` can be a single value or an array of values.
343
     *
344
     * @param string $where to use in where statement.
345
     * @param mixed  $value to use in where statement.
346
     *
347
     * @return void
348
     */
349
    public function deleteWhere($where, $value)
350
    {
351
        $this->checkDb();
352
        $values = is_array($value) ? $value : [$value];
353
354
        $this->db->connect()
355
                 ->deleteFrom($this->tableName)
356
                 ->where($where)
357
                 ->execute($values);
358
    }
359
}
360