Test Failed
Push — 1.0.0-dev ( 6506b5...225896 )
by nguereza
05:07
created

Database::connect()   B

Complexity

Conditions 9
Paths 32

Size

Total Lines 32
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 24
c 0
b 0
f 0
nc 32
nop 0
dl 0
loc 32
rs 8.0555
1
<?php
2
    defined('ROOT_PATH') || exit('Access denied');
3
  /**
4
   * TNH Framework
5
   *
6
   * A simple PHP framework using HMVC architecture
7
   *
8
   * This content is released under the GNU GPL License (GPL)
9
   *
10
   * Copyright (C) 2017 Tony NGUEREZA
11
   *
12
   * This program is free software; you can redistribute it and/or
13
   * modify it under the terms of the GNU General Public License
14
   * as published by the Free Software Foundation; either version 3
15
   * of the License, or (at your option) any later version.
16
   *
17
   * This program is distributed in the hope that it will be useful,
18
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
   * GNU General Public License for more details.
21
   *
22
   * You should have received a copy of the GNU General Public License
23
   * along with this program; if not, write to the Free Software
24
   * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
  */
26
  class Database{
27
	
28
	/**
29
	 * The PDO instance
30
	 * @var object
31
	*/
32
    private $pdo                 = null;
33
    
34
	/**
35
	 * The database name used for the application
36
	 * @var string
37
	*/
38
	private $databaseName        = null;
39
    
40
	/**
41
	 * The SQL SELECT statment
42
	 * @var string
43
	*/
44
	private $select              = '*';
45
	
46
	/**
47
	 * The SQL FROM statment
48
	 * @var string
49
	*/
50
    private $from                = null;
51
	
52
	/**
53
	 * The SQL WHERE statment
54
	 * @var string
55
	*/
56
    private $where               = null;
57
	
58
	/**
59
	 * The SQL LIMIT statment
60
	 * @var string
61
	*/
62
    private $limit               = null;
63
	
64
	/**
65
	 * The SQL JOIN statment
66
	 * @var string
67
	*/
68
    private $join                = null;
69
	
70
	/**
71
	 * The SQL ORDER BY statment
72
	 * @var string
73
	*/
74
    private $orderBy             = null;
75
	
76
	/**
77
	 * The SQL GROUP BY statment
78
	 * @var string
79
	*/
80
    private $groupBy             = null;
81
	
82
	/**
83
	 * The SQL HAVING statment
84
	 * @var string
85
	*/
86
    private $having              = null;
87
	
88
	/**
89
	 * The number of rows returned by the last query
90
	 * @var int
91
	*/
92
    private $numRows             = 0;
93
	
94
	/**
95
	 * The last insert id for the primary key column that have auto increment or sequence
96
	 * @var mixed
97
	*/
98
    private $insertId            = null;
99
	
100
	/**
101
	 * The full SQL query statment after build for each command
102
	 * @var string
103
	*/
104
    private $query               = null;
105
	
106
	/**
107
	 * The error returned for the last query
108
	 * @var string
109
	*/
110
    private $error               = null;
111
	
112
	/**
113
	 * The result returned for the last query
114
	 * @var mixed
115
	*/
116
    private $result              = array();
117
	
118
	/**
119
	 * The prefix used in each database table
120
	 * @var string
121
	*/
122
    private $prefix              = null;
123
	
124
	/**
125
	 * The list of SQL valid operators
126
	 * @var array
127
	*/
128
    private $operatorList        = array('=','!=','<','>','<=','>=','<>');
129
    
130
	/**
131
	 * The cache default time to live in second. 0 means no need to use the cache feature
132
	 * @var int
133
	*/
134
	private $cacheTtl              = 0;
135
	
136
	/**
137
	 * The cache current time to live. 0 means no need to use the cache feature
138
	 * @var int
139
	*/
140
    private $temporaryCacheTtl   = 0;
141
	
142
	/**
143
	 * The number of executed query for the current request
144
	 * @var int
145
	*/
146
    private $queryCount          = 0;
147
	
148
	/**
149
	 * The default data to be used in the statments query INSERT, UPDATE
150
	 * @var array
151
	*/
152
    private $data                = array();
153
	
154
	/**
155
	 * The database configuration
156
	 * @var array
157
	*/
158
    private $config              = array();
159
	
160
	/**
161
	 * The logger instance
162
	 * @var Log
163
	 */
164
    private $logger              = null;
165
166
167
    /**
168
    * The cache instance
169
    * @var CacheInterface
170
    */
171
    private $cacheInstance       = null;
172
173
     /**
174
    * The benchmark instance
175
    * @var Benchmark
176
    */
177
    private $benchmarkInstance   = null;
178
179
180
    /**
181
     * Construct new database
182
     * @param array $overwriteConfig the config to overwrite with the config set in database.php
183
     * @param object $logger the log instance
184
     */
185
    public function __construct($overwriteConfig = array(), Log $logger = null){
186
        /**
187
         * instance of the Log class
188
         */
189
        if(is_object($logger)){
190
          $this->logger = $logger;
191
        }
192
        else{
193
            $this->logger =& class_loader('Log', 'classes');
194
            $this->logger->setLogger('Library::Database');
195
        }
196
197
        $db = array();
198
      	if(file_exists(CONFIG_PATH . 'database.php')){
199
          //here don't use require_once because somewhere user can create database instance directly
200
      	  require CONFIG_PATH . 'database.php';
201
        }
202
          
203
				if(! empty($overwriteConfig)){
204
				  $db = array_merge($db, $overwriteConfig);
205
				}
206
				$config['driver']    = isset($db['driver']) ? $db['driver'] : 'mysql';
0 ignored issues
show
Comprehensibility Best Practice introduced by
$config was never initialized. Although not strictly required by PHP, it is generally a good practice to add $config = array(); before regardless.
Loading history...
207
				$config['username']  = isset($db['username']) ? $db['username'] : 'root';
208
				$config['password']  = isset($db['password']) ? $db['password'] : '';
209
				$config['database']  = isset($db['database']) ? $db['database'] : '';
210
				$config['hostname']  = isset($db['hostname']) ? $db['hostname'] : 'localhost';
211
				$config['charset']   = isset($db['charset']) ? $db['charset'] : 'utf8';
212
				$config['collation'] = isset($db['collation']) ? $db['collation'] : 'utf8_general_ci';
213
				$config['prefix']    = isset($db['prefix']) ? $db['prefix'] : '';
214
        $port = '';
215
        if(strstr($config['hostname'], ':')){
216
          $p = explode(':', $config['hostname']);
217
          $port = isset($p[1]) ? $p[1] : '';
218
        }
219
				$config['port']      = $port;
220
				
221
		  	$this->setDatabaseConfiguration($config);
222
223
    		$this->temporaryCacheTtl = $this->cacheTtl;
224
    }
225
226
    /**
227
     * This is used to connect to database
228
     * @return bool 
229
     */
230
    public function connect(){
231
      $config = $this->getDatabaseConfiguration();
232
      if(! empty($config)){
233
        try{
234
            $dsn = '';
235
            if($config['driver'] == 'mysql' || $config['driver'] == '' || $config['driver'] == 'pgsql'){
236
                $dsn = $config['driver'] . ':host=' . $config['hostname'] . ';'
237
                . (($config['port']) != '' ? 'port=' . $config['port'] . ';' : '')
238
                . 'dbname=' . $config['database'];
239
            }
240
            else if ($config['driver'] == 'sqlite'){
241
              $dsn = 'sqlite:' . $config['database'];
242
            }
243
            else if($config['driver'] == 'oracle'){
244
              $dsn = 'oci:dbname=' . $config['host'] . '/' . $config['database'];
245
            }
246
            
247
            $this->pdo = new PDO($dsn, $config['username'], $config['password']);
248
            $this->pdo->exec("SET NAMES '" . $config['charset'] . "' COLLATE '" . $config['collation'] . "'");
249
            $this->pdo->exec("SET CHARACTER SET '" . $config['charset'] . "'");
250
            $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
251
            return true;
252
          }
253
          catch (PDOException $e){
254
            $this->logger->fatal($e->getMessage());
255
            show_error('Cannot connect to Database.');
256
            return false;
257
          }
258
      }
259
      else{
260
        show_error('Database configuration is not set.');
261
        return false;
262
      }
263
    }
264
265
    /**
266
     * Set the SQL FROM statment
267
     * @param  string|array $table the table name or array of table list
268
     * @return object        the current Database instance
269
     */
270
    public function from($table){
271
      if(is_array($table)){
272
        $froms = '';
273
        foreach($table as $key){
274
          $froms .= $this->prefix . $key . ', ';
275
        }
276
        $this->from = rtrim($froms, ', ');
277
      }
278
      else{
279
        $this->from = $this->prefix . $table;
280
      }
281
      return $this;
282
    }
283
284
    /**
285
     * Set the SQL SELECT statment
286
     * @param  string|array $fields the field name or array of field list
287
     * @return object        the current Database instance
288
     */
289
    public function select($fields){
290
      $select = (is_array($fields) ? implode(', ', $fields) : $fields);
291
      $this->select = ($this->select == '*' ? $select : $this->select . ', ' . $select);
292
      return $this;
293
    }
294
295
    /**
296
     * Set the SQL SELECT DISTINCT statment
297
     * @param  string $field the field name to distinct
298
     * @return object        the current Database instance
299
     */
300
    public function distinct($field){
301
      $distinct = ' DISTINCT ' . $field;
302
      $this->select = ($this->select == '*' ? $distinct : $this->select . ', ' . $distinct);
303
304
      return $this;
305
    }
306
307
    /**
308
     * Set the SQL function MAX in SELECT statment
309
     * @param  string $field the field name
310
     * @param  string $name  if is not null represent the alias used for this field in the result
311
     * @return object        the current Database instance
312
     */
313
    public function max($field, $name = null){
314
      $func = 'MAX(' . $field . ')' . (!is_null($name) ? ' AS ' . $name : '');
315
      $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func);
316
      return $this;
317
    }
