Passed
Push — master ( 0c354d...481c82 )
by Ryan
01:38
created

Database::parseClause()   B

Complexity

Conditions 8
Paths 10

Size

Total Lines 29
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 8

Importance

Changes 0
Metric Value
cc 8
eloc 21
nc 10
nop 1
dl 0
loc 29
ccs 21
cts 21
cp 1
crap 8
rs 8.4444
c 0
b 0
f 0
1
<?php
2
namespace Godsgood33\Php_Db;
3
4
use Monolog\Logger;
5
use Monolog\Formatter\LineFormatter;
6
use Monolog\Handler\StreamHandler;
7
use Exception;
8
use mysqli;
9
10
/**
11
 * Constant to define that we want to return an object
12
 *
13
 * @var int
14
 */
15
define('MYSQLI_OBJECT', 4);
16
17
/**
18
 * Constant to return consistent date format
19
 *
20
 * @var string
21
 */
22
define('MYSQL_DATE', 'Y-m-d');
23
24
/**
25
 * Constant to return consistent datetime format
26
 *
27
 * @var string
28
 */
29
define('MYSQL_DATETIME', 'Y-m-d H:i:s');
30
31
/**
32
 * A generic database class
33
 *
34
 * @author Ryan Prather <[email protected]>
35
 */
