Dolphin::all()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 1
Metric Value
cc 2
eloc 3
c 1
b 1
f 1
nc 2
nop 0
dl 0
loc 6
rs 10
1
<?php
2
/**
3
 * The Query builder API.
4
 *
5
 * @author RN Kushwaha <[email protected]>
6
 * @since v0.0.1 <Date: 12th April, 2019>
7
 */
8
9
namespace Dolphin\Mapper;
10
11
use Dolphin\Connections\Connection;
12
use Dolphin\Builders\QueryBuilder;
13
use Dolphin\Builders\WhereQueryBuilder;
14
use Dolphin\Builders\InsertQueryBuilder;
15
use Dolphin\Builders\UpdateQueryBuilder;
16
use Dolphin\Builders\DeleteQueryBuilder;
17
use Dolphin\Builders\PrepareQueryBuilder;
18
use \Exception;
19
20
/**
21
 * This class provides some nice features to interact with the Database
22
 * Elegant Query builder
23
 * Method Chaining
24
 * Prepared Statement using named parameter like status = :status
25
 * Raw Query Option
26
 * Join Clause
27
 * Where Clause
28
 * WhereRaw Clause
29
 * orWhere Clause [TODO]
30
 * WhereIn Clause
31
 * WhereNotIn Clause
32
 * WhereNull Clause
33
 * WhereNotNull Clause
34
 * GroupBy Clause
35
 * Having Clause
36
 * OrderBy Clause.
37
 *
38
 * Aggregations like
39
 * Count()
40
 * Max() [TODO]
41
 * Min() [TODO]
42
 * First()
43
 * Last() [TODO]
44
 * Avg() [TODO]
45
 * fetchColumn [TODO]
46
 * union() [TODO]
47
 * delete()
48
 * update()
49
 * insert()
50
 * truncate()
51
 * havingRaw() [TODO]
52
 * exists() [TODO]
53
 */