318
319
    /**
320
     * Set the SQL function MIN in SELECT statment
321
     * @param  string $field the field name
322
     * @param  string $name  if is not null represent the alias used for this field in the result
323
     * @return object        the current Database instance
324
     */
325
    public function min($field, $name = null){
326
      $func = 'MIN(' . $field . ')' . (!is_null($name) ? ' AS ' . $name : '');
327
      $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func);
328
      return $this;
329
    }
330
331
    /**
332
     * Set the SQL function SUM in SELECT statment
333
     * @param  string $field the field name
334
     * @param  string $name  if is not null represent the alias used for this field in the result
335
     * @return object        the current Database instance
336
     */
337
    public function sum($field, $name = null){
338
      $func = 'SUM(' . $field . ')' . (!is_null($name) ? ' AS ' . $name : '');
339
      $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func);
340
      return $this;
341
    }
342
343
    /**
344
     * Set the SQL function COUNT in SELECT statment
345
     * @param  string $field the field name
346
     * @param  string $name  if is not null represent the alias used for this field in the result
347
     * @return object        the current Database instance
348
     */
349
    public function count($field = '*', $name = null){
350
      $func = 'COUNT(' . $field . ')' . (!is_null($name) ? ' AS ' . $name : '');
351
      $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func);
352
      return $this;
353
    }
354
355
    /**
356
     * Set the SQL function AVG in SELECT statment
357
     * @param  string $field the field name
358
     * @param  string $name  if is not null represent the alias used for this field in the result
359
     * @return object        the current Database instance
360
     */
361
    public function avg($field, $name = null){
362
      $func = 'AVG(' . $field . ')' . (!is_null($name) ? ' AS ' . $name : '');
363
      $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func);
364
      return $this;
365
    }
366
367
    /**
368
     * Set the SQL JOIN statment
369
     * @param  string $table  the join table name
370
     * @param  string $field1 the first field for join conditions	
371
     * @param  string $op     the join condition operator. If is null the default will be "="
372
     * @param  string $field2 the second field for join conditions
373
     * @param  string $type   the type of join (INNER, LEFT, RIGHT)
374
     * @return object        the current Database instance
375
     */
376
    public function join($table, $field1 = null, $op = null, $field2 = null, $type = ''){
377
      $on = $field1;
378
      $table = $this->prefix . $table;
379
      if(! is_null($op)){
380
        $on = (! in_array($op, $this->operatorList) ? $this->prefix . $field1 . ' = ' . $this->prefix . $op : $this->prefix . $field1 . ' ' . $op . ' ' . $this->prefix . $field2);
381
      }
382
      if (is_null($this->join)){
0 ignored issues
show
introduced by
The condition is_null($this->join) is always false.
Loading history...
383
        $this->join = ' ' . $type . 'JOIN' . ' ' . $table . ' ON ' . $on;
384
      }
385
      else{
386
        $this->join = $this->join . ' ' . $type . 'JOIN' . ' ' . $table . ' ON ' . $on;
387
      }
388
      return $this;
389
    }
390
391
    /**
392
     * Set the SQL INNER JOIN statment
393
     * @see  Database::join()
394
     * @return object        the current Database instance
395
     */