36
class Database
37
{
38
39
    /**
40
     * Constant defining a SELECT query
41
     *
42
     * @var integer
43
     */
44
    const SELECT = 1;
45
46
    /**
47
     * Constant defining a SELECT COUNT query
48
     *
49
     * @var integer
50
     */
51
    const SELECT_COUNT = 2;
52
53
    /**
54
     * Constant defining a CREATE TABLE query
55
     *
56
     * @var integer
57
     */
58
    const CREATE_TABLE = 3;
59
60
    /**
61
     * Constant defining DROP query
62
     *
63
     * @var integer
64
     */
65
    const DROP = 4;
66
67
    /**
68
     * Constant defining DELETE query
69
     *
70
     * @var integer
71
     */
72
    const DELETE = 5;
73
74
    /**
75
     * Constant defining INSERT query
76
     *
77
     * @var integer
78
     */
79
    const INSERT = 6;
80
81
    /**
82
     * Constant defining REPLACE query
83
     *
84
     * @var integer
85
     */
86
    const REPLACE = 7;
87
88
    /**
89
     * Constant defining UPDATE query
90
     *
91
     * @var integer
92
     */
93
    const UPDATE = 8;
94
95
    /**
96
     * Constant defining EXTENDED INSERT query
97
     *
98
     * @var integer
99
     */
100
    const EXTENDED_INSERT = 9;
101
102
    /**
103
     * Constant defining EXTENDED REPLACE query
104
     *
105
     * @var integer
106
     */
107
    const EXTENDED_REPLACE = 10;
108
109
    /**
110
     * Constant defining EXTENDED UPDATE query
111
     *
112
     * @var integer
113
     */
114
    const EXTENDED_UPDATE = 11;
115
116
    /**
117
     * Constant defining ALTER TABLE query
118
     *
119
     * @var integer
120
     */
121
    const ALTER_TABLE = 12;
122
123
    /**
124
     * Constant defining action for alter table statement
125
     *
126
     * @var integer
127
     */
128
    const ADD_COLUMN = 1;
129
130
    /**
131
     * Constant defining action for alter table statement
132
     *
133
     * @var integer
134
     */
135
    const DROP_COLUMN = 2;
136
137
    /**
138
     * Constant defining action for alter table statement
139
     *
140
     * @var integer
141
     */
142
    const MODIFY_COLUMN = 3;
143
144
    /**
145
     * Constant defining action to add a constraint
146
     * 
147
     * @var integer
148
     */
149
    const ADD_CONSTRAINT = 4;
150
151
    /**
152
     * Constant defining a TRUNCATE TABLE query
153
     *
154
     * @var integer
155
     */
156
    const TRUNCATE = 13;
157
158
    /**
159
     * The mysqli connection
160
     *
161
     * @access protected
162
     * @var \mysqli
163
     */
164
    protected $_c;
165
166
    /**
167
     * To store the SQL statement
168
     *
169
     * @access private
170
     * @var string
171
     */
172
    private $_sql = null;
173
174
    /**
175
     * A variable to store the type of query that is being run
176
     *
177
     * @access private
178
     * @var int
179
     */
180
    private $_queryType = null;
181
182
    /**
183
     * The result of the query
184
     *
185
     * @access protected
186
     * @var mixed
187
     */
188
    protected $_result = null;
189
190
    /**
191
     * Log level
192
     *
193
     * @access private
194
     * @var string
195
     */
196
    private $_logLevel = Logger::ERROR;
197
198
    /**
199
     * Variable to store the logger
200
     *
201
     * @access private
202
     * @var \Monolog\Logger
203
     */
204
    private $_logger = null;
205
206
    /**
207
     * Path for the logger to log the file
208
     *
209
     * @access private
210
     * @var string
211
     */
212
    private $_logPath = null;
213
214
    /**
215
     * Variable to store the most recent insert ID from an insert query
216
     *
217
     * @access protected
218
     * @var mixed
219
     */
220
    protected $_insertId = null;
221
222
    /**
223
     * Variable to decide if we need to automatically run the queries after generating them
224
     *
225
     * @access public
226
     * @staticvar
227
     * @var boolean
228
     */
229
    public static $autorun = false;
230
231
    /**
232
     * Variable to decide if the system should create a CLI logger in addition to the file logger
233
     *
234
     * @access public
235
     * @staticvar
236
     * @var boolean
237
     */
238
    public static $cliLog = false;
239
240
    /**
241
     * Constructor
242
     *
243
     * @param string $strLogPath
244
     *            [optional]
245
     * @param \mysqli $dbh
246
     *            [optional]
247
     *            [by ref]
248
     *            mysqli object to perform queries.
249
     * @param int $intLogLevel
250
     */
251 115
    public function __construct($strLogPath = __DIR__, mysqli &$dbh = null, $intLogLevel = null)
252
    {
253 115
        if(! is_null($dbh) && is_a($dbh, 'mysqli')) {
254 1
            $this->_c = $dbh;
255 115
        } elseif(!defined('PHP_DB_SERVER') || !defined('PHP_DB_USER') || !defined('PHP_DB_PWD') || !defined('PHP_DB_SCHEMA')) {
256
            throw new Exception("Please create and include a constant file with the following constants defining your DB connection (PHP_DB_SERVER, PHP_DB_USER, PHP_DB_PWD, PHP_DB_SCHEMA)", E_USER_ERROR);
257 115
        } elseif(defined('PHP_DB_ENCRYPT') && (!defined('PHP_DB_ENCRYPT_ALGORITHM') || !defined('PHP_DB_ENCRYPT_SALT'))) {
258
            throw new Exception("Missing required PHP_DB_ENCRYPT_ALGORITHM or PHP_DB_ENCRYPT_SALT constants");
259
        }
260
        
261 115
        if(defined('PHP_DB_ENCRYPT') && PHP_DB_ENCRYPT) {
262 115
            $pwd = $this->decrypt(PHP_DB_PWD);
0 ignored issues
show
Bug introduced by
The constant Godsgood33\Php_Db\PHP_DB_PWD was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
263
        } else {
264
            $pwd = PHP_DB_PWD;
265
        }
266
267 115
        $this->_c = new mysqli(PHP_DB_SERVER, PHP_DB_USER, $pwd, PHP_DB_SCHEMA);
0 ignored issues
show
Bug introduced by
The constant Godsgood33\Php_Db\PHP_DB_USER was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant Godsgood33\Php_Db\PHP_DB_SCHEMA was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant Godsgood33\Php_Db\PHP_DB_SERVER was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
268
        
269 115
        if ($this->_c->connect_errno) {
270
            throw new Exception("Could not create database class due to error {$this->_c->connect_error}", E_ERROR);
271
        }
272
273 115
        $this->_logPath = $strLogPath;
274 115
        touch($this->_logPath . "/db.log");
275
276 115
        if(!defined("PHP_DB_LOG_LEVEL") && is_null($intLogLevel)) {
277
            $this->_logLevel = Logger::ERROR;
278 115
        } elseif(!is_null($intLogLevel)) {
279
            $this->_logLevel = $intLogLevel;
280 115
        } elseif(defined('PHP_DB_LOG_LEVEL')) {
281 115
            $this->_logLevel = PHP_DB_LOG_LEVEL;
0 ignored issues
show
Bug introduced by
The constant Godsgood33\Php_Db\PHP_DB_LOG_LEVEL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
282
        }
283
284 115
        $this->_logger = new Logger('db', [
285 115
            new StreamHandler(realpath($this->_logPath . "/db.log"), $this->_logLevel)
0 ignored issues
show
Bug introduced by
$this->_logLevel of type string is incompatible with the type integer expected by parameter $level of Monolog\Handler\StreamHandler::__construct(). ( Ignorable by Annotation )

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

285
            new StreamHandler(realpath($this->_logPath . "/db.log"), /** @scrutinizer ignore-type */ $this->_logLevel)
Loading history...
286
        ]);
287
288 115
        if (PHP_SAPI == 'cli' && self::$cliLog) {
289
            $stream = new StreamHandler(STDOUT, $this->_logLevel);
290
            $stream->setFormatter(new LineFormatter("%datetime% %level_name% %message%" . PHP_EOL, "H:i:s.u"));
291
            $this->_logger->pushHandler($stream);
292
        }
293
294 115
        $this->_logger->info("Database connected");
295 115
        $this->_logger->debug("Connection details:", [
296 115
            'Server' => PHP_DB_SERVER,
297 115
            'User'   => PHP_DB_USER,
298 115
            'Schema' => PHP_DB_SCHEMA
299
        ]);
300
301 115
        $this->setVar("time_zone", "+00:00");
302 115
        $this->setVar("sql_mode", "");
303 115
    }
304
305
    /**
306
     * Function to make sure that the database is connected
307
     *
308
     * @return boolean
309
     */
310 1
    public function isConnected()
311
    {
312 1
        $this->_logger->debug("Pinging server");
313 1
        return $this->_c->ping();
314
    }
315
316
    /**
317
     * Setter function for _logger
318
     *
319
     * @param Logger $log
320
     */
321 1
    public function setLogger(Logger $log)
322
    {
323 1
        $this->_logger->debug("Setting logger");
324 1
        $this->_logger = $log;
325 1
        return true;
326
    }
327
328
    /**
329
     * Getter function for _logLevel
330
     *
331
     * @return string
332
     */
333 1
    public function getLogLevel()
334
    {
335 1
        $level = $this->_logLevel;
336
337 1
        $this->_logger->debug("Getting log level ({$level})");
338 1
        return $level;
339
    }
340
341
    /**
342
     * Function to set the log level just in case there needs to be a change to the default log level
343
     *
344
     * @param string $strLevel
345
     */
346 1
    public function setLogLevel($strLevel)
347
    {
348 1
        $this->_logger->debug("Setting log level to {$strLevel}");
349 1
        $this->_logLevel = $strLevel;
350
351 1
        $handles = [];
352
353 1
        foreach ($this->_logger->getHandlers() as $h) {
354
            $h->/** @scrutinizer ignore-call */
355 1
                setLevel($strLevel);
356 1
            $handles[] = $h;
357
        }
358
359 1
        $this->_logger->setHandlers($handles);
360 1
    }
361
362
    /**
363
     * Getter function for _queryType
364
     *
365
     * @return int
366
     */
367 2
    public function getQueryType()
368
    {
369 2
        return $this->_queryType;
370
    }
371
372
    /**
373
     * Setter function for _queryType
374
     *
375
     * @param int $qt
376
     */
377 1
    public function setQueryType($qt)
378
    {
379 1
        $this->_queryType = $qt;
380 1
    }
381
382
    /**
383
     * Getter function for _sql
384
     *
385
     * @return string
386
     */
387 61
    public function getSql()
388
    {
389 61
        return $this->_sql;
390
    }
391
392
    /**
393
     * Function to return the currently selected database schema
394
     *
395
     * @return string|boolean
396
     */
397 1
    public function getSchema()
398
    {
399 1
        if ($res = $this->_c->query("SELECT DATABASE()")) {
400 1
            $row = $res->fetch_row();
401
402 1
            $this->_logger->debug("Getting schema {$row[0]}");
403 1
            return $row[0];
404
        }
405
406
        return false;
407
    }
408
409
    /**
410
     * Function to set schema
411
     *
412
     * @param string $strSchema
413
     */
414 2
    public function setSchema($strSchema)
415
    {
416 2
        $this->_logger->debug("Setting schema to {$strSchema}");
417 2
        if (! $this->_c->select_db($strSchema)) {
418 1
            $this->_logger->emergency("Unknown schema {$strSchema}", [debug_backtrace()]);
419 1
            return false;
420
        }
421 1
        return true;
422
    }
423
424
    /**
425
     * Method to set a MYSQL variable
426
     *
427
     * @param string $strName
428
     * @param string $strVal
429
     *
430
     * @return boolean
431
     */
432 115
    public function setVar($strName, $strVal)
433
    {
434 115
        if (! $strName ) {
435 1
            $this->_logger->debug("name is blank", [
436 1
                'name'  => $strName
437
            ]);
438 1
            return false;
439
        }
440
441 115
        $this->_logger->debug("Setting {$strName} = '{$strVal}'");
442
443 115
        if ($this->_c->real_query("SET $strName = {$this->_escape($strVal)}")) {
444 115
            return true;
445
        } else {
446
            $this->_logger->error("Failed to set variable {$this->_c->error}");
447
            return false;
448
        }
449
    }
450
451
    /**
452
     * Function to execute the statement
453
     *
454
     * @param mixed $return
455
     *            [optional]
456
     *            MYSQLI constant to control what is returned from the mysqli_result object
457
     * @param string $class
458
     *            [optional]
459
     *            Class to use when returning object
460
     * @param string $strSql
461
     *            [optional]
462
     *            Optional SQL query
463
     *
464
     * @throws \Exception
465
     * @throws \InvalidArgumentException
466
     *
467
     * @return mixed
468
     */
469 7
    public function execute($return = MYSQLI_OBJECT, $strSql = null)
470
    {
471 7
        if (! is_null($strSql)) {
472
            $this->_sql = $strSql;
473
        }
474
475 7
        $this->_result = false;
476
477 7
        if (is_a($this->_c, 'mysqli')) {
478 7
            if (! $this->_c->ping()) {
479 7
                throw new Exception("Database lost connection", E_ERROR);
480
            }
481
        } else {
482
            throw new Exception('Database was not connected', E_ERROR);
483
        }
484
485 7
        $this->_logger->info("Executing {$this->_queryType} query");
486 7
        $this->_logger->debug($this->_sql);
487
488
        try {
489 7
            if (in_array($this->_queryType, [
490 7
                self::SELECT,
491 7
                self::SELECT_COUNT
492
            ])) {
493 4
                $this->_result = $this->_c->query($this->_sql);
494 4
                if ($this->_c->error) {
495
                    $this->_logger->error("There is an error {$this->_c->error}");
496
                    $this->_logger->debug("Errored on query", [$this->_sql]);
497 4
                    throw new Exception("There was an error {$this->_c->error}", E_ERROR);
498
                }
499
            } else {
500 3
                $this->_result = $this->_c->real_query($this->_sql);
501 3
                if ($this->_c->errno) {
502
                    $this->_logger->error("There was an error {$this->_c->error}");
503
                    $this->_logger->debug("Errored on query", [$this->_sql]);
504
                    throw new Exception("There was an error {$this->_c->error}", E_ERROR);
505
                }
506
            }
507
508 7
            $this->_logger->debug("Checking for query results");
509 7
            $this->_result = $this->checkResults($return);
510
        } catch (Exception $e) {}
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
511
512 7
        return $this->_result;
513
    }
514
515
    /**
516
     * Function to check the results and return what is expected
517
     *
518
     * @param mixed $returnType
519
     *            [optional]
520
     *            Optional return mysqli_result return type
521
     *
522
     * @return mixed
523
     */
524 7
    protected function checkResults($returnType)
525
    {
526 7
        $res = null;
527
528 7
        if (in_array($this->_queryType, [Database::CREATE_TABLE, Database::ALTER_TABLE, Database::TRUNCATE, Database::DROP])) {
529 3
            $res = $this->_result;
530
        }
531 4
        elseif (in_array($this->_queryType, [Database::INSERT, Database::EXTENDED_INSERT, Database::DELETE, Database::UPDATE, Database::EXTENDED_UPDATE, Database::REPLACE, Database::EXTENDED_REPLACE, Database::DELETE])) {
532
            $res = $this->_c->affected_rows;
533
534
            if (in_array($this->_queryType, [Database::INSERT, Database::REPLACE, Database::EXTENDED_INSERT])) {
535
                $this->_insertId = $this->_c->insert_id;
536
            }
537
        }
538 4
        elseif ($this->_queryType == Database::SELECT_COUNT) {
539
            if (! is_a($this->_result, 'mysqli_result')) {
540
                $this->_logger->error("Error with return on query");
541
                return null;
542
            }
543
544
            if ($this->_result->num_rows == 1) {
545
                $row = $this->_result->fetch_assoc();
546
                if (isset($row['count'])) {
547
                    $this->_logger->debug("Returning SELECT_COUNT query", [
548
                        'count' => $row['count']
549
                    ]);
550
                    $res = $row['count'];
551
                }
552
            } elseif ($this->_result->num_rows > 1) {
553
                $this->_logger->debug("Returning SELECT_COUNT query", [
554
                    'count' => $this->_result->num_rows
555
                ]);
556
                $res = $this->_result->num_rows;
557
            }
558
559
            mysqli_free_result($this->_result);
560
        }
561
        else {
562 4
            $method = "mysqli_fetch_object";
563 4
            if($returnType == MYSQLI_ASSOC) {
564 1
                $method = "mysqli_fetch_assoc";
565 3
            } elseif ($returnType == MYSQLI_NUM) {
566 1
                $method = "mysqli_fetch_array";
567
            }
568
569 4
            if (is_a($this->_result, 'mysqli_result')) {
570 4
                if($this->_result->num_rows > 1) {
571 3
                    $res = [];
572 3
                    while ($row = call_user_func($method, $this->_result)) {
573 3
                        $res[] = $row;
574
                    }
575
                } else {
576 4
                    $res = call_user_func($method, $this->_result);
577
                }
578
            } else {
579
                $this->_logger->error("Error with return on query");
580
                return null;
581
            }
582
        }
583
584 7
        if ($this->_c->error) {
585
            $this->_logger->error("Encountered a SQL error", ['error' => $this->_c->error, 'list' => $this->_c->error_list]);
586
            $this->_logger->debug("Debug", ['debug' => debug_backtrace()]);
587
            return null;
588
        }
589
590 7
        return $res;
591
    }
592
593
    /**
594
     * Function to pass through calling the query function (used for backwards compatibility and for more complex queries that aren't currently supported)
595
     * Nothing is escaped
596
     *
597
     * @param string $strSql
598
     *            [optional]
599
     *            Optional query to pass in and execute
600
     *
601
     * @return \mysqli_result|boolean
602
     */
603 2
    public function query($strSql = null)
604
    {
605 2
        if (is_null($strSql)) {
606 1
            return $this->_c->query($this->_sql);
607
        } else {
608 1
            return $this->_c->query($strSql);
609
        }
610
    }
611
612
    /**
613
     * A function to build a select query
614
     *
615
     * @param string $strTableName
616
     *            The table to query
617
     * @param array|string $fields
618
     *            [optional]
619
     *            Optional array of fields to return (defaults to '*')
620
     * @param array $arrWhere
621
     *            [optional]
622
     *            Optional 2-dimensional array to build where clause from
623
     * @param array $arrFlags
624
     *            [optional]
625
     *            Optional 2-dimensional array to allow other flags
626
     *
627
     * @see Database::flags()
628
     *
629
     * @throws Exception
630
     *
631
     * @return mixed
632
     */
633 34
    public function select($strTableName, $fields = null, $arrWhere = [], $arrFlags = [])
634
    {
635 34
        $this->_sql = null;
636 34
        $this->_queryType = self::SELECT;
637
638 34
        if (! is_null($strTableName) && is_string($strTableName)) {
0 ignored issues
show
introduced by
The condition is_null($strTableName) is always false.
Loading history...
introduced by
The condition is_string($strTableName) is always true.
Loading history...
639 33
            $this->_logger->debug("Starting SELECT query of {$strTableName}", [
640 33
                'fields' => $this->fields($fields)
641
            ]);
642 32
            $this->_sql = "SELECT " . $this->fields($fields) . " FROM $strTableName";
643
        } else {
644 1
            $this->_logger->emergency("Table name is invalid or wrong type", [debug_backtrace()]);
645 1
            throw new Exception("Table name is invalid");
646
        }
647
648 32
        if (isset($arrFlags['joins']) && is_array($arrFlags['joins']) && count($arrFlags['joins'])) {
649 1
            $this->_logger->debug("Adding joins", [
650 1
                'joins' => implode(' ', $arrFlags['joins'])
651
            ]);
652 1
            $this->_sql .= " " . implode(" ", $arrFlags['joins']);
653
        } else {
654 31
            $this->_logger->debug("No joins");
655
        }
656
657 32
        $where = $this->parseClause($arrWhere);
658
659 30
        if (! is_null($where) && is_array($where) && count($where)) {
0 ignored issues
show
introduced by
The condition is_array($where) is always true.
Loading history...
introduced by
The condition is_null($where) is always false.
Loading history...
660 8
            $where_str = " WHERE";
661 8
            $this->_logger->debug("Parsing where clause and adding to query");
662 8
            foreach ($where as $x => $w) {
663 8
                if($x > 0) {
664 1
                    $where_str .= " {$w->sqlOperator}";
665
                }
666 8
                $where_str .= $w;
667
            }
668 8
            if (strlen($where_str) > strlen(" WHERE")) {
669 8
                $this->_sql .= $where_str;
670
            }
671
        }
672
673 30
        if (is_array($arrFlags) && count($arrFlags)) {
674 8
            $this->_logger->debug("Parsing flags and adding to query", $arrFlags);
675 8
            $this->_sql .= $this->flags($arrFlags);
676
        }
677
678 29
        if (self::$autorun) {
679
            return $this->execute();
680
        }
681
682 29
        return $this->_sql;
683
    }
684
685
    /**
686
     * Function to build a query to check the number of rows in a table
687
     *
688
     * @param string $strTableName
689
     *            The table to query
690
     * @param array $arrWhere
691
     *            [optional]
692
     *            Optional 2-dimensional array to build where clause
693
     * @param array $arrFlags
694
     *            [optional]
695
     *            Optional 2-dimensional array to add flags
696
     *
697
     * @see Database::flags()
698
     *
699
     * @return string|NULL
700
     */
701 4
    public function selectCount($strTableName, $arrWhere = [], $arrFlags = [])
702
    {
703 4
        $this->_sql = null;
704 4
        $this->_queryType = self::SELECT_COUNT;
705
706 4
        if (! is_null($strTableName) && is_string($strTableName)) {
0 ignored issues
show
introduced by
The condition is_string($strTableName) is always true.
Loading history...
introduced by
The condition is_null($strTableName) is always false.
Loading history...
707 3
            $this->_sql = "SELECT COUNT(1) AS 'count' FROM $strTableName";
708
        } else {
709 1
            $this->_logger->emergency("Table name is invalid or wrong type", [debug_backtrace()]);
710 1
            throw new Exception("Table name is invalid");
711
        }
712
713 3
        if (isset($arrFlags['joins']) && is_array($arrFlags['joins'])) {
714 1
            $this->_sql .= " " . implode(" ", $arrFlags['joins']);
715
        }
716
717 3
        $where = $this->parseClause($arrWhere);
718
719 3
        if (! is_null($where) && is_array($where) && count($where)) {
0 ignored issues
show
introduced by
The condition is_null($where) is always false.
Loading history...
introduced by
The condition is_array($where) is always true.
Loading history...
720 2
            $where_str = " WHERE";
721 2
            $this->_logger->debug("Parsing where clause and adding to query");
722 2
            foreach ($where as $x => $w) {
723 2
                if($x > 0) {
724 1
                    $where_str .= " {$w->sqlOperator}";
725
                }
726 2
                $where_str .= $w;
727
            }
728 2
            if (strlen($where_str) > strlen(" WHERE")) {
729 2
                $this->_sql .= $where_str;
730
            }
731
        }
732
733 3
        if (is_array($arrFlags) && count($arrFlags)) {
734 1
            $this->_sql .= $this->flags($arrFlags);
735
        }
736
737 3
        if (self::$autorun) {
738
            return $this->execute();
739
        }
740
741 3
        return $this->_sql;
742
    }
743
744
    /**
745
     * Function to build an insert query statement
746
     *
747
     * @param string $strTableName
748
     * @param array|string $arrParams
749
     * @param boolean $blnToIgnore
750
     *
751
     * @return string|NULL
752
     */
753 8
    public function insert($strTableName, $arrParams = null, $blnToIgnore = false)
754
    {
755 8
        $this->_sql = null;
756 8
        $this->_queryType = self::INSERT;
757
758 8
        if (! is_null($strTableName) && is_string($strTableName)) {
0 ignored issues
show
introduced by
The condition is_null($strTableName) is always false.
Loading history...
introduced by
The condition is_string($strTableName) is always true.
Loading history...
759 7
            $this->_sql = "INSERT" . ($blnToIgnore ? " IGNORE" : "") . " INTO {$strTableName}";
760
        } else {
761 1
            throw new Exception("Table name is invalid");
762
        }
763
764 7
        if (is_array($arrParams) && count($arrParams)) {
765 4
            if(is_array($arrParams) && count($arrParams)) {
766 4
                $this->_sql .= " (`" . implode("`,`", array_keys($arrParams)) . "`)";
767
            }
768 4
            $this->_sql .= " VALUES (" . implode(",", array_map([
769 4
                $this,
770 4
                '_escape'
771 4
            ], array_values($arrParams))) . ")";
772 3
        } elseif (is_string($arrParams) && strpos(strtolower($arrParams), 'select') !== false) {
773 1
            $this->_sql .= " {$arrParams}";
774 2
        } elseif (is_object($arrParams)) {
775 2
            $interfaces = \class_implements($arrParams);
776 2
            if(in_array("Godsgood33\Php_Db\DBInterface", $interfaces) && is_callable(get_class($arrParams) . "::insert")) {
777 1
                $params = \call_user_func([$arrParams, "insert"]);
778 1
                $this->_sql .= " (`" . implode("`,`", array_keys($params)) . "`) VALUES ";
779 1
                $this->_sql .= "(" . implode(",", array_map([$this, '_escape'], array_values($params))) . ")";
780
            } else {
781 2
                throw new Exception("Object does not implement the DBInterface interface and methods");
782
            }
783
        } else {
784
            throw new Exception("Invalid type passed to insert " . gettype($arrParams));
785
        }
786
787 6
        if (self::$autorun) {
788
            return $this->execute();
789
        }
790
791 6
        return $this->_sql;
792
    }
793
794
    /**
795
     * Function to create an extended insert query statement
796
     *
797
     * @param string $strTableName
798
     *            The table name that the data is going to be inserted on
799
     * @param array $arrFields
800
     *            An array of field names that each value represents
801
     * @param array|string $params
802
     *            An array of array of values or a string with a SELECT statement to populate the insert with
803
     * @param boolean $blnToIgnore
804
     *            [optional]
805
     *            Boolean to decide if we need to use the INSERT IGNORE INTO syntax
806
     *
807
     * @return NULL|string Returns the SQL if self::$autorun is set to false, else it returns the output from running.
808
     */
809 4
    public function extendedInsert($strTableName, $arrFields, $params, $blnToIgnore = false)
810
    {
811 4
        $this->_sql = null;
812 4
        $this->_queryType = self::EXTENDED_INSERT;
813
814 4
        if (! is_null($strTableName) && is_string($strTableName)) {
0 ignored issues
show
introduced by
The condition is_null($strTableName) is always false.
Loading history...
introduced by
The condition is_string($strTableName) is always true.
Loading history...
815 3
            $this->_sql = "INSERT " . ($blnToIgnore ? "IGNORE " : "") . "INTO $strTableName " . "(`" . implode("`,`", $arrFields) . "`)";
816
        } else {
817 1
            throw new Exception("Table name is invalid");
818
        }
819
820 3
        if (is_array($params) && count($params)) {
821 3
            $this->_sql .= " VALUES ";
822 3
            if (isset($params[0]) && is_array($params[0])) {
823 3
                foreach ($params as $p) {
824 3
                    if (count($p) != count($arrFields)) {
825 2
                        $this->_logger->emergency("Inconsistent number of fields to values in extendedInsert", [
826 2
                            $p,
827 2
                            debug_backtrace()
828
                        ]);
829 2
                        throw new Exception("Inconsistent number of fields in fields and values in extendedInsert " . print_r($p, true));
830
                    }
831 2
                    $this->_sql .= "(" . implode(",", array_map([$this, '_escape'], array_values($p))) . ")";
832
833 2
                    if ($p != end($params)) {
834 2
                        $this->_sql .= ",";
835
                    }
836
                }
837
            } else {
838 1
                $this->_sql .= "(" . implode("),(", array_map([$this, '_escape'], array_values($params))) . ")";
839
            }
840
        } else {
841
            throw new Exception("Invalid param type");
842
        }
843
844 1
        if (self::$autorun) {
845
            return $this->execute();
846
        }
847
848 1
        return $this->_sql;
849
    }
850
851
    /**
852
     * Build a statement to update a table
853
     *
854
     * @param string $strTableName
855
     *            The table name to update
856
     * @param array $arrParams
857
     *            Name/value pairs of the field name and value
858
     * @param array $arrWhere
859
     *            [optional]
860
     *            Two-dimensional array to create where clause
861
     * @param array $arrFlags
862
     *            [optional]
863
     *            Two-dimensional array to create other flag options (joins, order, and group)
864
     *
865
     * @see Database::flags()
866
     *
867
     * @return NULL|string
868
     */
869 10
    public function update($strTableName, $arrParams, $arrWhere = [], $arrFlags = [])
870
    {
871 10
        $this->_sql = "UPDATE ";
872 10
        $this->_queryType = self::UPDATE;
873
874 10
        if (! is_null($strTableName) && is_string($strTableName)) {
0 ignored issues
show
introduced by
The condition is_null($strTableName) is always false.
Loading history...
introduced by
The condition is_string($strTableName) is always true.
Loading history...
875 9
            $this->_sql .= $strTableName;
876
877 9
            if (isset($arrFlags['joins']) && is_array($arrFlags['joins'])) {
878 1
                $this->_sql .= " " . implode(" ", $arrFlags['joins']);
879 1
                unset($arrFlags['joins']);
880
            }
881
882 9
            $this->_sql .= " SET ";
883
        } else {
884 1
            throw new Exception("Table name is invalid");
885
        }
886
887 9
        if (is_array($arrParams) && count($arrParams)) {
888 6
            $keys = array_keys($arrParams);
889 6
            foreach ($arrParams as $f => $p) {
890 6
                $field = $f;
891 6
                if ((strpos($f, "`") === false) && (strpos($f, ".") === false) && (strpos($f, "*") === false) && (stripos($f, " as ") === false)) {
892 5
                    $field = "`{$f}`";
893
                }
894
895 6
                if (! is_null($p)) {
896 5
                    $this->_sql .= "$field={$this->_escape($p)}";
897
                } else {
898 1
                    $this->_sql .= "$field=NULL";
899
                }
900
901 6
                if($f != end($keys)) {
902 1
                    $this->_sql .= ",";
903
                }
904
            }
905 3
        } elseif (is_object($arrParams)) {
906 2
            $interfaces = \class_implements($arrParams);
907 2
            if(in_array("Godsgood33\Php_Db\DBInterface", $interfaces) && is_callable(get_class($arrParams) . "::update")) {
908 1
                $params = \call_user_func([$arrParams, "update"]);
909 1
                $fields = array_keys($params);
910 1
                $values = array_map([$this, '_escape'], array_values($params));
911 1
                foreach($fields as $x => $f) {
912 1
                    if($x > 0) {
913 1
                        $this->_sql .= ",";
914
                    }
915 1
                    $this->_sql .= "`{$f}`={$values[$x]}";
916
                }
917
            } else {
918 2
                throw new Exception("Params is an object that doesn't implement DBInterface");
919
            }
920
        } else {
921 1
            throw new Exception("No fields to update");
922
        }
923
924 7
        $where = $this->parseClause($arrWhere);
925
        
926 7
        if (! is_null($where) && is_array($where) && count($where)) {
0 ignored issues
show
introduced by
The condition is_null($where) is always false.
Loading history...
introduced by
The condition is_array($where) is always true.
Loading history...
927 3
            $where_str = " WHERE";
928 3
            $this->_logger->debug("Parsing where clause and adding to query");
929 3
            foreach ($where as $x => $w) {
930 3
                if($x > 0) {
931 1
                    $where_str .= " {$w->sqlOperator}";
932
                }
933 3
                $where_str .= $w;
934
            }
935 3
            if (strlen($where_str) > strlen(" WHERE")) {
936 3
                $this->_sql .= $where_str;
937
            }
938
        }
939
940 7
        if (! is_null($arrFlags) && is_array($arrFlags) && count($arrFlags)) {
941
            $this->_sql .= $this->flags($arrFlags);
942
        }
943
944 7
        if (self::$autorun) {
945
            return $this->execute();
946
        }
947
948 7
        return $this->_sql;
949
    }
950
951
    /**
952
     * Function to offer an extended updated functionality by using two different tables.
953
     *
954
     * @param string $strTableToUpdate
955
     *            The table that you want to update (alias 'tbu' is automatically added)
956
     * @param string $strOriginalTable
957
     *            The table with the data you want to overwrite to_be_updated table (alias 'o' is automatically added)
958
     * @param string $strLinkField
959
     *            The common index value between them that will join the fields
960
     * @param array|string $arrParams
961
     *            If string only a single field is updated (tbu.$params = o.$params)
962
     *            If array each element in the array is a field to be updated (tbu.$param = o.$param)
963
     *
964
     * @return mixed
965
     */
966 3
    public function extendedUpdate($strTableToUpdate, $strOriginalTable, $strLinkField, $arrParams)
967
    {
968 3
        $this->_sql = "UPDATE ";
969 3
        $this->_queryType = self::EXTENDED_UPDATE;
970
971 3
        if (! is_null($strTableToUpdate) && ! is_null($strOriginalTable) && ! is_null($strLinkField)) {
0 ignored issues
show
introduced by
The condition is_null($strOriginalTable) is always false.
Loading history...
introduced by
The condition is_null($strLinkField) is always false.
Loading history...
introduced by
The condition is_null($strTableToUpdate) is always false.
Loading history...
972 3
            $this->_sql .= "$strTableToUpdate tbu INNER JOIN $strOriginalTable o USING ($strLinkField) SET ";
973
        } else {
974
            throw new Exception("Missing necessary fields");
975
        }
976
977 3
        if (is_array($arrParams) && count($arrParams)) {
978 1
            foreach ($arrParams as $param) {
979 1
                if ($param != $strLinkField) {
980 1
                    $this->_sql .= "tbu.`$param` = o.`$param`,";
981
                }
982
            }
983 1
            $this->_sql = substr($this->_sql, 0, - 1);
984 2
        } elseif (is_string($arrParams)) {
985 1
            $this->_sql .= "tbu.`$arrParams` = o.`$arrParams`";
986
        } else {
987 1
            throw new Exception("Do not understand datatype " . gettype($arrParams), E_ERROR);
988
        }
989
990 2
        if (self::$autorun) {
991
            return $this->execute();
992
        }
993
994 2
        return $this->_sql;
995
    }
996
997
    /**
998
     * Function to build a replace query
999
     *
1000
     * @param string $strTableName
1001
     *            The table to update
1002
     * @param array $arrParams
1003
     *            Name/value pair to insert
1004
     *
1005
     * @return NULL|string
1006
     */
1007 3
    public function replace($strTableName, $arrParams)
1008
    {
1009 3
        $this->_sql = null;
1010 3
        $this->_queryType = self::REPLACE;
1011
1012 3
        if (! is_null($strTableName) && is_string($strTableName)) {
0 ignored issues
show
introduced by
The condition is_string($strTableName) is always true.
Loading history...
introduced by
The condition is_null($strTableName) is always false.
Loading history...
1013 2
            $this->_sql = "REPLACE INTO $strTableName ";
1014
        } else {
1015 1
            throw new Exception("Table name is invalid");
1016
        }
1017
1018 2
        if(is_array($arrParams) && count($arrParams)) {
1019 1
            $keys = array_keys($arrParams);
1020 1
            $vals = array_values($arrParams);
1021
1022 1
            $this->_sql .= "(`" . implode("`,`", $keys) . "`)";
1023 1
            $this->_sql .= " VALUES (" . implode(",", array_map([
1024 1
                $this,
1025 1
                '_escape'
1026 1
            ], array_values($vals))) . ")";
1027 1
        } elseif (is_object($arrParams)) {
1028 1
            $interfaces = class_implements($arrParams);
1029 1
            if(in_array("Godsgood33\Php_Db\DBInterface", $interfaces) && is_callable(get_class($arrParams) . "::replace")) {
1030 1
                $params = \call_user_func([$arrParams, "replace"]);
1031 1
                $this->_sql .= "(`" . implode("`,`", array_keys($params)) . "`) VALUES ";
1032 1
                $this->_sql .= "(" . implode(",", array_map([$this, '_escape'], array_values($params))) . ")";
1033
            }
1034
        }
1035
1036 2
        if (self::$autorun) {
1037
            return $this->execute();
1038
        }
1039
1040 2
        return $this->_sql;
1041
    }
1042
1043
    /**
1044
     * Function to build an extended replace statement
1045
     *
1046
     * @param string $strTableName
1047
     *            Table name to update
1048
     * @param array $arrFields
1049
     *            Array of fields
1050
     * @param array $arrParams
1051
     *            Two-dimensional array of values
1052
     *
1053
     * @return NULL|string
1054
     */
1055 2
    public function extendedReplace($strTableName, $arrFields, $arrParams)
1056
    {
1057 2
        $this->_sql = null;
1058 2
        $this->_queryType = self::EXTENDED_REPLACE;
1059
1060 2
        if (! is_array($arrFields) || ! count($arrFields)) {
0 ignored issues
show
introduced by
The condition is_array($arrFields) is always true.
Loading history...
1061 1
            throw new Exception("Error with the field type");
1062
        }
1063
1064 1
        if (! is_null($strTableName) && is_string($strTableName)) {
0 ignored issues
show
introduced by
The condition is_null($strTableName) is always false.
Loading history...
introduced by
The condition is_string($strTableName) is always true.
Loading history...
1065 1
            $this->_sql = "REPLACE INTO $strTableName " . "(`" . implode("`,`", $arrFields) . "`)";
1066
        } else {
1067
            throw new Exception("Table name is invalid");
1068
        }
1069
1070 1
        if (is_array($arrParams) && count($arrParams)) {
1071 1
            $this->_sql .= " VALUES ";
1072 1
            foreach ($arrParams as $p) {
1073 1
                $this->_sql .= "(" . implode(",", array_map([
1074 1
                    $this,
1075 1
                    '_escape'
1076 1
                ], array_values($p))) . ")";
1077
1078 1
                if ($p != end($arrParams)) {
1079 1
                    $this->_sql .= ",";
1080
                }
1081
            }
1082
        }
1083
1084 1
        if (self::$autorun) {
1085
            return $this->execute();
1086
        }
1087
1088 1
        return $this->_sql;
1089
    }
1090
1091
    /**
1092
     * Function to build a delete statement
1093
     *
1094
     * @param string $strTableName
1095
     *            Table name to act on
1096
     * @param array $arrFields
1097
     *            [optional]
1098
     *            Optional list of fields to delete (used when including multiple tables)
1099
     * @param array $arrWhere
1100
     *            [optional]
1101
     *            Optional 2-dimensional array to build where clause from
1102
     * @param array $arrJoins
1103
     *            [optional]
1104
     *            Optional 2-dimensional array to add other flags
1105
     *
1106
     * @see Database::flags()
1107
     *
1108
     * @return string|NULL
1109
     */
1110 5
    public function delete($strTableName, $arrFields = [], $arrWhere = [], $arrJoins = [])
1111
    {
1112 5
        $this->_sql = "DELETE";
1113 5
        $this->_queryType = self::DELETE;
1114
1115 5
        $this->_logger->debug("Deleting table data");
1116
1117 5
        if (! is_null($arrFields) && is_array($arrFields) && count($arrFields)) {
0 ignored issues
show
introduced by
The condition is_array($arrFields) is always true.
Loading history...
introduced by
The condition is_null($arrFields) is always false.
Loading history...
1118 1
            $this->_sql .= " " . implode(",", $arrFields);
1119
        }
1120
1121 5
        if (! is_null($strTableName) && is_string($strTableName)) {
0 ignored issues
show
introduced by
The condition is_null($strTableName) is always false.
Loading history...
introduced by
The condition is_string($strTableName) is always true.
Loading history...
1122 4
            $this->_sql .= " FROM $strTableName";
1123
        } else {
1124 1
            throw new Exception("Table name is invalid");
1125
        }
1126
1127 4
        if (! is_null($arrJoins) && is_array($arrJoins) && count($arrJoins)) {
0 ignored issues
show
introduced by
The condition is_null($arrJoins) is always false.
Loading history...
introduced by
The condition is_array($arrJoins) is always true.
Loading history...
1128 1
            $this->_sql .= " " . implode(" ", $arrJoins);
1129
        }
1130
1131 4
        $where = $this->parseClause($arrWhere);
1132
1133 4
        if (! is_null($where) && is_array($where) && count($where)) {
0 ignored issues
show
introduced by
The condition is_null($where) is always false.
Loading history...
introduced by
The condition is_array($where) is always true.
Loading history...
1134 2
            $where_str = " WHERE";
1135 2
            $this->_logger->debug("Parsing where clause and adding to query");
1136 2
            foreach ($where as $x => $w) {
1137 2
                if($x > 0) {
1138 1
                    $where_str .= " {$w->sqlOperator}";
1139
                }
1140 2
                $where_str .= $w;
1141
            }
1142 2
            if (strlen($where_str) > strlen(" WHERE")) {
1143 2
                $this->_sql .= $where_str;
1144
            }
1145
        }
1146
1147 4
        if (self::$autorun) {
1148
            return $this->execute();
1149
        }
1150
1151 4
        return $this->_sql;
1152
    }
1153
1154
    /**
1155
     * Function to build a drop table statement (automatically executes)
1156
     *
1157
     * @param string $strTableName
1158
     *            Table to drop
1159
     * @param string $strType
1160
     *            [optional]
1161
     *            Type of item to drop ('table', 'view') (defaulted to 'table')
1162
     * @param boolean $blnIsTemp
1163
     *            [optional]
1164
     *            Optional boolean if this is a temporary table
1165
     *
1166
     * @return string|NULL
1167
     */
1168 5
    public function drop($strTableName, $strType = 'table', $blnIsTemp = false)
1169
    {
1170 5
        $this->_sql = null;
1171 5
        $this->_queryType = self::DROP;
1172
1173 5
        switch ($strType) {
1174 5
            case 'table':
1175 3
                $strType = 'TABLE';
1176 3
                break;
1177 2
            case 'view':
1178 1
                $strType = 'VIEW';
1179 1
                break;
1180
            default:
1181 1
                throw new Exception("Invalid type " . gettype($strType), E_ERROR);
1182
        }
1183
1184 4
        if (! is_null($strTableName) && is_string($strTableName)) {
0 ignored issues
show
introduced by
The condition is_null($strTableName) is always false.
Loading history...
introduced by
The condition is_string($strTableName) is always true.
Loading history...
1185 3
            $this->_sql = "DROP" . ($blnIsTemp ? " TEMPORARY" : "") . " $strType IF EXISTS `{$strTableName}`";
1186
        } else {
1187 1
            throw new Exception("Table name is invalid");
1188
        }
1189
1190 3
        if (self::$autorun) {
1191
            return $this->execute();
1192
        }
1193
1194 3
        return $this->_sql;
1195
    }
1196
1197
    /**
1198
     * Function to build a truncate table statement (automatically executes)
1199
     *
1200
     * @param string $strTableName
1201
     *            Table to truncate
1202
     *
1203
     * @throws Exception
1204
     *
1205
     * @return string|NULL
1206
     */
1207 2
    public function truncate($strTableName)
1208
    {
1209 2
        $this->_sql = null;
1210 2
        $this->_queryType = self::TRUNCATE;
1211
1212 2
        if (! is_null($strTableName) && is_string($strTableName)) {
0 ignored issues
show
introduced by
The condition is_string($strTableName) is always true.
Loading history...
introduced by
The condition is_null($strTableName) is always false.
Loading history...
1213 1
            $this->_sql = "TRUNCATE TABLE $strTableName";
1214
        } else {
1215 1
            throw new Exception("Table name is invalid");
1216
        }
1217
1218 1
        if (self::$autorun) {
1219
            return $this->execute();
1220
        }
1221
1222 1
        return $this->_sql;
1223
    }
1224
1225
    /**
1226
     * Function to build a create temporary table statement
1227
     *
1228
     * @param string $strTableName
1229
     *            Name to give the table when creating
1230
     * @param boolean $blnIsTemp
1231
     *            [optional]
1232
     *            Optional boolean to make the table a temporary table
1233
     * @param mixed $strSelect
1234
     *            [optional]
1235
     *            Optional parameter if null uses last built statement
1236
     *            If string, will be made the SQL statement executed to create the table
1237
     *            If array, 2-dimensional array with "field", "datatype" values to build table fields
1238
     *
1239
     * @return NULL|string
1240
     */
1241 3
    public function createTable($strTableName, $blnIsTemp = false, $strSelect = null)
1242
    {
1243 3
        $this->_queryType = self::CREATE_TABLE;
1244
1245 3
        if (is_null($strSelect) && ! is_null($this->_sql) && substr($this->_sql, 0, 6) == 'SELECT') {
1246 1
            $this->_sql = "CREATE" . ($blnIsTemp ? " TEMPORARY" : "") . " TABLE IF NOT EXISTS $strTableName AS ($this->_sql)";
1247 2
        } elseif (! is_null($strTableName) && is_string($strTableName) && is_string($strSelect)) {
0 ignored issues
show
introduced by
The condition is_string($strTableName) is always true.
Loading history...
introduced by
The condition is_null($strTableName) is always false.
Loading history...
1248 1
            $this->_sql = "CREATE" . ($blnIsTemp ? " TEMPORARY" : "") . " TABLE IF NOT EXISTS $strTableName AS ($strSelect)";
1249 1
        } elseif (! is_null($strTableName) && is_string($strTableName) && is_array($strSelect)) {
1250 1
            $this->_sql = "CREATE" . ($blnIsTemp ? " TEMPORARY" : "") . " TABLE IF NOT EXISTS $strTableName (";
1251
1252 1
            foreach ($strSelect as $field) {
1253 1
                $default = null;
1254 1
                if (isset($field['default'])) {
1255 1
                    $default = (is_null($field['default']) ? "" : " DEFAULT '{$field['default']}'");
1256
                }
1257 1
                $this->_sql .= "`{$field['field']}` {$field['datatype']}" . $default . (isset($field['option']) ? " {$field['option']}" : '') . ",";
1258
            }
1259 1
            $this->_sql = substr($this->_sql, 0, - 1) . ")";
1260
        }
1261
1262 3
        if (self::$autorun) {
1263
            return $this->execute();
1264
        }
1265
1266 3
        return $this->_sql;
1267
    }
1268
1269
    /**
1270
     * Function to create a table using a stdClass object derived from JSON
1271
     *
1272
     * @param \stdClass $json
1273
     *
1274
     * @example /examples/create_table_json.json
1275
     *
1276
     */
1277 3
    public function createTableJson($json)
1278
    {
1279 3
        $this->_queryType = self::CREATE_TABLE;
1280 3
        $this->_c->select_db($json->schema);
1281
1282 3
        $this->_sql = "CREATE TABLE IF NOT EXISTS `{$json->name}` (";
1283 3
        foreach ($json->fields as $field) {
1284 3
            $this->_sql .= "`{$field->name}` {$field->dataType}";
1285
1286 3
            if ($field->dataType == 'enum' && isset($field->values)) {
1287 1
                $this->_sql .= "('" . implode("','", $field->values) . "')";
1288
            }
1289
1290 3
            if (isset($field->ai) && $field->ai) {
1291 3
                $this->_sql .= " AUTO_INCREMENT";
1292
            }
1293
1294 3
            if (isset($field->nn) && $field->nn) {
1295 3
                $this->_sql .= " NOT NULL";
1296 2
            } elseif(isset($field->default)) {
1297 2
                if (strtolower($field->default) == 'null') {
1298 1
                    $this->_sql .= " DEFAULT NULL";
1299 1
                } elseif (strlen($field->default)) {
1300 1
                    $this->_sql .= " DEFAULT '{$field->default}'";
1301
                }
1302
            }
1303
1304 3
            if ($field != end($json->fields)) {
1305 2
                $this->_sql .= ",";
1306
            }
1307
        }
1308
1309 3
        if (isset($json->index) && count($json->index)) {
1310 1
            foreach ($json->index as $ind) {
1311 1
                $ref = null;
1312 1
                if(is_array($ind->ref)) {
1313
                    $ref = "";
1314
                    foreach($ind->ref as $r) {
1315
                        $ref .= "`{$r}` ASC,";
1316
                    }
1317
                    $ref = substr($ref, 0, -1);
1318 1
                } elseif(is_string($ind->ref)) {
1319 1
                    $ref = $ind->ref;
1320
                }
1321 1
                if(!is_null($ref)) {
1322 1
                    $this->_sql .= ", " . strtoupper($ind->type) . " `{$ind->id}` (`{$ref}`)";
1323
                }
1324
            }
1325
        }
1326
1327 3
        if (isset($json->constraints) && count($json->constraints)) {
1328
            foreach ($json->constraints as $con) {
1329
                $this->_sql .= ", CONSTRAINT `{$con->id}` " . "FOREIGN KEY (`{$con->local}`) " . "REFERENCES `{$con->schema}`.`{$con->table}` (`{$con->field}`) " . "ON DELETE " . (is_null($con->delete) ? "NO ACTION" : strtoupper($con->delete)) . " " . "ON UPDATE " . (is_null($con->update) ? "NO ACTION" : strtoupper($con->update));
1330
            }
1331
        }
1332
1333 3
        if (isset($json->unique) && count($json->unique)) {
1334 1
            $this->_sql .= ", UNIQUE(`" . implode("`,`", $json->unique) . "`)";
1335
        }
1336
1337 3
        if (isset($json->primary_key) && count($json->primary_key)) {
1338 3
            $this->_sql .= ", PRIMARY KEY(`" . implode("`,`", $json->primary_key) . "`))";
1339
        } else {
1340
            if (substr($this->_sql, - 1) == ',') {
1341
                $this->_sql = substr($this->_sql, 0, - 1);
1342
            }
1343
1344
            $this->_sql .= ")";
1345
        }
1346
1347 3
        $this->execute();
1348 3
    }
1349
1350
    /**
1351
     * Method to add a column to the database (only one at a time!)
1352
     * 
1353
     * @param string $strTableName
1354
     * @param stdClass $params
0 ignored issues
show
Bug introduced by
The type Godsgood33\Php_Db\stdClass was not found. Did you mean stdClass? If so, make sure to prefix the type with \.
Loading history...
1355
     * 
1356
     * @return string|mixed
1357
     */
1358 3
    public function addColumn($strTableName, $params)
1359
    {
1360 3
        $this->_queryType = self::ALTER_TABLE;
1361 3
        $this->_sql = "ALTER TABLE {$strTableName} ADD COLUMN";
1362
1363 3
        if(!self::checkObject($params, ['name', 'dataType'])) {
1364 1
            $this->_logger->error("Missing elements for the addColumn method (need 'name', 'dataType')", [$params]);
1365 1
            throw new \Exception("Missing elements for the addColumn method");
1366
        }
1367
1368 2
        $nn = (isset($params->nn) && $params->nn ? " NOT NULL" : "");
1369 2
        $default = null;
1370 2
        if ($params->default === null) {
1371 1
            $default = " DEFAULT NULL";
1372 1
        } elseif (strlen($params->default)) {
1373 1
            $default = " DEFAULT {$this->_escape($params->default)}";
1374
        }
1375 2
        $this->_sql .= " `{$params->name}` {$params->dataType}" . $nn . $default;
1376
1377 2
        if(self::$autorun) {
1378
            return $this->execute();
1379
        }
1380
1381 2
        return $this->_sql;
1382
    }
1383
1384
    /**
1385
     * Method to drop a fields from a table
1386
     * 
1387
     * @param string $strTableName
1388
     * @param string|array:string $params
0 ignored issues
show
Documentation Bug introduced by
The doc comment $params at position 0 could not be parsed: Unknown type name '$params' at position 0 in $params.
Loading history...
1389
     * 
1390
     * @return string|mixed
1391
     */
1392 3
    public function dropColumn($strTableName, $params)
1393
    {
1394 3
        $this->_queryType = self::ALTER_TABLE;
1395 3
        $this->_sql = "ALTER TABLE {$strTableName} DROP COLUMN";
1396
1397 3
        if(is_array($params) && count($params)) {
1398 2
            foreach ($params as $col) {
1399 2
                $this->_sql .= " `{$col->name}`";
1400
1401 2
                if ($col != end($params)) {
1402 1
                    $this->_sql .= ",";
1403
                }
1404
            }
1405 1
        } elseif(is_string($params)) {
1406 1
            $this->_sql .= " `{$params}`";
1407
        }
1408
1409 3
        if(self::$autorun) {
1410
            return $this->execute();
1411
        }
1412
1413 3
        return $this->_sql;
1414
    }
1415
1416
    /**
1417
     * Method to modify a field to change it's datatype, name, or other parameter
1418
     * 
1419
     * @param string $strTableName
1420
     * @param stdClass $params
1421
     * 
1422
     * @return string|mixed
1423
     */
1424 3
    public function modifyColumn($strTableName, $params)
1425
    {
1426 3
        $this->_queryType = self::ALTER_TABLE;
1427 3
        $this->_sql = "ALTER TABLE {$strTableName} MODIFY COLUMN";
1428
1429 3
        if(!self::checkObject($params, ['name', 'dataType'])) {
1430 1
            $this->_logger->error("Missing elements to the modifyColumn method (need 'name' and 'dataType')", [$params]);
1431 1
            throw new \Exception("Missing elements to the modifyColumn method");
1432
        }
1433
1434 2
        if(!isset($params->new_name)) {
1435 1
            $params->new_name = $params->name;
1436
        }
1437
1438 2
        $nn = (isset($params->nn) && $params->nn ? " NOT NULL" : "");
1439 2
        $default = null;
1440 2
        if ($params->default === null) {
1441 1
            $default = " DEFAULT NULL";
1442 1
        } elseif (strlen($params->default)) {
1443 1
            $default = " DEFAULT {$this->_escape($params->default)}";
1444
        }
1445 2
        $this->_sql .= " `{$params->name}` `{$params->new_name}` {$params->dataType}" . $nn . $default;
1446
1447 2
        if(self::$autorun) {
1448
            return $this->execute();
1449
        }
1450
1451 2
        return $this->_sql;
1452
    }
1453
1454
    /**
1455
     * Method to add a constraint to a table
1456
     * 
1457
     * @param string $strTableName
1458
     * @param stdClass $params
1459
     * 
1460
     * @return string|mixed
1461
     */
1462 6
    public function addConstraint($strTableName, $params)
1463
    {
1464 6
        $this->_queryType = self::ALTER_TABLE;
1465 6
        $this->_sql = "ALTER TABLE {$strTableName} ADD CONSTRAINT";
1466
1467 6
        if(!is_a($params, 'stdClass')) {
1468 1
            $this->_logger->critical("Error in reading constraint field");
1469 1
            throw new \Exception("Error in reading constraint field");
1470
        }
1471
1472 5
        if(!self::checkObject($params, ['id', 'local', 'schema', 'table', 'field', 'delete', 'update'])) {
1473 1
            $this->_logger->error("Missing elements in the addConstraint method (need 'id', 'local', 'schema', 'table', 'field', 'delete', 'update')", [$params]);
1474 1
            throw new \Exception("There are some missing elements for the addConstraint action");
1475
        }
1476
1477 4
        if(!in_array(strtoupper($params->delete), ['CASCADE', 'SET NULL', 'RESTRICT', 'NO ACTION'])) {
1478 1
            $this->_logger->error("Invalid action for deletion on addConstraint");
1479 1
            throw new \Exception("Invalid action for deletion on addConstraint");
1480
        }
1481
1482 3
        if(!in_array(strtoupper($params->update), ['CASCADE', 'SET NULL', 'RESTRICT', 'NO ACTION'])) {
1483 1
            $this->_logger->error("Invalid action for update on addConstraint");
1484 1
            throw new Exception("Invalid action for update on addConstraint");
1485
        }
1486
1487 2
        if(is_array($params->field) && is_array($params->local)) {
1488 1
            $field = "`" . implode("`,`", $params->field) . "`";
1489 1
            $local = "`" . implode("`,`", $params->local) . "`";
1490 1
        } elseif(is_string($params->field) && is_string($params->local)) {
1491 1
            $field = "`{$params->field}`";
1492 1
            $local = "`{$params->local}`";
1493
        }
1494 2
        $this->_sql .= " `{$params->id}` FOREIGN KEY ({$local}) REFERENCES `{$params->schema}`.`{$params->table}` ({$field}) ON DELETE {$params->delete} ON UPDATE {$params->update}";
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $field does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $local does not seem to be defined for all execution paths leading up to this point.
Loading history...
1495
1496 2
        if(self::$autorun) {
1497
            return $this->execute();
1498
        }
1499
1500 2
        return $this->_sql;
1501
    }
1502
1503
    /**
1504
     * Check to see if a field in a table exists
1505
     *
1506
     * @param string $strTableName
1507
     *            Table to check
1508
     * @param string $strFieldName
1509
     *            Field name to find
1510
     *
1511
     * @return boolean Returns TRUE if field is found in that schema and table, otherwise FALSE
1512
     */
1513 2
    public function fieldExists($strTableName, $strFieldName)
1514
    {
1515 2
        $fdata = $this->fieldData($strTableName);
1516
1517 2
        if (is_array($fdata) && count($fdata)) {
1518 2
            foreach ($fdata as $field) {
1519 2
                if ($field->name == $strFieldName) {
1520 1
                    return true;
1521
                }
1522
            }
1523
        }
1524
1525 1
        return false;
1526
    }
1527
1528
    /**
1529
     * Function to get the column data (datatype, flags, defaults, etc)
1530
     *
1531
     * @param string $strTableName
1532
     *            Table to query
1533
     * @param mixed $field
1534
     *            [optional]
1535
     *            Optional field to retrieve data (if null, returns data from all fields)
1536
     *
1537
     * @return array
1538
     */
1539 3
    public function fieldData($strTableName, $field = null)
1540
    {
1541 3
        if (is_null($field)) {
1542 3
            $res = $this->_c->query("SELECT * FROM $strTableName LIMIT 1");
1543 1
        } elseif (is_array($field)) {
1544 1
            $res = $this->_c->query("SELECT `" . implode("`,`", $field) . "` FROM $strTableName LIMIT 1");
1545 1
        } elseif (is_string($field)) {
1546 1
            $res = $this->_c->query("SELECT $field FROM $strTableName LIMIT 1");
1547
        } else {
1548 1
            return null;
1549
        }
1550
1551 3
        $fields = null;
1552 3
        if (is_a($res, 'mysqli_result')) {
1553 3
            $fields = $res->fetch_fields();
1554 3
            foreach ($fields as $i => $f) {
1555 3
                $fields["{$f->name}"] = $f;
1556 3
                unset($fields[$i]);
1557
            }
1558
        }
1559
1560 3
        return $fields;
1561
    }
1562
1563
    /**
1564
     * Function to check that all field parameters are set correctly
1565
     *
1566
     * @param object $field_data
1567
     * @param object $check
1568
     * @param array $pks
1569
     * @param object $index
1570
     *
1571
     * @return array|string
1572
     */
1573
    public function fieldCheck($field_data, $check, $pks, $index)
1574
    {
1575
        $default = null;
1576
        $ret = null;
1577
1578
        $nn = ($check->nn ? " NOT NULL" : null);
1579
        if ($check->default === null) {
1580
            $default = " DEFAULT NULL";
1581
        } elseif (strlen($check->default)) {
1582
            $default = " DEFAULT '{$check->default}'";
1583
        }
1584
1585
        if ($field_data->type != $check->type && $check->type != MYSQLI_TYPE_ENUM) {
1586
            $this->_logger->notice("Wrong datatype", [
1587
                'name' => $field_data->name,
1588
                'datatype' => $check->dataType
1589
            ]);
1590
            $ret = " CHANGE COLUMN `{$field_data->name}` `{$check->name}` {$check->dataType}" . "{$nn}{$default}";
1591
        } elseif (! is_null($check->length) && $field_data->length != $check->length) {
1592
            $this->_logger->notice("Incorrect size", [
1593
                'name' => $field_data->name,
1594
                'current' => $field_data->length,
1595
                'new_size' => $check->length
1596
            ]);
1597
            $ret = " CHANGE COLUMN `{$field_data->name}` `{$check->name}` {$check->dataType}" . "{$nn}{$default}";
1598
        } elseif ($check->type == MYSQLI_TYPE_ENUM && ! ($field_data->flags & MYSQLI_ENUM_FLAG)) {
1599
            $this->_logger->notice("Setting ENUM type", [
1600
                'name' => $field_data->name,
1601
                'values' => implode(",", $check->values)
1602
            ]);
1603
            $ret = " CHANGE COLUMN `{$field_data->name}` `{$check->name}` {$check->dataType}('" . implode("','", $check->values) . "')" . "{$nn}{$default}";
1604
        }
1605
1606
        if (! is_null($index) && count($index)) {
1607
            foreach ($index as $ind) {
1608
                if ($check->name == $ind->ref && ! ($field_data->flags & MYSQLI_MULTIPLE_KEY_FLAG)) {
1609
                    $this->_logger->debug("Missing index", [
1610
                        'name' => $field_data->name
1611
                    ]);
1612
                    $ret .= ($ret ? "," : "") . " ADD INDEX `{$ind->id}` (`{$ind->ref}` ASC)";
1613
                }
1614
            }
1615
        }
1616
1617
        if (in_array($check->name, $pks) && ! ($field_data->flags & MYSQLI_PRI_KEY_FLAG)) {
1618
            $this->_logger->debug("Setting PKs", [
1619
                'keys' => implode(',', $pks)
1620
            ]);
1621
            $ret .= ($ret ? "," : "") . " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode("`,`", $pks) . "`)";
1622
        }
1623
1624
        return $ret;
1625
    }
1626
1627
    /**
1628
     * Function to check for the existence of a table within a schema
1629
     *
1630
     * @param string $strSchema
1631
     *            The schema to search in
1632
     * @param string $strTableName
1633
     *            Table to search for
1634
     *
1635
     * @return integer|boolean Returns number of tables that match if table is found in that schema, otherwise FALSE
1636
     */
1637 3
    public function tableExists($strSchema, $strTableName)
1638
    {
1639 3
        if (! $this->_c->select_db($strSchema)) {
1640
            fwrite(STDOUT, $this->_c->error . PHP_EOL);
1641
        }
1642 3
        $sql = "SHOW TABLES LIKE '{$strTableName}'";
1643
1644 3
        if ($res = $this->_c->query($sql)) {
1645 3
            if (gettype($res) == 'object' && is_a($res, 'mysqli_result') && $res->num_rows) {
1646 3
                return $res->num_rows;
1647
            }
1648
        } else {
1649
            if ($this->_c->errno) {
1650
                fwrite(STDOUT, $this->_c->error . PHP_EOL);
1651
            }
1652
        }
1653
1654 1
        return false;
1655
    }
1656
1657
    /**
1658
     * Function to detect if string is a JSON object or not
1659
     *
1660
     * @param string $strVal
1661
     *
1662
     * @return boolean
1663
     */
1664 1
    public function isJson($strVal)
1665
    {
1666 1
        json_decode($strVal);
1667 1
        return (json_last_error() == JSON_ERROR_NONE);
1668
    }
1669
1670
    /**
1671
     * Function to escape SQL characters to prevent SQL injection
1672
     *
1673
     * @param mixed $val
1674
     *            Value to escape
1675
     * @param boolean $blnEscape
1676
     *            Decide if we should escape or not
1677
     *
1678
     * @return string Escaped value
1679
     */
1680 115
    public function _escape($val, $blnEscape = true)
1681
    {
1682 115
        if (is_null($val) || (is_string($val) && strtolower($val) == 'null')) {
1683 1
            return 'NULL';
1684 115
        } elseif (is_numeric($val) || is_string($val)) {
1685 115
            if (stripos($val, "IF(") !== false) {
1686
                return $val;
1687 115
            } elseif ($blnEscape) {
1688 115
                return "'{$this->_c->real_escape_string($val)}'";
1689
            }
1690 2
            return "'{$val}'";
1691 6
        } elseif (is_a($val, 'DateTime')) {
1692 1
            return "'{$val->format(MYSQL_DATETIME)}'";
1693 5
        } elseif (is_bool($val)) {
1694 1
            return $val ? "'1'" : "'0'";
1695 4
        } elseif (is_array($val)) {
1696 1
            $ret = [];
1697 1
            foreach($val as $v) {
1698 1
                $ret[] = $this->_escape($v);
1699
            }
1700 1
            return "(" . implode(",", $ret) . ")";
1701 3
        } elseif (is_object($val) && method_exists($val, '_escape')) {
1702 2
            $ret = call_user_func([
1703 2
                $val,
1704 2
                '_escape'
1705
            ]);
1706 2
            if ($ret !== false) {
1707 1
                return $ret;
1708
            } else {
1709 1
                throw new Exception("Error in return from _escape method in " . get_class($val), E_ERROR);
1710
            }
1711
        }
1712
1713 1
        throw new Exception("Unknown datatype to escape in SQL string {$this->_sql} " . gettype($val), E_ERROR);
1714
    }
1715
1716
    /**
1717
     * Function to retrieve all results
1718
     *
1719
     * @param int $intResultType
1720
     *
1721
     * @return mixed
1722
     */
1723
    protected function fetchAll($intResultType = MYSQLI_ASSOC)
1724
    {
1725
        $res = [];
1726
        if (method_exists('mysqli_result', 'fetch_all')) { // Compatibility layer with PHP < 5.3
1727
            $res = $this->_result->fetch_all($intResultType);
1728
        } else {
1729
            while ($tmp = $this->_result->fetch_array($intResultType)) {
1730
                $res[] = $tmp;
1731
            }
1732
        }
1733
1734
        return $res;
1735
    }
1736
1737
    /**
1738
     * Function to populate the fields for the SQL
1739
     *
1740
     * @param array|string $fields
1741
     *            [optional]
1742
     *            Optional array of fields to string together to create a field list
1743
     *
1744
     * @return string
1745
     */
1746 33
    protected function fields($fields = null)
1747
    {
1748 33
        $ret = null;
1749
1750 33
        if (is_array($fields) && count($fields) && isset($fields[0]) && is_string($fields[0])) {
1751 2
            foreach ($fields as $field) {
1752 2
                if ((strpos($field, '`') === false) && (strpos($field, '.') === false) && (strpos($field, '*') === false) && (strpos($field, 'JSON_') === false) && (stripos($field, ' as ') === false)) {
1753 2
                    $ret .= "`$field`,";
1754
                } else {
1755
                    $ret .= "$field,";
1756
                }
1757
            }
1758 2
            $ret = substr($ret, - 1) == ',' ? substr($ret, 0, - 1) : $ret;
1759 31
        } elseif (is_string($fields)) {
1760 4
            $ret = $fields;
1761 27
        } elseif (is_null($fields)) {
1762 26
            $ret = "*";
1763
        } else {
1764 1
            throw new \InvalidArgumentException("Invalid field type");
1765
        }