54
class Dolphin
55
{
56
    protected $fields = [];
57
    public $table;
58
    public $className;
59
    protected $groupBy;
60
    protected $orderBy;
61
    protected $having;
62
    protected $join = [];
63
    protected $leftJoin = [];
64
    protected $rightJoin = [];
65
    protected $crossJoin = [];
66
    protected $where = [];
67
    protected $whereRaw = [];
68
    protected $whereIn = [];
69
    protected $whereNotIn = [];
70
    protected $whereNull = [];
71
    protected $whereNotNull = [];
72
    protected $limit;
73
    protected $offset;
74
    protected $results;
75
76
    private function getFields(array $args, bool $quote = true){
77
        return (new QueryBuilder())->getFields($args, $quote);
78
    }
79
80
    private function validateArgsCount($noOfArgs){
81
        if($noOfArgs<2 || $noOfArgs >3){
82
            throw new Exception('Where parameter contains invalid number of parameters', 1);
83
        }
84
    }
85
86
    public function select()
87
    {
88
        $args = func_get_args();
89
        $fldAr = $this->getFields($args, true);
90
        $this->fields = array_merge($this->fields, $fldAr);
91
92
        return $this;
93
    }
94
95
    public function selectRaw()
96
    {
97
        $args = func_get_args();
98
        $fldAr = $this->getFields($args, false);
99
        $this->fields = array_merge($this->fields, $fldAr);
100
101
        return $this;
102
    }
103
104
    public function join($join, $mixedParam, $param3 = null, $param4 = null, $mixedParam2 = null)
105
    {
106
        $this->join = array_merge($this->join, [[$join, $mixedParam, $param3, $param4, $mixedParam2]]);
107
108
        return $this;
109
    }
110
111
    public function leftJoin($leftJoin, $mixedParam, $param3 = null, $param4 = null, $mixedParam2 = null)
112
    {
113
        $this->leftJoin = array_merge($this->leftJoin, [[$leftJoin, $mixedParam, $param3, $param4, $mixedParam2]]);
114
115
        return $this;
116
    }
117
118
    public function rightJoin($rightJoin, $mixedParam, $param3 = null, $param4 = null, $mixedParam2 = null)
119
    {
120
        $this->rightJoin = array_merge($this->rightJoin, [[$rightJoin, $mixedParam, $param3, $param4, $mixedParam2]]);
121
122
        return $this;
123
    }
124
125
    public function crossJoin($crossJoin, $params = null)
126
    {
127
        $this->crossJoin = array_merge($this->crossJoin, [[$crossJoin, $params]]);
128
129
        return $this;
130
    }
131
132
    /**
133
     * @throws Exception
134
     */
135
    public function where()
136
    {
137
        $args = func_get_args();
138
        $noOfArgs = func_num_args();
139
        $this->validateArgsCount($noOfArgs);
140
141
        if($noOfArgs===2){
142
            $this->where = array_merge($this->where, [[$args[0], '=', $args[1]]]);
143
            return $this;
144
        }
145
146
        $this->where = array_merge($this->where, [[$args[0], $args[1], $args[2]]]);
147
        return $this;
148
    }
149
150
    public function whereIn($whereIn, $params = [])
151
    {
152
        $this->whereIn = array_merge($this->whereIn, [[$whereIn, $params]]);
153
154
        return $this;
155
    }
156
157
    public function whereNotIn($whereNotIn, $params = [])
158
    {
159
        $this->whereNotIn = array_merge($this->whereNotIn, [[$whereNotIn, $params]]);
160
161
        return $this;
162
    }
163
164
    public function whereNull($whereNull)
165
    {
166
        $this->whereNull = array_merge($this->whereNull, [$whereNull]);
167
168
        return $this;
169
    }
170
171
    public function whereNotNull($whereNotNull)
172
    {
173
        $this->whereNotNull = array_merge($this->whereNotNull, [$whereNotNull]);
174
175
        return $this;
176
    }
177
178
    public function whereRaw($whereConditions)
179
    {
180
        $this->whereRaw = array_merge($this->whereRaw, [$whereConditions]);
181
182
        return $this;
183
    }
184
185
    public function offset($offset)
186
    {
187
        $this->offset = $offset;
188
189
        return $this;
190
    }
191
192
    public function limit($limit)
193
    {
194
        $this->limit = $limit;
195
196
        return $this;
197
    }
198
199
    public function orderBy($orderBy)
200
    {
201
        $this->orderBy = $orderBy;
202
203
        return $this;
204
    }
205
206
    public function groupBy($groupBy)
207
    {
208
        $this->groupBy = $groupBy;
209
210
        return $this;
211
    }
212
213
    public function having($having)
214
    {
215
        $this->having = $having;
216
217
        return $this;
218
    }
219
220
    /**
221
     * Builds Query added by method chaining.
222
     * It has the main logic of ORM
223
     */
224
    protected function buildQuery()
225
    {
226
        $query  = (new QueryBuilder())->buildQuery([
227
            'table' => $this->table,
228
            'fields' => $this->fields,
229
            'join' => $this->join,
230
            'leftJoin' => $this->leftJoin,
231
            'rightJoin' => $this->rightJoin,
232
            'crossJoin' => $this->crossJoin,
233
            'where' => $this->where,
234
            'whereRaw' => $this->whereRaw,
235
            'whereIn' => $this->whereIn,
236
            'whereNotIn' => $this->whereNotIn,
237
            'whereNull' => $this->whereNull,
238
            'whereNotNull' => $this->whereNotNull,
239
            'groupBy' => $this->groupBy,
240
            'having' => $this->having,
241
            'orderBy' => $this->orderBy,
242
            'limit' => $this->limit,
243
            'offset' => $this->offset
244
        ]);
245
246
        return join(' ', $query);
247
    }
248
249
    protected function reset()
250
    {
251
        $this->fields = [];
252
        $this->table = null;
253
        $this->className = null;
254
        $this->groupBy = null;
255
        $this->orderBy = null;
256
        $this->having = null;
257
        $this->join = [];
258
        $this->leftJoin = [];
259
        $this->rightJoin = [];
260
        $this->crossJoin = [];
261
        $this->where = [];
262
        $this->whereRaw = [];
263
        $this->whereIn = [];
264
        $this->whereNotIn = [];
265
        $this->whereNull = [];
266
        $this->whereNotNull = [];
267
        $this->limit = null;
268
        $this->offset = null;
269
    }
270
271
    public function prepare($query, $fetchRows = 'all')
272
    {
273
        $results = (new PrepareQueryBuilder())->prepare($this->where, $this->className, $query, $fetchRows);
274
275
        $this->results = $results;
276
        $this->reset();
277
278
        return $results;
279
    }
280
281
    public function query($query, $fetchRows = 'all')
282
    {
283
        $result = (new QueryBuilder())->query($query, $fetchRows);
284
        $this->reset();
285
286
        return $result;
287
    }
288
289
    public function get()
290
    {
291
        return $this->prepare($this->buildQuery());
292
    }
293
294
    public function first()
295
    {
296
        $query = $this->buildQuery();
297
298
        if (!strripos($query, 'LIMIT 1')) {
299
            $query .= ' LIMIT 1';
300
        }
301
302
        $result = $this->prepare($query, 'first');
303
304
        return isset($result->data) ? $result->data : '';
0 ignored issues
show
Bug introduced by
The property data does not exist on boolean.
Loading history...
305
    }
306
307
    public function all()
308
    {
309
        $query = $this->buildQuery();
310
        $result = $this->prepare($query);
311
312
        return isset($result->data) ? $result->data : '';
0 ignored issues
show
Bug introduced by
The property data does not exist on boolean.
Loading history...
313
    }
314
315
    /**
316
     * It fetches the row by primary key
317
     *
318
     * @since v0.0.5
319
     */
320
    public function find($id)
321
    {
322
        $this->where('id', $id);
323
324
        return $this->first();
325
    }
326
327
    /**
328
     * It fetches the row by primary key
329
     *
330
     * @param int $id
331
     * @return object $row
332
     * @throws Exception
333
     * @since v0.0.5
334
     */
335
    public function findOrFail($id)
336
    {
337
        $this->where('id', $id);
338
        $row = $this->first();
339
340
        if($row == null ){
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $row of type mixed|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison === instead.
Loading history...
341
            throw new Exception("The record does not exists!");
342
        }
343
344
        return $row;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $row also could return the type string which is incompatible with the documented return type object.
Loading history...
345
    }
346
347
    public function count()
348
    {
349
        $this->fields = null;
350
        $query = $this->buildQuery();
351
        $query = str_replace('SELECT * ', 'SELECT COUNT(*) as count ', $query);
352
353
        return $this->query($query, 'count');
354
    }
355
356
    /**
357
     * It inserts the new rows
358
     *
359
     * @param array $rows
360
     * @return integer $lastInsertedId
361
     * @throws Exception
362
     * @since v0.0.5
363
     */
364
    public function insert($rows)
365
    {
366
        return (new InsertQueryBuilder())->insert($rows, $this->table);
367
    }
368
369
    /**
370
     * It updates the rows
371
     *
372
     * @param array $row
373
     * @return boolean
374
     * @throws Exception
375
     * @since v0.0.5
376
     */
377
    public function update($row)
378
    {
379
        $result =  (new UpdateQueryBuilder())->update(
380
          $row,
381
          $this->table,
382
          $this->where,
383
          $this->whereRaw,
384
          $this->whereIn,
385
          $this->whereNotIn,
386
          $this->whereNull,
387
          $this->whereNotNull
388
        );
389
390
        $this->reset();
391
392
        return $result;
393
    }
394
395
    /**
396
     * It truncates the table
397
     *
398
     * @return boolean
399
     * @throws Exception
400
     * @since v0.0.5
401
     */
402
    public function truncate()
403
    {
404
        $qb = new QueryBuilder();
405
        $query = "TRUNCATE ".$this->table;
406
407
        try{
408
            Connection::get()->query($qb->queryPrefix($query));
409
        } catch(Exception $e){
410
            throw new Exception($e->getMessage());
411
        }
412
413
        return true;
414
    }
415
416
    /**
417
     * It deleted the rows matched by where clause
418
     *
419
     * @return boolean
420
     * @throws Exception
421
     * @since v0.0.5
422
     */
423
    public function delete()
424
    {
425
        $result =  (new DeleteQueryBuilder())->delete(
426
          $this->table,
427
          $this->where,
428
          $this->whereRaw,
429
          $this->whereIn,
430
          $this->whereNotIn,
431
          $this->whereNull,
432
          $this->whereNotNull
433
        );
434
435
        $this->reset();
436
437
        return $result;
438
    }
439
440
}
441