396
    public function innerJoin($table, $field1, $op = null, $field2 = ''){
397
      return $this->join($table, $field1, $op, $field2, 'INNER ');
398
    }
399
400
    /**
401
     * Set the SQL LEFT JOIN statment
402
     * @see  Database::join()
403
     * @return object        the current Database instance
404
     */
405
    public function leftJoin($table, $field1, $op = null, $field2 = ''){
406
      return $this->join($table, $field1, $op, $field2, 'LEFT ');
407
	}
408
409
	/**
410
     * Set the SQL RIGHT JOIN statment
411
     * @see  Database::join()
412
     * @return object        the current Database instance
413
     */
414
    public function rightJoin($table, $field1, $op = null, $field2 = ''){
415
      return $this->join($table, $field1, $op, $field2, 'RIGHT ');
416
    }
417
418
    /**
419
     * Set the SQL FULL OUTER JOIN statment
420
     * @see  Database::join()
421
     * @return object        the current Database instance
422
     */
423
    public function fullOuterJoin($table, $field1, $op = null, $field2 = ''){
424
    	return $this->join($table, $field1, $op, $field2, 'FULL OUTER ');
425
    }
426
427
    /**
428
     * Set the SQL LEFT OUTER JOIN statment
429
     * @see  Database::join()
430
     * @return object        the current Database instance
431
     */
432
    public function leftOuterJoin($table, $field1, $op = null, $field2 = ''){
433
      return $this->join($table, $field1, $op, $field2, 'LEFT OUTER ');
434
    }
435
436
    /**
437
     * Set the SQL RIGHT OUTER JOIN statment
438
     * @see  Database::join()
439
     * @return object        the current Database instance
440
     */
441
    public function rightOuterJoin($table, $field1, $op = null, $field2 = ''){
442
      return $this->join($table, $field1, $op, $field2, 'RIGHT OUTER ');
443
    }
444
445
    /**
446
     * Set the SQL WHERE CLAUSE for IS NULL
447
     * @param  string|array $field  the field name or array of field list
448
     * @param  string $andOr the separator type used 'AND', 'OR', etc.
449
     * @return object        the current Database instance
450
     */
451
    public function whereIsNull($field, $andOr = 'AND'){
452
      if(is_array($field)){
453
        foreach($field as $f){
454
        	$this->whereIsNull($f, $andOr);
455
        }
456
      }
457
      else{
458
        if (! $this->where){
459
          $this->where = $field.' IS NULL ';
460
        }
461
        else{
462
            $this->where = $this->where . ' '.$andOr.' ' . $field.' IS NULL ';
463
          }
464
      }
465
      return $this;
466
    }
467
468
    /**
469
     * Set the SQL WHERE CLAUSE for IS NOT NULL
470
     * @param  string|array $field  the field name or array of field list
471
     * @param  string $andOr the separator type used 'AND', 'OR', etc.
472
     * @return object        the current Database instance
473
     */
474
    public function whereIsNotNull($field, $andOr = 'AND'){
475
      if(is_array($field)){
476
        foreach($field as $f){
477
          $this->whereIsNotNull($f, $andOr);
478
        }
479
      }
480
      else{
481
        if (! $this->where){
482
          $this->where = $field.' IS NOT NULL ';
483
        }
484
        else{
485
            $this->where = $this->where . ' '.$andOr.' ' . $field.' IS NOT NULL ';
486
          }
487
      }
488
      return $this;
489
    }
490
    
491
    /**
492
     * Set the SQL WHERE CLAUSE statment
493
     * @param  string|array  $where the where field or array of field list
494
     * @param  string  $op     the condition operator. If is null the default will be "="
495
     * @param  mixed  $val    the where value
496
     * @param  string  $type   the type used for this where clause (NOT, etc.)
497
     * @param  string  $andOr the separator type used 'AND', 'OR', etc.
498
     * @param  boolean $escape whether to escape or not the $val
499
     * @return object        the current Database instance
500
     */
501
    public function where($where, $op = null, $val = null, $type = '', $andOr = 'AND', $escape = true){
502
      if (is_array($where)){
503
        $_where = array();
504
        foreach ($where as $column => $data){
505
          if(is_null($data)){
506
            $data = '';
507
          }
508
          $_where[] = $type . $column . '=' . ($escape ? $this->escape($data) : $data);
509
        }
510
        $where = implode(' '.$andOr.' ', $_where);
511
      }
512
      else{
513
        if(is_array($op)){
0 ignored issues
show
introduced by
The condition is_array($op) is always false.
Loading history...
514
          $x = explode('?', $where);
515
          $w = '';
516
          foreach($x as $k => $v){
517
            if(! empty($v)){
518
                if(isset($op[$k]) && is_null($op[$k])){
519
                  $op[$k] = '';
520
                }
521
                $w .= $type . $v . (isset($op[$k]) ? ($escape ? $this->escape($op[$k]) : $op[$k]) : '');
522
            }
523
          }
524
          $where = $w;
525
        }
526
        else if (! in_array((string)$op, $this->operatorList)){
527
          if(is_null($op)){
528
            $op = '';
529
          }
530
        	$where = $type . $where . ' = ' . ($escape ? $this->escape($op) : $op);
531
        }
532
        else{
533
          if(is_null($val)){
534
            $val = '';
535
          }
536
        	$where = $type . $where . $op . ($escape ? $this->escape($val) : $val);
537
        }
538
      }
539
      if (is_null($this->where)){
0 ignored issues
show
introduced by
The condition is_null($this->where) is always false.
Loading history...
540
        $this->where = $where;
541
      }
542
      else{
543
        if(substr($this->where, -1) == '('){
544
          $this->where = $this->where . ' ' . $where;
545
        }
546
        else{
547
          $this->where = $this->where . ' '.$andOr.' ' . $where;
548
        }
549
      }
550
      return $this;
551
    }
552
553
    /**
554
     * Set the SQL WHERE CLAUSE statment using OR
555
     * @see  Database::where()
556
     * @return object        the current Database instance
557
     */
558
    public function orWhere($where, $op = null, $val = null, $escape = true){
559
      return $this->where($where, $op, $val, '', 'OR', $escape);
560
    }
561
562
563
    /**
564
     * Set the SQL WHERE CLAUSE statment using AND and NOT
565
     * @see  Database::where()
566
     * @return object        the current Database instance
567
     */
568
    public function notWhere($where, $op = null, $val = null, $escape = true){
569
      return $this->where($where, $op, $val, 'NOT ', 'AND', $escape);
570
    }