1766
1767 32
        return $ret;
1768
    }
1769
1770
    /**
1771
     * Function to parse the flags
1772
     *
1773
     * @param array $flags
1774
     *            Two-dimensional array to added flags
1775
     *
1776
     *            <code>
1777
     *            [
1778
     *            &nbsp;&nbsp;'joins' => [
1779
     *            &nbsp;&nbsp;&nbsp;&nbsp;"JOIN table2 t2 ON t2.id=t1.id"
1780
     *            &nbsp;&nbsp;],
1781
     *            &nbsp;&nbsp;'group' => 'field',
1782
     *            &nbsp;&nbsp;'having' => 'field',
1783
     *            &nbsp;&nbsp;'order' => 'field',
1784
     *            &nbsp;&nbsp;'start' => 0,
1785
     *            &nbsp;&nbsp;'limit' => 0
1786
     *            ]
1787
     *            </code>
1788
     *
1789
     * @see Database::groups()
1790
     * @see Database::having()
1791
     * @see Database::order()
1792
     *
1793
     * @return string
1794
     */
1795 9
    protected function flags($arrFlags)
1796
    {
1797 9
        $ret = '';
1798
1799 9
        if (isset($arrFlags['group'])) {
1800 3
            $ret .= $this->groups($arrFlags['group']);
1801
        }
1802
1803 8
        if (isset($arrFlags['having']) && is_array($arrFlags['having'])) {
1804 1
            $having = " HAVING";
1805 1
            $this->_logger->debug("Parsing where clause and adding to query");
1806 1
            foreach ($arrFlags['having'] as $x => $h) {
1807 1
                if($x > 0) {
1808 1
                    $having .= " {$h->sqlOperator}";
1809
                }
1810 1
                $having .= $h;
1811
            }
1812 1
            if(strlen($having) > strlen(" HAVING")) {
1813 1
                $ret .= $having;
1814
            }
1815
        }
1816
1817 8
        if (isset($arrFlags['order'])) {
1818 2
            $ret .= $this->order($arrFlags['order']);
1819
        }
1820
1821 8
        if (isset($arrFlags['limit']) && (is_string($arrFlags['limit']) || is_numeric($arrFlags['limit']))) {
1822 1
            $ret .= " LIMIT ";
1823 1
            if (isset($arrFlags['start']) && (is_string($arrFlags['start']) || is_numeric($arrFlags['start']))) {
1824 1
                $ret .= "{$arrFlags['start']},";
1825
            }
1826 1
            $ret .= "{$arrFlags['limit']}";
1827
        }
1828
1829 8
        return $ret;
1830
    }
