Passed
Push — master ( 8adb69...893094 )
by RN
01:44
created

Dolphin::buildAllWhereQuery()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 0
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * The Query builder API.
4
 *
5
 * @author RN Kushwaha <[email protected]>
6
 *
7
 * @since v0.0.1 <Date: 12th April, 2019>
8
 */
9
10
namespace Dolphin\Mapper;
11
12
use Dolphin\Connections\Connection;
13
use Dolphin\Builders\QueryBuilder;
14
use Dolphin\Builders\WhereQueryBuilder;
15
use Dolphin\Builders\JoinQueryBuilder;
16
use Dolphin\Builders\InsertQueryBuilder;
17
use Dolphin\Parsers\WhereQueryParser;
18
use Dolphin\Utils\Utils;
19
use \Exception;
20
21
/**
22
 * This class provides some nice features to interact with the Database
23
 * Elegant Query builder
24
 * Method Chaining
25
 * Prepared Statement using named parameter like status = :status
26
 * Raw Query Option
27
 * Join Clause
28
 * Where Clause
29
 * WhereRaw Clause
30
 * orWhere Clause [TODO]
31
 * WhereIn Clause
32
 * WhereNotIn Clause
33
 * WhereNull Clause
34
 * WhereNotNull Clause
35
 * GroupBy Clause
36
 * Having Clause
37
 * OrderBy Clause.
38
 *
39
 * Aggregations like
40
 * Count()
41
 * Max() [TODO]
42
 * Min() [TODO]
43
 * First()
44
 * Last() [TODO]
45
 * Avg() [TODO]
46
 * fetchColumn [TODO]
47
 * union() [TODO]
48
 * delete()
49
 * update()
50
 * insert()
51
 * truncate()
52
 * havingRaw() [TODO]
53
 * exists() [TODO]
54
 */