571
572
    /**
573
     * Set the SQL WHERE CLAUSE statment using OR and NOT
574
     * @see  Database::where()
575
     * @return object        the current Database instance
576
     */
577
    public function orNotWhere($where, $op = null, $val = null, $escape = true){
578
    	return $this->where($where, $op, $val, 'NOT ', 'OR', $escape);
579
    }
580
581
    /**
582
     * Set the opened parenthesis for the complex SQL query
583
     * @param  string $type   the type of this grouped (NOT, etc.)
584
     * @param  string $andOr the multiple conditions separator (AND, OR, etc.)
585
     * @return object        the current Database instance
586
     */
587
    public function groupStart($type = '', $andOr = ' AND'){
588
      if (is_null($this->where)){
0 ignored issues
show
introduced by
The condition is_null($this->where) is always false.
Loading history...
589
        $this->where = $type . ' (';
590
      }
591
      else{
592
          if(substr($this->where, -1) == '('){
593
            $this->where .= $type . ' (';
594
          }
595
          else{
596
          	$this->where .= $andOr . ' ' . $type . ' (';
597
          }
598
      }
599
      return $this;
600
    }
601
602
    /**
603
     * Set the opened parenthesis for the complex SQL query using NOT type
604
     * @see  Database::groupStart()
605
     * @return object        the current Database instance
606
     */
607
    public function notGroupStart(){
608
      return $this->groupStart('NOT');
609
    }
610
611
    /**
612
     * Set the opened parenthesis for the complex SQL query using OR for separator
613
     * @see  Database::groupStart()
614
     * @return object        the current Database instance
615
     */
616
    public function orGroupStart(){
617
      return $this->groupStart('', ' OR');
618
    }
619
620
     /**
621
     * Set the opened parenthesis for the complex SQL query using OR for separator and NOT for type
622
     * @see  Database::groupStart()
623
     * @return object        the current Database instance
624
     */
625
    public function orNotGroupStart(){
626
      return $this->groupStart('NOT', ' OR');
627
    }
628
629
    /**
630
     * Close the parenthesis for the grouped SQL
631
     * @return object        the current Database instance
632
     */
633
    public function groupEnd(){
634
      $this->where .= ')';
635
      return $this;
636
    }
637
638
    /**
639
     * Set the SQL WHERE CLAUSE statment for IN
640
     * @param  string  $field  the field name for IN statment
641
     * @param  array   $keys   the list of values used
642
     * @param  string  $type   the condition separator type (NOT)
643
     * @param  string  $andOr the multiple conditions separator (OR, AND)
644
     * @param  boolean $escape whether to escape or not the values
645
     * @return object        the current Database instance
646
     */
647
    public function in($field, array $keys, $type = '', $andOr = 'AND', $escape = true){
648
      if (is_array($keys)){
0 ignored issues
show
introduced by
The condition is_array($keys) is always true.
Loading history...
649
        $_keys = array();
650
        foreach ($keys as $k => $v){
651
          if(is_null($v)){
652
            $v = '';
653
          }
654
          $_keys[] = (is_numeric($v) ? $v : ($escape ? $this->escape($v) : $v));
655
        }
656
        $keys = implode(', ', $_keys);
657
        if (is_null($this->where)){
0 ignored issues
show
introduced by
The condition is_null($this->where) is always false.
Loading history...
658
          $this->where = $field . ' ' . $type . 'IN (' . $keys . ')';
659
        }
660
        else{
661
          if(substr($this->where, -1) == '('){
662
            $this->where = $this->where . ' ' . $field . ' '.$type.'IN (' . $keys . ')';
663
          }
664
          else{
665
            $this->where = $this->where . ' ' . $andOr . ' ' . $field . ' '.$type.'IN (' . $keys . ')';
666
          }
667
        }
668
      }
669
      return $this;
670
    }
671
672
    /**
673
     * Set the SQL WHERE CLAUSE statment for NOT IN with AND separator
674
     * @see  Database::in()
675
     * @return object        the current Database instance
676
     */
677
    public function notIn($field, array $keys, $escape = true){
678
      return $this->in($field, $keys, 'NOT ', 'AND', $escape);
679
    }
680
681
    /**
682
     * Set the SQL WHERE CLAUSE statment for IN with OR separator
683
     * @see  Database::in()
684
     * @return object        the current Database instance
685
     */
686
    public function orIn($field, array $keys, $escape = true){
687
      return $this->in($field, $keys, '', 'OR', $escape);
688
    }
689
690
    /**
691
     * Set the SQL WHERE CLAUSE statment for NOT IN with OR separator
692
     * @see  Database::in()
693
     * @return object        the current Database instance
694
     */
695
    public function orNotIn($field, array $keys, $escape = true){
696
      return $this->in($field, $keys, 'NOT ', 'OR', $escape);
697
    }
698
699
    /**
700
     * Set the SQL WHERE CLAUSE statment for BETWEEN
701
     * @param  string  $field  the field used for the BETWEEN statment
702
     * @param  mixed  $value1 the BETWEEN begin value
703
     * @param  mixed  $value2 the BETWEEN end value
704
     * @param  string  $type   the condition separator type (NOT)
705
     * @param  string  $andOr the multiple conditions separator (OR, AND)
706
     * @param  boolean $escape whether to escape or not the values
707
     * @return object        the current Database instance
708
     */
709
    public function between($field, $value1, $value2, $type = '', $andOr = 'AND', $escape = true){
710
      if(is_null($value1)){
711
        $value1 = '';
712
      }
713
      if(is_null($value2)){
714
        $value2 = '';
715
      }
716
      if (is_null($this->where)){
0 ignored issues
show
introduced by
The condition is_null($this->where) is always false.
Loading history...
717
      	$this->where = $field . ' ' . $type . 'BETWEEN ' . ($escape ? $this->escape($value1) : $value1) . ' AND ' . ($escape ? $this->escape($value2) : $value2);
718
      }
719
      else{
720
        if(substr($this->where, -1) == '('){
721
          $this->where = $this->where . ' ' . $field . ' ' . $type . 'BETWEEN ' . ($escape ? $this->escape($value1) : $value1) . ' AND ' . ($escape ? $this->escape($value2) : $value2);
722
        }
723
        else{
724
          $this->where = $this->where . ' ' . $andOr . ' ' . $field . ' ' . $type . 'BETWEEN ' . ($escape ? $this->escape($value1) : $value1) . ' AND ' . ($escape ? $this->escape($value2) : $value2);
725
        }
726
      }
727
      return $this;
728
    }
