CrudBuilder::innerJoin()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 9
c 0
b 0
f 0
nc 2
nop 3
dl 0
loc 11
rs 9.9666
1
<?php
2
3
namespace BMorais\Database;
4
5
/**
6
 * CLASS CrudBuilder
7
 * Basic class to make connection between the database and the application
8
 *
9
 * @author Bruno Morais <[email protected]>
10
 * @copyright MIT, bmorais.com
11
 * @package bmorais\database
12
 * @subpackage class
13
 * @access protected
14
 */
15
abstract class CrudBuilder extends Crud
16
{
17
    /**
18
     * @var array
19
     */
20
    private array $sqlPartsSelect = [
21
        'main'      => [],
22
        'join'      => [],
23
        'where'     => "",
24
        'andWhere'  => [],
25
        'orWhere'   => [],
26
        'groupBy'   => [],
27
        'having'    => [],
28
        'andHaving' => [],
29
        'orHaving'  => [],
30
        'orderBy'   => "",
31
        'addOrderBy'=> [],
32
        'limit'     => "",
33
        'offset'    => "",
34
    ];
35
36
    /**
37
     *
38
     * <code>
39
     *   $qb = $this->select('u.id, p.id')
40
     *           ->where('phonenumbers=?', [$number]);
41
     * </code>
42
     * @param string $fields
43
     * @param array $paramns
44
     * @return $this
45
     * @throws DatabaseException
46
     */
47
    protected function selectBuilder(string $fields = "*", array $paramns = []): self
48
    {
49
        try {
50
            $query = "SELECT {$fields} FROM {$this->getTableName()}";
51
            if (!empty($this->getTableAlias()))
52
                $query .= " AS {$this->getTableAlias()}";
53
            $this->add($query, "main", $paramns);
54
            return $this;
55
        } catch (\PDOException $e) {
56
            throw new DatabaseException(
57
                "Select builder failed - TABLE: [{$this->getTableName()}] MESSAGE: [{$e->getMessage()}]",
58
                $e->getCode(),
59
                $e
60
            );
61
        }
62
    }
63
64
    /**
65
     * @param string $fields
66
     * @param array $paramns
67
     * @return $this
68
     * @throws DatabaseException
69
     */
70
    protected function insertBuilder(string $fields, array $paramns): self
71
    {
72
        try {
73
            $numparams = '';
74
            foreach ($paramns as $item) {
75
                $numparams .= ',?';
76
            }
77
            $numparams = substr($numparams, 1);
78
            $query = "INSERT INTO {$this->getTableName()} ({$fields}) VALUES ({$numparams})";
79
            $this->add($query, "main", $paramns);
80
            return $this;
81
        } catch (\PDOException $e) {
82
            throw new DatabaseException(
83
                "Insert builder failed - TABLE: [{$this->getTableName()}] MESSAGE: [{$e->getMessage()}]",
84
                $e->getCode(),
85
                $e
86
            );
87
        }
88
    }
89
90
    /**
91
     * @param string $fields
92
     * @param array $paramns
93
     * @return $this
94
     * @throws DatabaseException
95
     */
96
    protected function updateBuilder(string $fields, array $paramns): self
97
    {
98
        try {
99
            $fields_T = '';
100
            $atributos = explode(',', $fields);
101
102
            foreach ($atributos as $item) {
103
                $fields_T .= ", {$item} = ?";
104
            }
105
            $fields_T = substr($fields_T, 2);
106
            $query = "UPDATE {$this->getTableName()} SET {$fields_T}";
107
            $this->add($query, "main", $paramns);
108
            return $this;
109
        } catch (\PDOException $e) {
110
            throw new DatabaseException(
111
                "Update builder failed - TABLE: [{$this->getTableName()}] MESSAGE: [{$e->getMessage()}]",
112
                $e->getCode(),
113
                $e
114
            );
115
        }
116
    }
117
118
    /**
119
     * @param string $fields
120
     * @param array $paramns
121
     * @return $this
122
     * @throws DatabaseException
123
     */
124
    protected function deleteBuilder(): self
125
    {
126
        try {
127
            $query = "DELETE FROM {$this->getTableName()}";
128
            $this->add($query, "main");
129
            return $this;
130
        } catch (\PDOException $e) {
131
            throw new DatabaseException(
132
                "Delete builder failed - TABLE: [{$this->getTableName()}] MESSAGE: [{$e->getMessage()}]",
133
                $e->getCode(),
134
                $e
135
            );
136
        }
137
    }
138
139
    /**
140
     * @param string $query
141
     * @param array $paramns
142
     * @return $this
143
     * @throws DatabaseException
144
     */
145
    protected function query(string $query, array $paramns = []): self
146
    {
147
        try {
148
            $this->add($query, "main", $paramns);
149
            return $this;
150
        } catch (\PDOException $e) {
151
            throw new DatabaseException(
152
                "Query builder failed - TABLE: [{$this->getTableName()}] MESSAGE: [{$e->getMessage()}]",
153
                $e->getCode(),
154
                $e
155
            );
156
        }
157
    }
158
159
    /**
160
     * @param string $texto
161
     * @param array $paramns
162
     * @return $this
163
     * @throws DatabaseException
164
     */
165
    protected function where(string $texto, array $paramns = []): self
166
    {
167
        try {
168
            $query = "WHERE {$texto}";
169
            $this->add($query, "where", $paramns);
170
            return $this;
171
        } catch (\PDOException $e) {
172
            throw new DatabaseException(
173
                "Where clause failed - TABLE: [{$this->getTableName()}] MESSAGE: [{$e->getMessage()}]",
174
                $e->getCode(),
175
                $e
176
            );
177
        }
178
    }
179
180
    /**
181
     * @param string $condition
182
     * @param array $paramns
183
     * @return $this
184
     * @throws DatabaseException
185
     */
186
    protected function andWhere(string $condition, array $paramns = []): self
187
    {
188
        try {
189
            $query = "AND {$condition}";
190
            $this->add($query, "andWhere", $paramns);
191
            return $this;
192
        } catch (\PDOException $e) {
193
            throw new DatabaseException(
194
                "And where clause failed - TABLE: [{$this->getTableName()}] MESSAGE: [{$e->getMessage()}]",
195
                $e->getCode(),
196
                $e
197
            );
198
        }
199
    }
200
201
    /**
202
     * @param string $condition
203
     * @param array $paramns
204
     * @return $this
205
     * @throws DatabaseException
206
     */
207
    protected function orWhere(string $condition, array $paramns = []): self
208
    {
209
        try {
210
            $query = "OR {$condition}";
211
            $this->add($query, "orWhere", $paramns);
212
            return $this;
213
        } catch (\PDOException $e) {
214
            throw new DatabaseException(
215
                "Or where clause failed - TABLE: [{$this->getTableName()}] MESSAGE: [{$e->getMessage()}]",
216
                $e->getCode(),
217
                $e
218
            );
219
        }
220
    }
221
222
    /**
223
     * @param string $parameter
224
     * @param string|null $order
225
     * @return $this
226
     * @throws DatabaseException
227
     */
228
    protected function orderBy(string $parameter, ?string $order = null): self
229
    {
230
        try {
231
            $query = "ORDER BY {$parameter} ".($order ?? 'ASC');
232
            $this->add($query, "orderBy");
233
            return $this;
234
        } catch (\PDOException $e) {
235
            throw new DatabaseException(
236
                "Order by clause failed - TABLE: [{$this->getTableName()}] MESSAGE: [{$e->getMessage()}]",
237
                $e->getCode(),
238
                $e
239
            );
240
        }
241
    }
242
243
    /**
244
     * @param string $parameter
245
     * @param string|null $order
246
     * @return $this
247
     * @throws DatabaseException
248
     */
249
    protected function addOrderBy(string $parameter, ?string $order = null): self
250
    {
251
        try {
252
            $query = ", {$parameter} ".($order ?? 'ASC')." ";
253
            $this->add($query, "addOrderBy");
254
            return $this;
255
        } catch (\PDOException $e) {
256
            throw new DatabaseException(
257
                "Add order by clause failed - TABLE: [{$this->getTableName()}] MESSAGE: [{$e->getMessage()}]",
258
                $e->getCode(),
259
                $e
260
            );
261
        }
262
    }
263
264
    /**
265
     * @param string $texto
266
     * @return $this
267
     */
268
    protected function limit(string $texto): self
269
    {
270
        $query = "LIMIT {$texto}";
271
        $this->add($query,"limit");
272
        return $this;
273
    }
274
275
    /**
276
     * @param string $texto
277
     * @return $this
278
     * @throws DatabaseException
279
     */
280
    protected function offset(string $texto): self
281
    {
282
        try {
283
            $query = "OFFSET {$texto}";
284
            $this->add($query,"offset");
285
            return $this;
286
        } catch (\PDOException $e) {
287
            throw new DatabaseException(
288
                "Offset clause failed - TABLE: [{$this->getTableName()}] MESSAGE: [{$e->getMessage()}]",
289
                $e->getCode(),
290
                $e
291
            );
292
        }
293
    }
294
295
    /**
296
     * @param string $texto
297
     * @return $this
298
     * @throws DatabaseException
299
     */
300
    protected function groupBy(string $texto): self
301
    {
302
        try {
303
            $query = "GROUP BY {$texto}";
304
            $this->add($query,"groupBy");
305
            return $this;
306
        } catch (\PDOException $e) {
307
            throw new DatabaseException(
308
                "Group by clause failed - TABLE: [{$this->getTableName()}] MESSAGE: [{$e->getMessage()}]",
309
                $e->getCode(),
310
                $e
311
            );
312
        }
313
    }
314
315
    /**
316
     * @param string $texto
317
     * @return $this
318
     * @throws DatabaseException
319
     */
320
    protected function having(string $texto): self
321
    {
322
        try {
323
            $query = "HAVING {$texto}";
324
            $this->add($query,"having");
325
            return $this;
326
        } catch (\PDOException $e) {
327
            throw new DatabaseException(
328
                "Having clause failed - TABLE: [{$this->getTableName()}] MESSAGE: [{$e->getMessage()}]",
329
                $e->getCode(),
330
                $e
331
            );
332
        }
333
    }
334
335
    /**
336
     * @param string $texto
337
     * @return $this
338
     * @throws DatabaseException
339
     */
340
    protected function andHaving(string $texto): self
341
    {
342
        try {
343
            $query = "AND {$texto}";
344
            $this->add($query,"andHaving");
345
            return $this;
346
        } catch (\PDOException $e) {
347
            throw new DatabaseException(
348
                "And having clause failed - TABLE: [{$this->getTableName()}] MESSAGE: [{$e->getMessage()}]",
349
                $e->getCode(),
350
                $e
351
            );
352
        }
353
    }
354
355
    /**
356
     * @param string $codition
357
     * @return $this
358
     * @throws DatabaseException
359
     */
360
    protected function orHaving(string $codition): self
361
    {
362
        try {
363
            $query = "OR {$codition}";
364
            $this->add($query,"orHaving");
365
            return $this;
366
        } catch (\PDOException $e) {
367
            throw new DatabaseException(
368
                "Or having clause failed - TABLE: [{$this->getTableName()}] MESSAGE: [{$e->getMessage()}]",
369
                $e->getCode(),
370
                $e
371
            );
372
        }
373
    }
374
375
    /**
376
     * @param string $table
377
     * @param string $alias
378
     * @param string $codition
379
     * @return $this
380
     * @throws DatabaseException
381
     */
382
    protected function innerJoin(string $table, string $alias, string $codition): self
383
    {
384
        try {
385
            $query = "INNER JOIN {$table} AS {$alias} ON $codition";
386
            $this->add($query,"join");
387
            return $this;
388
        } catch (\PDOException $e) {
389
            throw new DatabaseException(
390
                "Inner join failed - TABLE: [{$this->getTableName()}] MESSAGE: [{$e->getMessage()}]",
391
                $e->getCode(),
392
                $e
393
            );
394
        }
395
    }
396
397
    /**
398
     * @param string $table
399
     * @param string $alias
400
     * @param string $codition
401
     * @return $this
402
     * @throws DatabaseException
403
     */
404
    protected function leftJoin(string $table, string $alias, string $codition): self
405
    {
406
        try {
407
            $query = "LEFT JOIN {$table} AS {$alias} ON {$codition}";
408
            $this->add($query,"join");
409
            return $this;
410
        } catch (\PDOException $e) {
411
            throw new DatabaseException(
412
                "Left join failed - TABLE: [{$this->getTableName()}] MESSAGE: [{$e->getMessage()}]",
413
                $e->getCode(),
414
                $e
415
            );
416
        }
417
    }
418
419
    /**
420
     * @param string $table
421
     * @param string $alias
422
     * @param string $codition
423
     * @return $this
424
     * @throws DatabaseException
425
     */
426
    protected function rightJoin(string $table, string $alias, string $codition): self
427
    {
428
        try {
429
            $query = "RIGHT JOIN {$table} AS {$alias} ON $codition";
430
            $this->add($query,"join");
431
            return $this;
432
        } catch (\PDOException $e) {
433
            throw new DatabaseException(
434
                "Right join failed - TABLE: [{$this->getTableName()}] MESSAGE: [{$e->getMessage()}]",
435
                $e->getCode(),
436
                $e
437
            );
438
        }
439
    }
440
441
    /**
442
     * @return $this
443
     * @throws DatabaseException
444
     */
445
    protected function executeQuery(): self
446
    {
447
        try {
448
            foreach ($this->sqlPartsSelect as $key => $part){
449
                if (is_array($part)) {
450
                    foreach ($part as $item){
451
                        $this->setQuery($this->getQuery().$item);
452
                    }
453
                } else {
454
                    $this->setQuery($this->getQuery().$part);
455
                }
456
457
            }
458
459
            $this->executeSQL($this->getQuery(), $this->getParams());
460
            return $this;
461
        } catch (\PDOException $e) {
462
            throw new DatabaseException(
463
                "Execute query failed - TABLE: [{$this->getTableName()}] MESSAGE: [{$e->getMessage()}]",
464
                $e->getCode(),
465
                $e,
466
                $this->getQuery(),
467
                $this->getParams()
468
            );
469
        }
470
    }
471
472
    /**
473
     * @return void
474
     * @throws DatabaseException
475
     */
476
    protected function debug(): void
477
    {
478
        try {
479
            echo $this->getQuery() . '<pre>' . print_r($this->getParams()) . '</pre>';
0 ignored issues
show
Bug introduced by
Are you sure print_r($this->getParams()) of type string|true can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

479
            echo $this->getQuery() . '<pre>' . /** @scrutinizer ignore-type */ print_r($this->getParams()) . '</pre>';
Loading history...
480
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
481
        } catch (\PDOException $e) {
482
            throw new DatabaseException(
483
                "Debug failed - TABLE: [{$this->getTableName()}] MESSAGE: [{$e->getMessage()}]",
484
                $e->getCode(),
485
                $e
486
            );
487
        }
488
    }
489
490
    /**
491
     * @param string $query
492
     * @param string $type
493
     * @param array $params
494
     * @return void
495
     * @throws DatabaseException
496
     */
497
    private function add(string $query, string $type, array $params = []): void
498
    {
499
        $query = $query." ";
500
        try {
501
            if (is_array($this->sqlPartsSelect[$type])) {
502
                $this->sqlPartsSelect[$type][] = $query;
503
            } else {
504
                $this->sqlPartsSelect[$type] = $query;
505
            }
506
507
            if (!empty($params))
508
                $this->setParams($params);
509
        } catch (\PDOException $e) {
510
            throw new DatabaseException(
511
                "Add query part failed - TABLE: [{$this->getTableName()}] MESSAGE: [{$e->getMessage()}]",
512
                $e->getCode(),
513
                $e
514
            );
515
        }
516
    }
517
}