Passed
Push — master ( 1b5140...aad147 )
by RN
02:02
created

Dolphin::having()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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