729
730
    /**
731
     * Set the SQL WHERE CLAUSE statment for BETWEEN with NOT type and AND separator
732
     * @see  Database::between()
733
     * @return object        the current Database instance
734
     */
735
    public function notBetween($field, $value1, $value2, $escape = true){
736
      return $this->between($field, $value1, $value2, 'NOT ', 'AND', $escape);
737
    }
738
739
    /**
740
     * Set the SQL WHERE CLAUSE statment for BETWEEN with OR separator
741
     * @see  Database::between()
742
     * @return object        the current Database instance
743
     */
744
    public function orBetween($field, $value1, $value2, $escape = true){
745
      return $this->between($field, $value1, $value2, '', 'OR', $escape);
746
    }
747
748
    /**
749
     * Set the SQL WHERE CLAUSE statment for BETWEEN with NOT type and OR separator
750
     * @see  Database::between()
751
     * @return object        the current Database instance
752
     */
753
    public function orNotBetween($field, $value1, $value2, $escape = true){
754
      return $this->between($field, $value1, $value2, 'NOT ', 'OR', $escape);
755
    }
756
757
    /**
758
     * Set the SQL WHERE CLAUSE statment for LIKE
759
     * @param  string  $field  the field name used in LIKE statment
760
     * @param  string  $data   the LIKE value for this field including the '%', and '_' part
761
     * @param  string  $type   the condition separator type (NOT)
762
     * @param  string  $andOr the multiple conditions separator (OR, AND)
763
     * @param  boolean $escape whether to escape or not the values
764
     * @return object        the current Database instance
765
     */
766
    public function like($field, $data, $type = '', $andOr = 'AND', $escape = true){
767
      if(is_null($data)){
0 ignored issues
show
introduced by
The condition is_null($data) is always false.
Loading history...
768
        $data = '';
769
      }
770
      $like = $escape ? $this->escape($data) : $data;
771
      if (is_null($this->where)){
0 ignored issues
show
introduced by
The condition is_null($this->where) is always false.
Loading history...
772
        $this->where = $field . ' ' . $type . 'LIKE ' . $like;
773
      }
774
      else{
775
        if(substr($this->where, -1) == '('){
776
          $this->where = $this->where . ' ' . $field . ' ' . $type . 'LIKE ' . $like;
777
        }
778
        else{
779
          $this->where = $this->where . ' '.$andOr.' ' . $field . ' ' . $type . 'LIKE ' . $like;
780
        }
781
      }
782
      return $this;
783
    }
784
785
    /**
786
     * Set the SQL WHERE CLAUSE statment for LIKE with OR separator
787
     * @see  Database::like()
788
     * @return object        the current Database instance
789
     */
790
    public function orLike($field, $data, $escape = true){
791
      return $this->like($field, $data, '', 'OR', $escape);
792
    }
793
794
    /**
795
     * Set the SQL WHERE CLAUSE statment for LIKE with NOT type and AND separator
796
     * @see  Database::like()
797
     * @return object        the current Database instance
798
     */
799
    public function notLike($field, $data, $escape = true){
800
      return $this->like($field, $data, 'NOT ', 'AND', $escape);
801
    }
802
803
    /**
804
     * Set the SQL WHERE CLAUSE statment for LIKE with NOT type and OR separator
805
     * @see  Database::like()
806
     * @return object        the current Database instance
807
     */
808
    public function orNotLike($field, $data, $escape = true){
809
      return $this->like($field, $data, 'NOT ', 'OR', $escape);
810
    }
811
812
    /**
813
     * Set the SQL LIMIT statment
814
     * @param  int $limit    the limit offset. If $limitEnd is null this will be the limit count
815
     * like LIMIT n;
816
     * @param  int $limitEnd the limit count
817
     * @return object        the current Database instance
818
     */
819
    public function limit($limit, $limitEnd = null){
820
      if(is_null($limit)){
0 ignored issues
show
introduced by
The condition is_null($limit) is always false.
Loading history...
821
        return;
822
      }
823
      if (! is_null($limitEnd)){
824
        $this->limit = $limit . ', ' . $limitEnd;
825
      }
826
      else{
827
        $this->limit = $limit;
828
      }
829
      return $this;
830
    }
831
832
    /**
833
     * Set the SQL ORDER BY CLAUSE statment
834
     * @param  string $orderBy   the field name used for order
835
     * @param  string $orderDir the order direction (ASC or DESC)
836
     * @return object        the current Database instance
837
     */
838
    public function orderBy($orderBy, $orderDir = ' ASC'){
839
      if (! is_null($orderDir)){
0 ignored issues
show
introduced by
The condition is_null($orderDir) is always false.
Loading history...
840
        $this->orderBy = ! $this->orderBy ? ($orderBy . ' ' . strtoupper($orderDir)) : $this->orderBy . ', ' . $orderBy . ' ' . strtoupper($orderDir);
841
      }
842
      else{
843
        if(stristr($orderBy, ' ') || $orderBy == 'rand()'){
844
          $this->orderBy = ! $this->orderBy ? $orderBy : $this->orderBy . ', ' . $orderBy;
845
        }
846
        else{
847
          $this->orderBy = ! $this->orderBy ? ($orderBy . ' ASC') : $this->orderBy . ', ' . ($orderBy . ' ASC');
848
        }
849
      }
850
      return $this;
851
    }
852
853
    /**
854
     * Set the SQL GROUP BY CLAUSE statment
855
     * @param  string|array $field the field name used or array of field list
856
     * @return object        the current Database instance
857
     */
858
    public function groupBy($field){
859
      if(is_array($field)){
860
        $this->groupBy = implode(', ', $field);
861
      }
862
      else{
863
        $this->groupBy = $field;
864
      }
865
      return $this;
866
    }
867
868
    /**
869
     * Set the SQL HAVING CLAUSE statment
870
     * @param  string  $field  the field name used for HAVING statment
871
     * @param  string|array  $op     the operator used or array
872
     * @param  mixed  $val    the value for HAVING comparaison
873
     * @param  boolean $escape whether to escape or not the values
874
     * @return object        the current Database instance
875
     */
876
    public function having($field, $op = null, $val = null, $escape = true){
877
      if(is_array($op)){
878
        $x = explode('?', $field);
879
        $w = '';
880
        foreach($x as $k => $v){
881
  	      if(!empty($v)){
882
            if(isset($op[$k]) && is_null($op[$k])){
883
              $op[$k] = '';
884
            }
885
  	      	$w .= $v . (isset($op[$k]) ? ($escape ? $this->escape($op[$k]) : $op[$k]) : '');
886
  	      }
887
      	}
888
        $this->having = $w;
889
      }
890
      else if (! in_array($op, $this->operatorList)){
891
        if(is_null($op)){
892
          $op = '';
893
        }
894
        $this->having = $field . ' > ' . ($escape ? $this->escape($op) : $op);
895
      }
896
      else{
897
        if(is_null($val)){
898
          $val = '';
899
        }
900
        $this->having = $field . ' ' . $op . ' ' . ($escape ? $this->escape($val) : $val);
901
      }
902
      return $this;
903
    }