1831
1832
    /**
1833
     * Function to parse SQL GROUP BY statements
1834
     *
1835
     * @param mixed $groups
1836
     *
1837
     * @return string
1838
     */
1839 3
    protected function groups($groups)
1840
    {
1841 3
        $ret = '';
1842 3
        if (is_array($groups) && count($groups)) {
1843 1
            $ret .= " GROUP BY";
1844
1845 1
            foreach ($groups as $grp) {
1846 1
                $ret .= " $grp";
1847
1848 1
                if ($grp != end($groups)) {
1849 1
                    $ret .= ",";
1850
                }
1851
            }
1852 2
        } elseif (is_string($groups)) {
1853 1
            $ret .= " GROUP BY {$groups}";
1854
        } else {
1855 1
            throw (new Exception("Error in datatype for groups " . gettype($groups), E_ERROR));
1856
        }
1857
1858 2
        return $ret;
1859
    }
1860
1861
    /**
1862
     * Function to parse SQL ORDER BY statements
1863
     *
1864
     * @param mixed $order
1865
     *
1866
     * @return string
1867
     */
1868 2
    protected function order($order)
1869
    {
1870 2
        $ret = '';
1871 2
        if (is_array($order)) {
1872 1
            $ret .= " ORDER BY";
1873
1874 1
            foreach ($order as $ord) {
1875 1
                $ret .= " {$ord['field']} {$ord['sort']}";
1876
1877 1
                if ($ord != end($order)) {
1878 1
                    $ret .= ",";
1879
                }
1880
            }
1881 1
        } elseif (is_string($order)) {
1882 1
            $ret .= " ORDER BY {$order}";
1883
        }
1884
1885 2
        return $ret;
1886
    }