55
class Dolphin
56
{
57
    protected $fields = array();
58
    public $table;
59
    public $className;
60
    protected $groupBy;
61
    protected $orderBy;
62
    protected $having;
63
    protected $join = array();
64
    protected $leftJoin = array();
65
    protected $rightJoin = array();
66
    protected $crossJoin = array();
67
    protected $where = array();
68
    protected $whereIn = array();
69
    protected $whereNotIn = array();
70
    protected $whereNull = array();
71
    protected $whereNotNull = array();
72
    protected $limit;
73
    protected $offset;
74
    protected $results;
75
76
    public function select()
77
    {
78
        $args = func_get_args();
79
        $fldAr = array();
80
        $qb = new QueryBuilder();
81
82
        foreach ($args as $arg) {
83
            $argsAr = explode(',', $arg);
84
            foreach ($argsAr as $ar) {
85
                $fldAr[] = $qb->quote(trim($ar));
86
            }
87
        }
88
89
        $this->fields = array_merge($this->fields, $fldAr);
90
91
        return $this;
92
    }
93
94
    public function selectRaw()
95
    {
96
        $args = func_get_args();
97
        $fldAr = array();
98
99
        foreach ($args as $arg) {
100
            $argsAr = explode(',', $arg);
101
            foreach ($argsAr as $ar) {
102
                $fldAr[] = trim($ar);
103
            }
104
        }
105
106
        $this->fields = array_merge($this->fields, $fldAr);
107
108
        return $this;
109
    }
110
111
    public function join($join, $mixedParam, $param3 = null, $param4 = null, $mixedParam2 = null)
112
    {
113
        $this->join = array_merge($this->join, [[$join, $mixedParam, $param3, $param4, $mixedParam2]]);
114
115
        return $this;
116
    }
117
118
    public function leftJoin($leftJoin, $mixedParam, $param3 = null, $param4 = null, $mixedParam2 = null)
119
    {
120
        $this->leftJoin = array_merge($this->leftJoin, [[$leftJoin, $mixedParam, $param3, $param4, $mixedParam2]]);
121
122
        return $this;
123
    }
124
125
    public function rightJoin($rightJoin, $mixedParam, $param3 = null, $param4 = null, $mixedParam2 = null)
126
    {
127
        $this->rightJoin = array_merge($this->rightJoin, [[$rightJoin, $mixedParam, $param3, $param4, $mixedParam2]]);
128
129
        return $this;
130
    }
131
132
    public function crossJoin($crossJoin, $params = null)
133
    {
134
        $this->crossJoin = array_merge($this->crossJoin, [[$crossJoin, $params]]);
135
136
        return $this;
137
    }
138
139
    public function where()
140
    {
141
        $args = func_get_args();
142
        if(func_num_args()===2){
143
            $this->where = array_merge($this->where, [[$args[0], '=', $args[1]]]);
144
        } elseif(func_num_args()===3){
145
            $this->where = array_merge($this->where, [[$args[0], $args[1], $args[2]]]);
146
        } else{
147
            throw new Exception('Where parameter contains invalid number of parameters', 1);
148
        }
149
150
        return $this;
151
    }
152
153
    public function whereIn($whereIn, $params = array())
154
    {
155
        $this->whereIn = array_merge($this->whereIn, [[$whereIn, $params]]);
156
157
        return $this;
158
    }
159
160
    public function whereNotIn($whereNotIn, $params = array())
161
    {
162
        $this->whereNotIn = array_merge($this->whereNotIn, [[$whereNotIn, $params]]);
163
164
        return $this;
165
    }
166
167
    public function whereNull($whereNull)
168
    {
169
        $this->whereNull = array_merge($this->whereNull, [$whereNull]);
170
171
        return $this;
172
    }
173
174
    public function whereNotNull($whereNotNull)
175
    {
176
        $this->whereNotNull = array_merge($this->whereNotNull, [$whereNotNull]);
177
178
        return $this;
179
    }
180
181
    public function offset($offset)
182
    {
183
        $this->offset = $offset;
184
185
        return $this;
186
    }
187
188
    public function limit($limit)
189
    {
190
        $this->limit = $limit;
191
192
        return $this;
193
    }
194
195
    public function orderBy($orderBy)
196
    {
197
        $this->orderBy = $orderBy;
198
199
        return $this;
200
    }
201
202
    public function groupBy($groupBy)
203
    {
204
        $this->groupBy = $groupBy;
205
206
        return $this;
207
    }
208
209
    public function having($having)
210
    {
211
        $this->having = $having;
212
213
        return $this;
214
    }
215
216
    /**
217
     * Builds Query added by method chaining.
218
     * It has the main logic of ORM
219
     */
220
    protected function buildQuery()
221
    {
222
        $query = array();
223
        $tblWithPrefix = $this->table;
224
        $qb     = new QueryBuilder();
225
        $jqb = new JoinQueryBuilder();
226
        $wqb = new WhereQueryBuilder();
227
        $prefix = $qb->getPrefix();
228
        $tbl    = str_replace($prefix, '', $tblWithPrefix);
229
230
        $query[] = 'SELECT';
231
        if (empty($this->fields)) {
232
            $query[] = $qb->quote($tbl).'.*';
233
        } else {
234
            $query[] = join(', ', $this->fields);
235
        }
236
237
        $query[] = 'FROM';
238
        $query[] = $qb->quote($tblWithPrefix).' AS '.$qb->quote($tbl);
239
240
        $allJoinQuery = $jqb->buildAllJoinQuery(
241
                                $this->join, 
242
                                $this->leftJoin, 
243
                                $this->rightJoin, 
244
                                $this->crossJoin
245
                            );
246
        if (count($allJoinQuery)) {
247
            $query = array_merge($query, $allJoinQuery);
248
        }
249
250
        $allWhereQuery = $wqb->buildAllWhereQuery(
251
                                    $this->where, 
252
                                    $this->whereIn, 
253
                                    $this->whereNotIn, 
254
                                    $this->whereNull, 
255
                                    $this->whereNotNull
256
                                );
257
        if (count($allWhereQuery)) {
258
            $query = array_merge($query, $allWhereQuery);
259
        }
260
261
        if (!empty($this->groupBy)) {
262
            $query[] = 'GROUP BY';
263
            $query[] = $this->groupBy;
264
        }
265
266
        if (!empty($this->having)) {
267
            $query[] = 'HAVING';
268
            $query[] = $this->having;
269
        }
270
271
        if (!empty($this->orderBy)) {
272
            $query[] = 'ORDER BY';
273
            $query[] = $this->orderBy;
274
        }
275
276
        if (!empty($this->limit)) {
277
            $query[] = 'LIMIT';
278
279
            if (!empty($this->offset)) {
280
                $query[] = $this->offset.',';
281
            }
282
283
            $query[] = $this->limit;
284
        }
285
286
        return join(' ', $query);
287
    }
288
289
    protected function reset()
290
    {
291
        $this->fields = array();
292
        $this->table = null;
293
        $this->className = null;
294
        $this->groupBy = null;
295
        $this->orderBy = null;
296
        $this->having = null;
297
        $this->join = array();
298
        $this->leftJoin = array();
299
        $this->rightJoin = array();
300
        $this->crossJoin = array();
301
        $this->where = array();
302
        $this->whereIn = array();
303
        $this->whereNotIn = array();
304
        $this->whereNull = array();
305
        $this->whereNotNull = array();
306
        $this->limit = null;
307
        $this->offset = null;
308
    }
309
310
    public function prepare($query, $fetchRows = 'all')
311
    {
312
        $qb = new QueryBuilder();
313
        $wqp = new WhereQueryParser();
314
        $util = new Utils();
315
        
316
        try {
317
            $ar = $wqp->parseWhereQuery($this->where);
318
            $stmt = Connection::get()->prepare($qb->queryPrefix($query));
319
            $stmt->execute($ar);
320
321
            if ($fetchRows == 'first') {
322
                $rows = $stmt->fetch(\PDO::FETCH_OBJ);
323
                $this->results = $rows;
324
                // now turn this stdClass object to the object type of calling model
325
                $rows = $util->turnObject($this->className, $rows);
326
            } else {
327
                $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
328
                $this->results = $rows;
329
                $rows = $util->turnObjects($this->className, $rows);
330
            }
331
332
            // Reset class variables
333
            $this->reset();
334
335
            return $rows;
336
        } catch (\PDOException $ex) {
337
            throw new \PDOException($ex->getMessage(), 1);
338
        } catch (Exception $e) {
339
            throw new Exception($e->getMessage(), 1);
340
        }
341
    }
342
343
    public function query($query, $fetchRows = 'all')
344
    {
345
        $qb = new QueryBuilder();
346
347
        try {
348
            $obj = Connection::get()->query($qb->queryPrefix($query), \PDO::FETCH_OBJ);
349
350
            if ($fetchRows == 'count') {
351
                $data = $obj->fetchColumn();
352
            }
353
354
            // Reset class variables
355
            $this->reset();
356
357
            return isset($data) ? $data : $obj;
358
        } catch (\PDOException $ex) {
359
            throw new \PDOException($ex->getMessage(), 1);
360
        } catch (Exception $e) {
361
            throw new Exception($e->getMessage(), 1);
362
        }
363
    }
364
365
    public function get()
366
    {
367
        return $this->prepare($this->buildQuery());
368
    }
369
370
    public function first()
371
    {
372
        $query = $this->buildQuery();
373
374
        if (strripos($query, 'LIMIT 1')) {
375
            // [TODO]
376
        } else {
377
            $query .= ' LIMIT 1';
378
        }
379
380
        return $this->prepare($query, 'first');
381
    }
382
383
    /**
384
     * It fetches the row by primary key
385
     * 
386
     * @author RN Kushwaha <[email protected]>
387
     * @since v0.0.5 
388
     */
389
    public function find($id)
390
    {
391
        $this->where('id = :id', $id);
392
        
393
        return $this->first();
394
    }
395
396
    /**
397
     * It fetches the row by primary key
398
     * 
399
     * @param int $id
400
     * @return object $row
401
     * @throws Exception
402
     * @author RN Kushwaha <[email protected]>
403
     * @since v0.0.5 
404
     */
405
    public function findOrFail($id)
406
    {
407
        $this->where('id = :id', $id);
408
        
409
        $row = $this->first();
410
411
        if($row == null ){
412
            throw new Exception("The record does not exists!");
413
        }
414
415
        return $row;
416
    }
417
418
    public function count()
419
    {
420
        $this->fields = null;
421
        $query = $this->buildQuery();
422
        $query = str_replace('SELECT * ', 'SELECT COUNT(*) as count ', $query);
423
424
        return $this->query($query, 'count');
425
    }
426
427
    /**
428
     * It truncates the table
429
     * 
430
     * @return boolean
431
     * @throws Exception
432
     * @author RN Kushwaha <[email protected]>
433
     * @since v0.0.5 
434
     */
435
    public function truncate()
436
    {
437
        $qb = new QueryBuilder();
438
        $query = "TRUNCATE ".$this->table;
439
        
440
        try{
441
            Connection::get()->query($qb->queryPrefix($query));
442
        } catch(Exception $e){
443
            throw new Exception($e->getMessage());
444
        }
445
446
        return true;
447
    }
448
449
    /**
450
     * It inserts the new rows
451
     * 
452
     * @param array $rows
453
     * @return integer $lastInsertedId
454
     * @throws Exception
455
     * @author RN Kushwaha <[email protected]>
456
     * @since v0.0.5 
457
     */
458
    public function insert($rows)
459
    {
460
        $iqb = new InsertQueryBuilder();
461
        return $iqb->insert($rows, $this->table);
462
    }
463
464
    /**
465
     * It updates the rows
466
     * 
467
     * @param array $row
468
     * @return boolean
469
     * @throws Exception
470
     * @author RN Kushwaha <[email protected]>
471
     * @since v0.0.5 
472
     */
473
    public function update($row)
474
    {
475
        $qb = new QueryBuilder();
476
        $wqb = new WhereQueryBuilder();
477
        $query = "UPDATE ".$this->table." SET ";
478
        $ar = array();
479
        
480
        foreach($row as $key => $val){
481
            $ar[':'.$key] = $val;
482
            $query.= $qb->quote($key)." =:".$key.",";
483
        }
484
485
        $query = rtrim($query, ",");
486
        
487
        try{
488
            $whereQuery = $wqb->buildAllWhereQuery(
489
                                $this->where, 
490
                                $this->whereIn, 
491
                                $this->whereNotIn, 
492
                                $this->whereNull, 
493
                                $this->whereNotNull
494
                            );
495
            $query.= " ".join(" ", $whereQuery);
496
            $stmt = Connection::get()->prepare($qb->queryPrefix($query));
497
            $stmt->execute($ar);
498
            $this->reset();
499
        } catch(Exception $e){
500
            throw new Exception($e->getMessage());
501
        }
502
503
        return true;
504
    }
505
506
    /**
507
     * It deleted the rows matched by where clause
508
     * 
509
     * @return boolean
510
     * @throws Exception
511
     * @author RN Kushwaha <[email protected]>
512
     * @since v0.0.5 
513
     */
514
    public function delete()
515
    {
516
        $qb = new QueryBuilder();
517
        $wqb = new WhereQueryBuilder();
518
        $query = "DELETE FROM ".$this->table;
519
        
520
        try{
521
            $whereQuery = $wqb->buildAllWhereQuery(
522
                                    $this->where, 
523
                                    $this->whereIn, 
524
                                    $this->whereNotIn, 
525
                                    $this->whereNull, 
526
                                    $this->whereNotNull
527
                                );
528
            $query.= " ".join(" ", $whereQuery);
529
            Connection::get()->query($qb->queryPrefix($query));
530
            $this->reset();
531
        } catch(Exception $e){
532
            throw new Exception($e->getMessage());
533
        }
534
535
        return true;
536
    }
537
538
}
539