904
905
    /**
906
     * Return the number of rows returned by the current query
907
     * @return int
908
     */
909
    public function numRows(){
910
      return $this->numRows;
911
    }
912
913
    /**
914
     * Return the last insert id value
915
     * @return mixed
916
     */
917
    public function insertId(){
918
      return $this->insertId;
919
    }
920
921
    /**
922
     * Show an error got from the current query (SQL command synthax error, database driver returned error, etc.)
923
     */
924
    public function error(){
925
  		if($this->error){
926
  			show_error('Query: "' . $this->query . '" Error: ' . $this->error, 'Database Error');
927
  		}
928
    }
929
930
    /**
931
     * Get the result of one record rows returned by the current query
932
     * @param  boolean $returnSQLQueryOrResultType if is boolean and true will return the SQL query string.
933
     * If is string will determine the result type "array" or "object"
934
     * @return mixed       the query SQL string or the record result
935
     */
936
    public function get($returnSQLQueryOrResultType = false){
937
      $this->limit = 1;
938
      $query = $this->getAll(true);
939
      if($returnSQLQueryOrResultType === true){
940
        return $query;
941
      }
942
      else{
943
        return $this->query( $query, false, (($returnSQLQueryOrResultType == 'array') ? true : false) );
944
      }
945
    }
946
947
    /**
948
     * Get the result of record rows list returned by the current query
949
     * @param  boolean $returnSQLQueryOrResultType if is boolean and true will return the SQL query string.
950
     * If is string will determine the result type "array" or "object"
951
     * @return mixed       the query SQL string or the record result
952
     */
953
    public function getAll($returnSQLQueryOrResultType = false){
954
      $query = 'SELECT ' . $this->select . ' FROM ' . $this->from;
955
      if (! is_null($this->join)){
0 ignored issues
show
introduced by
The condition is_null($this->join) is always false.
Loading history...
956
        $query .= $this->join;
957
      }
958
	  
959
      if (! is_null($this->where)){
0 ignored issues
show
introduced by
The condition is_null($this->where) is always false.
Loading history...
960
        $query .= ' WHERE ' . $this->where;
961
      }
962
963
      if (! is_null($this->groupBy)){
0 ignored issues
show
introduced by
The condition is_null($this->groupBy) is always false.
Loading history...
964
        $query .= ' GROUP BY ' . $this->groupBy;
965
      }
966
967
      if (! is_null($this->having)){
0 ignored issues
show
introduced by
The condition is_null($this->having) is always false.
Loading history...
968
        $query .= ' HAVING ' . $this->having;
969
      }
970
971
      if (! is_null($this->orderBy)){
0 ignored issues
show
introduced by
The condition is_null($this->orderBy) is always false.
Loading history...
972
          $query .= ' ORDER BY ' . $this->orderBy;
973
      }
974
975
      if(! is_null($this->limit)){
0 ignored issues
show
introduced by
The condition is_null($this->limit) is always false.
Loading history...
976
      	$query .= ' LIMIT ' . $this->limit;
977
      }
978
	  
979
	  if($returnSQLQueryOrResultType === true){
980
    	return $query;
981
      }
982
      else{
983
    	return $this->query($query, true, (($returnSQLQueryOrResultType == 'array') ? true : false) );
984
      }
985
    }
986
987
    /**
988
     * Insert new record in the database
989
     * @param  array   $data   the record data if is empty will use the $this->data array.
990
     * @param  boolean $escape  whether to escape or not the values
991
     * @return mixed          the insert id of the new record or null
992
     */
993
    public function insert($data = array(), $escape = true){
994
      $column = array();
995
      $val = array();
996
      if(! $data && $this->getData()){
0 ignored issues
show
Bug Best Practice introduced by
The expression $data of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
997
        $columns = array_keys($this->getData());
998
        $column = implode(',', $columns);
999
        $val = implode(', ', $this->getData());
1000
      }
1001
      else{
1002
        $columns = array_keys($data);
1003
        $column = implode(',', $columns);
1004
        $val = implode(', ', ($escape ? array_map(array($this, 'escape'), $data) : $data));
1005
      }
1006
1007
      $query = 'INSERT INTO ' . $this->from . ' (' . $column . ') VALUES (' . $val . ')';
1008
      $query = $this->query($query);
1009
1010
      if ($query){
1011
        if(! $this->pdo){
1012
          $this->connect();
1013
        }
1014
        $this->insertId = $this->pdo->lastInsertId();
1015
        return $this->insertId();
1016
      }
1017
      else{
1018
		  return false;
1019
      }
1020
    }
1021
1022
    /**
1023
     * Update record in the database
1024
     * @param  array   $data   the record data if is empty will use the $this->data array.
1025
     * @param  boolean $escape  whether to escape or not the values
1026
     * @return mixed          the update status
1027
     */
1028
    public function update($data = array(), $escape = true){
1029
      $query = 'UPDATE ' . $this->from . ' SET ';
1030
      $values = array();
1031
      if(! $data && $this->getData()){
0 ignored issues
show
Bug Best Practice introduced by
The expression $data of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1032
        foreach ($this->getData() as $column => $val){
1033
          $values[] = $column . ' = ' . $val;
1034
        }
1035
      }
1036
      else{
1037
        foreach ($data as $column => $val){
1038
          $values[] = $column . '=' . ($escape ? $this->escape($val) : $val);
1039
        }
1040
      }
1041
      $query .= (is_array($data) ? implode(', ', $values) : $data);
0 ignored issues
show
introduced by
The condition is_array($data) is always true.
Loading history...
1042
      if (! is_null($this->where)){
0 ignored issues
show
introduced by
The condition is_null($this->where) is always false.
Loading history...
1043
        $query .= ' WHERE ' . $this->where;
1044
      }
1045
1046
      if (! is_null($this->orderBy)){
0 ignored issues
show
introduced by
The condition is_null($this->orderBy) is always false.
Loading history...
1047
        $query .= ' ORDER BY ' . $this->orderBy;
1048
      }
1049
1050
      if (! is_null($this->limit)){
0 ignored issues
show
introduced by
The condition is_null($this->limit) is always false.
Loading history...
1051
        $query .= ' LIMIT ' . $this->limit;
1052
      }
1053
      return $this->query($query);
1054
    }