1887
1888
    /**
1889
     * Function to see if a constraint exists
1890
     *
1891
     * @param string $strConstraintId
1892
     *
1893
     * @return boolean
1894
     */
1895
    public function isConstraint($strConstraintId)
1896
    {
1897
        $res = $this->_c->query("SELECT * FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_NAME = '{$strConstraintId}'");
1898
1899
        if ($res->num_rows) {
1900
            return true;
1901
        }
1902
1903
        return false;
1904
    }
1905
1906
    /**
1907
     * Method to add a where clause
1908
     * 
1909
     * @param DBWhere|array:DBWhere $where
0 ignored issues
show
Documentation Bug introduced by
The doc comment $where at position 0 could not be parsed: Unknown type name '$where' at position 0 in $where.
Loading history...
1910
     * 
1911
     * @return boolean|array:DBWhere
1912
     */
1913 46
    public function parseClause($where) 
1914
    {
1915 46
        $ret = [];
1916 46
        $interfaces = [];
1917 46
        if(is_object($where)) {
1918 9
            $interfaces = \class_implements($where);
1919
        }
1920 46
        if(is_array($where)) {
1921 36
            foreach($where as $k => $w) {
1922 9
                if(!is_a($w, 'Godsgood33\Php_Db\DBWhere')) {
1923 1
                    return false;
1924
                }
1925 8
                $v = $this->_escape($w->value, $w->escape);
0 ignored issues
show
Bug Best Practice introduced by
The property value does not exist on Godsgood33\Php_Db\DBWhere. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug Best Practice introduced by
The property escape does not exist on Godsgood33\Php_Db\DBWhere. Since you implemented __get, consider adding a @property annotation.
Loading history...
1926 8
                $where[$k]->value = $v;
1927
1928 8
                $ret[] = $where[$k];
1929
            }
1930 10
        } elseif(is_a($where, 'Godsgood33\Php_Db\DBWhere')) {
1931 9
            $v = $this->_escape($where->value, $where->escape);
1932 7
            $where->value = $v;
0 ignored issues
show
Bug Best Practice introduced by
The property value does not exist on Godsgood33\Php_Db\DBWhere. Since you implemented __set, consider adding a @property annotation.
Loading history...
1933 7
            $ret[] = $where;
1934 2
        } elseif(in_array("Godsgood33\Php_Db\DBInterface", $interfaces) && is_callable(get_class($where) . "::where")) {
1935 1
            $params = \call_user_func([$where, "where"]);
1936 1
            $ret = $this->parseClause($params);
1937
        } else {
1938 1
            $this->_logger->warning("Failed to get where from", [$where]);
1939
        }
1940
1941 43
        return $ret;
1942
    }
