Passed
Push — master ( 36c8a5...213898 )
by RN
01:43
created

Dolphin::all()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 1
Metric Value
cc 1
eloc 2
c 1
b 1
f 1
nc 1
nop 0
dl 0
loc 5
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
        return $this->prepare($query, 'first');
303
    }
304
305
    public function all()
306
    {
307
        $query = $this->buildQuery();
308
309
        return $this->prepare($query);
310
    }
311
312
    /**
313
     * It fetches the row by primary key
314
     *
315
     * @since v0.0.5
316
     */
317
    public function find($id)
318
    {
319
        $this->where('id', $id);
320
321
        return $this->first();
322
    }
323
324
    /**
325
     * It fetches the row by primary key
326
     *
327
     * @param int $id
328
     * @return object $row
329
     * @throws Exception
330
     * @since v0.0.5
331
     */
332
    public function findOrFail($id)
333
    {
334
        $this->where('id', $id);
335
        $row = $this->first();
336
337
        if($row == null ){
338
            throw new Exception("The record does not exists!");
339
        }
340
341
        return $row;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $row returns the type true which is incompatible with the documented return type object.
Loading history...
342
    }
343
344
    public function count()
345
    {
346
        $this->fields = null;
347
        $query = $this->buildQuery();
348
        $query = str_replace('SELECT * ', 'SELECT COUNT(*) as count ', $query);
349
350
        return $this->query($query, 'count');
351
    }
352
353
    /**
354
     * It inserts the new rows
355
     *
356
     * @param array $rows
357
     * @return integer $lastInsertedId
358
     * @throws Exception
359
     * @since v0.0.5
360
     */
361
    public function insert($rows)
362
    {
363
        return (new InsertQueryBuilder())->insert($rows, $this->table);
364
    }
365
366
    /**
367
     * It updates the rows
368
     *
369
     * @param array $row
370
     * @return boolean
371
     * @throws Exception
372
     * @since v0.0.5
373
     */
374
    public function update($row)
375
    {
376
        $result =  (new UpdateQueryBuilder())->update(
377
          $row,
378
          $this->table,
379
          $this->where,
380
          $this->whereRaw,
381
          $this->whereIn,
382
          $this->whereNotIn,
383
          $this->whereNull,
384
          $this->whereNotNull
385
        );
386
387
        $this->reset();
388
389
        return $result;
390
    }
391
392
    /**
393
     * It truncates the table
394
     *
395
     * @return boolean
396
     * @throws Exception
397
     * @since v0.0.5
398
     */
399
    public function truncate()
400
    {
401
        $qb = new QueryBuilder();
402
        $query = "TRUNCATE ".$this->table;
403
404
        try{
405
            Connection::get()->query($qb->queryPrefix($query));
406
        } catch(Exception $e){
407
            throw new Exception($e->getMessage());
408
        }
409
410
        return true;
411
    }
412
413
    /**
414
     * It deleted the rows matched by where clause
415
     *
416
     * @return boolean
417
     * @throws Exception
418
     * @since v0.0.5
419
     */
420
    public function delete()
421
    {
422
        $result =  (new DeleteQueryBuilder())->delete(
423
          $this->table,
424
          $this->where,
425
          $this->whereRaw,
426
          $this->whereIn,
427
          $this->whereNotIn,
428
          $this->whereNull,
429
          $this->whereNotNull
430
        );
431
432
        $this->reset();
433
434
        return $result;
435
    }
436
437
}
438