1055
1056
    /**
1057
     * Delete the record in database
1058
     * @return mixed the delete status
1059
     */
1060
    public function delete(){
1061
    	$query = 'DELETE FROM ' . $this->from;
1062
1063
    	if (! is_null($this->where)){
0 ignored issues
show
introduced by
The condition is_null($this->where) is always false.
Loading history...
1064
    		$query .= ' WHERE ' . $this->where;
1065
      	}
1066
1067
    	if (! is_null($this->orderBy)){
0 ignored issues
show
introduced by
The condition is_null($this->orderBy) is always false.
Loading history...
1068
    	  $query .= ' ORDER BY ' . $this->orderBy;
1069
      	}
1070
1071
    	if (! is_null($this->limit)){
0 ignored issues
show
introduced by
The condition is_null($this->limit) is always false.
Loading history...
1072
    		$query .= ' LIMIT ' . $this->limit;
1073
      	}
1074
1075
    	if($query == 'DELETE FROM ' . $this->from){
1076
    		$query = 'TRUNCATE TABLE ' . $this->from;
1077
      	}
1078
    	return $this->query($query);
1079
    }
1080
1081
    /**
1082
     * Execute an SQL query
1083
     * @param  string  $query the query SQL string
1084
     * @param  boolean $all   whether to return all record or not
1085
     * @param  boolean $array return the result as array
1086
     * @return mixed         the query result
1087
     */
1088
    public function query($query, $all = true, $array = false){
1089
      $this->reset();
1090
      if(is_array($all)){
0 ignored issues
show
introduced by
The condition is_array($all) is always false.
Loading history...
1091
        $x = explode('?', $query);
1092
        $q = '';
1093
        foreach($x as $k => $v){
1094
          if(! empty($v)){
1095
            $q .= $v . (isset($all[$k]) ? $this->escape($all[$k]) : '');
1096
          }
1097
        }
1098
        $query = $q;
1099
      }
1100
1101
      $this->query = preg_replace('/\s\s+|\t\t+/', ' ', trim($query));
1102
      $sqlSELECTQuery = stristr($this->query, 'SELECT');
1103
      $this->logger->info('Execute SQL query ['.$this->query.'], return type: ' . ($array?'ARRAY':'OBJECT') .', return as list: ' . ($all ? 'YES':'NO'));
1104
      //cache expire time
1105
  	  $cacheExpire = $this->temporaryCacheTtl;
1106
  	  
1107
  	  //return to the initial cache time
1108
  	  $this->temporaryCacheTtl = $this->cacheTtl;
1109
  	  
1110
  	  //config for cache
1111
        $cacheEnable = get_config('cache_enable');
1112
  	  
1113
  	  //the database cache content
1114
        $cacheContent = null;
1115
  	  
1116
  	  //this database query cache key
1117
        $cacheKey = null;
1118
  	  
1119
  	  //the cache manager instance
1120
      $cacheInstance = null;
1121
  	  
1122
  	  //if can use cache feature for this query
1123
  	  $dbCacheStatus = $cacheEnable && $cacheExpire > 0;
1124
	  
1125
      if ($dbCacheStatus && $sqlSELECTQuery){
1126
        $this->logger->info('The cache is enabled for this query, try to get result from cache'); 
1127
        $cacheKey = md5($query . $all . $array);
1128
        if(is_object($this->cacheInstance)){
1129
          $cacheInstance = $this->cacheInstance;
1130
        }
1131
        else{
1132
          $obj = & get_instance();
1133
          $cacheInstance = $obj->cache;  
1134
        }
1135
        $cacheContent = $cacheInstance->get($cacheKey);        
1136
      }
1137
      else{
1138
		  $this->logger->info('The cache is not enabled for this query or is not the SELECT query, get the result directly from real database');
1139
      }
1140
1141
      if(! $this->pdo){
1142
        $this->connect();
1143
      }
1144
      
1145
      if (! $cacheContent && $sqlSELECTQuery){
1146
		    //for database query execution time
1147
        $benchmarkMarkerKey = md5($query . $all . $array);
1148
        $bench = null;
1149
        if(is_object($this->benchmarkInstance)){
1150
          $bench = $this->benchmarkInstance;
1151
        }
1152
        else{
1153
          $obj = & get_instance();
1154
          $bench = $obj->benchmark;  
1155
        }
1156
        $bench->mark('DATABASE_QUERY_START(' . $benchmarkMarkerKey . ')');
1157
        //Now execute the query
1158
		    $sqlQuery = $this->pdo->query($this->query);
1159
        
1160
    		//get response time for this query
1161
        $responseTime = $bench->elapsedTime('DATABASE_QUERY_START(' . $benchmarkMarkerKey . ')', 'DATABASE_QUERY_END(' . $benchmarkMarkerKey . ')');
1162
	     	//TODO use the configuration value for the high response time currently is 1 second
1163
        if($responseTime >= 1 ){
1164
            $this->logger->warning('High response time while processing database query [' .$query. ']. The response time is [' .$responseTime. '] sec.');
1165
        }
1166
        if ($sqlQuery){
1167
          $this->numRows = $sqlQuery->rowCount();
1168
          if (($this->numRows > 0)){
1169
		    	//if need return all result like list of record
1170
            if ($all){
1171
    				$this->result = ($array == false) ? $sqlQuery->fetchAll(PDO::FETCH_OBJ) : $sqlQuery->fetchAll(PDO::FETCH_ASSOC);
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
1172
    		    }
1173
            else{
1174
				        $this->result = ($array == false) ? $sqlQuery->fetch(PDO::FETCH_OBJ) : $sqlQuery->fetch(PDO::FETCH_ASSOC);
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
1175
            }
1176
          }
1177
          if ($dbCacheStatus && $sqlSELECTQuery){
1178
            $this->logger->info('Save the result for query [' .$this->query. '] into cache for future use');
1179
            $cacheInstance->set($cacheKey, $this->result, $cacheExpire);
1180
          }
1181
        }
1182
        else{
1183
          $error = $this->pdo->errorInfo();
1184
          $this->error = $error[2];
1185
          $this->logger->fatal('The database query execution got error: ' . stringfy_vars($error));
1186
          $this->error();
1187
        }
1188
      }
1189
      else if ((! $cacheContent && !$sqlSELECTQuery) || ($cacheContent && !$sqlSELECTQuery)){
1190
    		$queryStr = $this->pdo->query($this->query);
1191
    		if($queryStr){
1192
    			$this->result = $queryStr->rowCount() >= 0; //to test the result for the query like UPDATE, INSERT, DELETE
1193
    			$this->numRows = $queryStr->rowCount();
1194
    		}
1195
        if (! $this->result){
1196
          $error = $this->pdo->errorInfo();
1197
          $this->error = $error[2];
1198
          $this->logger->fatal('The database query execution got error: ' . stringfy_vars($error));
1199
          $this->error();
1200
        }
1201
      }
1202
      else{
1203
        $this->logger->info('The result for query [' .$this->query. '] already cached use it');
1204
        $this->result = $cacheContent;
1205
	     	$this->numRows = count($this->result);
1206
      }
1207
      $this->queryCount++;
1208
      if(! $this->result){
1209
        $this->logger->info('No result where found for the query [' . $query . ']');
1210
      }
1211
      return $this->result;
1212
    }