1943
1944
    /**
1945
     * Encryption algorithm
1946
     *
1947
     * @param string $data
1948
     * @param string $key
1949
     * 
1950
     * @throws Exception
1951
     * 
1952
     * @return string
1953
     */
1954
    public static function encrypt($data, $salt = null)
1955
    {
1956
        if(!defined('PHP_DB_ENCRYPT_SALT') || !defined('PHP_DB_ENCRYPT_ALGORITHM')) {
1957
            throw new Exception("Need to declare and populate PHP_DB_ENCRYPT_SALT and PHP_DB_ENCRYPT_ALGORITHM");
1958
        }
1959
1960
        // Remove the base64 encoding from our key
1961
        if (is_null($salt)) {
1962
            $encryption_key = base64_decode(PHP_DB_ENCRYPT_SALT);
1963
        } else {
1964
            $encryption_key = base64_decode($salt);
1965
        }
1966
        // Generate an initialization vector
1967
        $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length(PHP_DB_ENCRYPT_ALGORITHM));
1968
        // Encrypt the data using AES 256 encryption in CBC mode using our encryption key and initialization vector.
1969
        $encrypted = openssl_encrypt($data, PHP_DB_ENCRYPT_ALGORITHM, $encryption_key, 0, $iv);
1970
        // The $iv is just as important as the key for decrypting, so save it with our encrypted data using a unique separator (::)
1971
        return base64_encode($encrypted . '::' . $iv);
1972
    }
1973
1974
    /**
1975
     * Decryption algorithm
1976
     *
1977
     * @param string $data
1978
     * 
1979
     * @throws Exception
1980
     * 
1981
     * @return string
1982
     */
1983 115
    public static function decrypt($data)
1984
    {
1985 115
        if(!defined('PHP_DB_ENCRYPT_SALT') || !defined('PHP_DB_ENCRYPT_ALGORITHM')) {
1986
            throw new Exception("Need to declare and populate PHP_DB_ENCRYPT_SALT and PHP_DB_ENCRYPT_ALGORITHM");
1987
        }
1988
1989
        // Remove the base64 encoding from our key
1990 115
        $encryption_key = base64_decode(PHP_DB_ENCRYPT_SALT);
1991
1992
        // To decrypt, split the encrypted data from our IV - our unique separator used was "::"
1993 115
        list($encrypted_data, $iv) = explode('::', base64_decode($data), 2);
1994 115
        $plaintext = openssl_decrypt($encrypted_data, PHP_DB_ENCRYPT_ALGORITHM, $encryption_key, 0, $iv);
1995 115
        return $plaintext;
1996
    }
1997
1998
    /**
1999
     * Method to check if all required fields are available in the object
2000
     * 
2001
     * @param object $object
2002
     * @param array:string $requiredFields
0 ignored issues
show
Documentation Bug introduced by
The doc comment $requiredFields at position 0 could not be parsed: Unknown type name '$requiredFields' at position 0 in $requiredFields.
Loading history...
2003
     * 
2004
     * @return boolean
2005
     */
2006 11
    public static function checkObject($object, $requiredFields)
2007
    {
2008 11
        $haystack = array_keys(json_decode(json_encode($object), true));
2009 11
        foreach($requiredFields as $r) {
2010 11
            if(!in_array($r, $haystack)) {
2011 3
                return false;
2012
            }
2013
        }
2014
2015 8
        return true;
2016
    }
2017
}
2018