1213
1214
    /**
1215
     * Set database cache time to live
1216
     * @param integer $ttl the cache time to live in second
1217
     * @return object        the current Database instance
1218
     */
1219
    public function setCache($ttl = 0){
1220
      if($ttl > 0){
1221
        $this->cacheTtl = $ttl;
1222
		    $this->temporaryCacheTtl = $ttl;
1223
      }
1224
      return $this;
1225
    }
1226
	
1227
	/**
1228
	 * Enabled cache temporary for the current query not globally	
1229
	 * @param  integer $ttl the cache time to live in second
1230
	 * @return object        the current Database instance
1231
	 */
1232
	public function cached($ttl = 0){
1233
      if($ttl > 0){
1234
        $this->temporaryCacheTtl = $ttl;
1235
      }
1236
	  return $this;
1237
    }
1238
1239
    /**
1240
     * Escape the data before execute query useful for security.
1241
     * @param  mixed $data the data to be escaped
1242
     * @return mixed       the data after escaped
1243
     */
1244
    public function escape($data){
1245
      if(is_null($data)){
1246
        return null;
1247
      }
1248
      if(! $this->pdo){
1249
        $this->connect();
1250
      }
1251
      return $this->pdo->quote(trim($data));
1252
    }
1253
1254
    /**
1255
     * Return the number query executed count for the current request
1256
     * @return int
1257
     */
1258
    public function queryCount(){
1259
      return $this->queryCount;
1260
    }
1261
1262
    /**
1263
     * Return the current query SQL string
1264
     * @return string
1265
     */
1266
    public function getQuery(){
1267
      return $this->query;
1268
    }
1269
1270
    /**
1271
     * Return the application database name
1272
     * @return string
1273
     */
1274
    public function getDatabaseName(){
1275
      return $this->databaseName;
1276
    }
1277
1278
     /**
1279
     * Return the database configuration
1280
     * @return array
1281
     */
1282
    public  function getDatabaseConfiguration(){
1283
      return $this->config;
1284
    }
1285
1286
    /**
1287
     * set the database configuration
1288
     * @param array $config the configuration
1289
     */
1290
    public function setDatabaseConfiguration(array $config){
1291
      $this->config = array_merge($this->config, $config);
1292
      $this->prefix = $this->config['prefix'];
1293
      $this->databaseName = $this->config['database'];
1294
      $this->logger->info('The database configuration are listed below: ' . stringfy_vars(array_merge($this->config, array('password' => string_hidden($this->config['password'])))));
1295
      return $this;
1296
    }
1297
1298
    /**
1299
     * Return the PDO instance
1300
     * @return PDO
1301
     */
1302
    public function getPdo(){
1303
      return $this->pdo;
1304
    }
1305
1306
    /**
1307
     * Set the PDO instance
1308
     * @param PDO $pdo the pdo object
1309
     */
1310
    public function setPdo(PDO $pdo){
1311
      $this->pdo = $pdo;
1312
      return $this;
1313
    }
1314
1315
1316
    /**
1317
     * Return the Log instance
1318
     * @return Log
1319
     */
1320
    public function getLogger(){
1321
      return $this->logger;
1322
    }
1323
1324
    /**
1325
     * Set the log instance
1326
     * @param Log $logger the log object
1327
     */
1328
    public function setLogger($logger){
1329
      $this->logger = $logger;
1330
      return $this;
1331
    }
1332
1333
     /**
1334
     * Return the cache instance
1335
     * @return CacheInterface
1336
     */
1337
    public function getCacheInstance(){
1338
      return $this->cacheInstance;
1339
    }
1340
1341
    /**
1342
     * Set the cache instance
1343
     * @param CacheInterface $cache the cache object
1344
     */
1345
    public function setCacheInstance($cache){
1346
      $this->cacheInstance = $cache;
1347
      return $this;
1348
    }
1349
1350
    /**
1351
     * Return the benchmark instance
1352
     * @return Benchmark
1353
     */
1354
    public function getBenchmark(){
1355
      return $this->benchmarkInstance;
1356
    }
1357
1358
    /**
1359
     * Set the benchmark instance
1360
     * @param Benchmark $cache the cache object
1361
     */
1362
    public function setBenchmark($benchmark){
1363
      $this->benchmarkInstance = $benchmark;
1364
      return $this;
1365
    }
1366
1367
    /**
1368
     * Return the data to be used for insert, update, etc.
1369
     * @return array
1370
     */
1371
    public function getData(){
1372
      return $this->data;
1373
    }
1374
1375
    /**
1376
     * Set the data to be used for insert, update, etc.
1377
     * @param string $key the data key identified
1378
     * @param mixed $value the data value
1379
     * @param boolean $escape whether to escape or not the $value
1380
     * @return object        the current Database instance
1381
     */
1382
    public function setData($key, $value, $escape = true){
1383
      $this->data[$key] = $escape ? $this->escape($value) : $value;
1384
      return $this;
1385
    }
1386
1387
1388
  /**
1389
   * Reset the database class attributs to the initail values before each query.
1390
   */
1391
  private function reset(){
1392
    $this->select   = '*';
1393
    $this->from     = null;
1394
    $this->where    = null;
1395
    $this->limit    = null;
1396
    $this->orderBy  = null;
1397
    $this->groupBy  = null;
1398
    $this->having   = null;
1399
    $this->join     = null;
1400
    $this->numRows  = 0;
1401
    $this->insertId = null;
1402
    $this->query    = null;
1403
    $this->error    = null;
1404
    $this->result   = array();
1405
    $this->data     = array();
1406
  }
1407
1408
  /**
1409
   * The class destructor
1410
   */
1411
  function __destruct(){
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
1412
    $this->pdo = null;
1413
  }
1414
1415
}
1416