DatabaseConnection::setDatabase()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 2
c 1
b 0
f 1
nc 1
nop 1
dl 0
loc 3
rs 10
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 MIT License (MIT)
9
     *
10
     * Copyright (c) 2017 TNH Framework
11
     *
12
     * Permission is hereby granted, free of charge, to any person obtaining a copy
13
     * of this software and associated documentation files (the "Software"), to deal
14
     * in the Software without restriction, including without limitation the rights
15
     * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
     * copies of the Software, and to permit persons to whom the Software is
17
     * furnished to do so, subject to the following conditions:
18
     *
19
     * The above copyright notice and this permission notice shall be included in all
20
     * copies or substantial portions of the Software.
21
     *
22
     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
     * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
     * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
     * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
     * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
     * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
     * SOFTWARE.
29
     */
30
    
31
    class DatabaseConnection extends BaseClass {
32
	
33
        /**
34
         * The PDO instance
35
         * @var object
36
         */
37
        private $pdo = null;
38
      
39
        /**
40
         * The database driver name to use
41
         * @var string
42
         */
43
        private $driver = null;
44
45
         /**
46
         * The database hostname
47
         * @var string
48
         */
49
        private $hostname = null;
50
51
          /**
52
         * The database port
53
         * @var integer
54
         */
55
        private $port = null;
56
        
57
         /**
58
         * The database username
59
         * @var string
60
         */
61
        private $username = null;
62
63
         /**
64
         * The database password
65
         * @var string
66
         */
67
        private $password = null;
68
69
        /**
70
         * The database name used for the application
71
         * @var string
72
         */
73
        private $databaseName = null;
74
75
         /**
76
         * The database charset
77
         * @var string
78
         */
79
        private $charset = null;
80
81
        /**
82
         * The database collation
83
         * @var string
84
         */
85
        private $collation = null;
86
87
         /**
88
         * The database tables prefix
89
         * @var string
90
         */
91
        private $prefix = null;
92
93
        /**
94
         * The database configuration
95
         * @var array
96
         */
97
        private $config = array();
98
	
99
        /**
100
         * Construct new DatabaseConnection
101
         * 
102
         * @param array $config the database configuration config
103
         * @param boolean $autoConnect whether to connect to database automatically
104
         */
105
        public function __construct(array $config = array(), $autoConnect = false) {
106
            parent::__construct();
107
            //Note need use the method to set config
108
            $this->setConfig($config);
109
110
            //if we need connect or not
111
            if ($autoConnect) {
112
                $this->connect();
113
            }
114
        }
115
116
         /**
117
         * This is method is used to connect to database
118
         * 
119
         * @return boolean true in case of successfully connection false if error
120
         */
121
        public function connect() {
122
            try {
123
                if(empty($this->config) && file_exists(CONFIG_PATH . 'database.php')) {
124
                    $db = array();
125
                    require CONFIG_PATH . 'database.php';
126
                    //Note need use the method to set config
127
                    $this->setConfig($db);
128
                }
129
                $options = array(
130
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ
131
                );
132
                $this->pdo = new PDO($this->getDsn(), $this->getUsername(), $this->getPassword(), $options);
133
                if($this->getDriver() == 'mysql') {
134
                    $this->pdo->exec("SET NAMES '" . $this->getCharset() . "' COLLATE '" . $this->getCollation() . "'");
135
                    $this->pdo->exec("SET CHARACTER SET '" . $this->getCharset() . "'");
136
                }
137
                return is_object($this->pdo);
138
            } catch (PDOException $e) {
139
                $this->logger->critical($e->getMessage());
140
                show_error('Cannot connect to Database.');
141
                return false;
142
            }
143
        }
144
145
        /**
146
         * Disconnect from database server
147
         */
148
        public function disconnect() {
149
            $this->pdo = null;
150
        }
151
152
        /**
153
         * Escape the data before execute query useful for security.
154
         * @param  mixed $data the data to be escaped
155
         * @param boolean $escaped whether can do escape or not 
156
         * @return mixed       the data after escaped or the same data if no
157
         * need escaped
158
         */
159
        public function escape($data, $escaped = true) {
160
            $data = trim($data);
161
            if ($escaped) {
162
                return $this->pdo->quote($data);
163
            }
164
            return $data; 
165
        }
166
167
        /**
168
         * Get the DSN value for the configuration driver
169
         * 
170
         * @return string|null         the dsn value
171
         */
172
        public function getDsn() {
173
            $dsn    = '';
174
            $port   = $this->getPort();
175
            $driver = $this->getDriver();
176
177
            $driversDsn = array(
178
                'mysql'  => 'mysql:host=' . $this->getHostname() . ';%sdbname=' . $this->getDatabase() . ';charset=' . $this->getCharset(),
179
                'pgsql'  => 'pgsql:host=' . $this->getHostname() . ';%sdbname=' . $this->getDatabase() . ';charset=' . $this->getCharset(),
180
                'oracle' => 'oci:dbname=' . $this->getHostname() . '%s/' . $this->getDatabase() . ';charset=' . $this->getCharset(),
181
                'sqlite' => 'sqlite:' . $this->getDatabase()
182
            );
183
            if ($port) {
184
                $driversPort = array(
185
                      'mysql'  => 'port=' . $port . ';',
186
                      'pgsql'  => 'port=' . $port . ';',
187
                      'oracle' => ':' . $port
188
                );
189
                if (isset($driversPort[$driver])) {
190
                    $port = $driversPort[$driver];
191
                }
192
            }
193
            if (isset($driversDsn[$driver])) {
194
                $dsn = sprintf($driversDsn[$driver], $port);
195
            }
196
            return $dsn;
197
        }
198
        
199
        /**
200
         * Return the PDO instance
201
         * @return object
202
         */
203
        public function getPdo() {
204
            return $this->pdo;
205
        }
206
207
        /**
208
         * Set the PDO object
209
         * @param object $pdo the instance of PDO
210
         *
211
         * @return object the current instance
212
         */
213
        public function setPdo(PDO $pdo = null) {
214
            $this->pdo = $pdo;
215
            return $this;
216
        }
217
218
        /**
219
         * Return the driver
220
         * 
221
         * @return string
222
         */
223
        public function getDriver() {
224
            return $this->driver;
225
        }
226
227
        /**
228
         * Set the driver
229
         * 
230
         * @param string $driver the drive to set like "pgsql", "mysql", etc.
231
         *
232
         * @return object the current instance
233
         */
234
        public function setDriver($driver) {
235
            $this->driver = $driver;
236
            return $this;
237
        }
238
239
        /**
240
         * Return the hostname
241
         * @return string
242
         */
243
        public function getHostname() {
244
            return $this->hostname;
245
        }
246
247
        /**
248
         * Set the hostname
249
         * @param string $hostname the hostname to set
250
         *
251
         * @return object the current instance
252
         */
253
        public function setHostname($hostname) {
254
            $this->hostname = $hostname;
255
            return $this;
256
        }
257
258
        /**
259
         * Return the port
260
         * 
261
         * @return int
262
         */
263
        public function getPort() {
264
            return $this->port;
265
        }
266
267
        /**
268
         * Set the port number
269
         * 
270
         * @param int $port the port to set
271
         *
272
         * @return object the current instance
273
         */
274
        public function setPort($port) {
275
            $this->port = $port;
276
            return $this;
277
        }
278
279
        /**
280
         * Return the username
281
         * 
282
         * @return string
283
         */
284
        public function getUsername() {
285
            return $this->username;
286
        }
287
288
        /**
289
         * Set the username
290
         * 
291
         * @param string $username the username to set
292
         *
293
         * @return object the current instance
294
         */
295
        public function setUsername($username) {
296
            $this->username = $username;
297
            return $this;
298
        }
299
300
        /**
301
         * Return the password
302
         * @return string
303
         */
304
        public function getPassword() {
305
            return $this->password;
306
        }
307
308
        /**
309
         * Set the password
310
         * 
311
         * @param string $password the password to set
312
         *
313
         * @return object the current instance
314
         */
315
        public function setPassword($password) {
316
            $this->password = $password;
317
            return $this;
318
        }
319
320
        /**
321
         * Return the database name
322
         * @return string
323
         */
324
        public function getDatabase() {
325
            return $this->databaseName;
326
        }
327
328
        /**
329
         * Set the database name
330
         * 
331
         * @param string $database the name of the database to set
332
         *
333
         * @return object the current instance
334
         */
335
        public function setDatabase($database) {
336
            $this->databaseName = $database;
337
            return $this;
338
        }
339
340
        /**
341
         * Return the charset
342
         * 
343
         * @return string
344
         */
345
        public function getCharset() {
346
            return $this->charset;
347
        }
348
349
        /**
350
         * Set the charset
351
         * 
352
         * @param string $charset the charset to set
353
         *
354
         * @return object the current instance
355
         */
356
        public function setCharset($charset) {
357
            $this->charset = $charset;
358
            return $this;
359
        }
360
361
        /**
362
         * Return the collation
363
         * 
364
         * @return string
365
         */
366
        public function getCollation() {
367
            return $this->collation;
368
        }
369
370
        /**
371
         * Set the collation
372
         * 
373
         * @param string $collation the collation to set
374
         *
375
         * @return object the current instance
376
         */
377
        public function setCollation($collation) {
378
            $this->collation = $collation;
379
            return $this;
380
        }
381
382
        /**
383
         * Return the prefix
384
         * 
385
         * @return string
386
         */
387
        public function getPrefix() {
388
            return $this->prefix;
389
        }
390
391
        /**
392
         * Set the tables prefix
393
         * 
394
         * @param string $prefix the prefix to set
395
         *
396
         * @return object the current instance
397
         */
398
        public function setPrefix($prefix) {
399
            $this->prefix = $prefix;
400
            return $this;
401
        }
402
403
        /**
404
         * Return the database configuration
405
         * 
406
         * @return array
407
         */
408
        public function getConfig() {
409
            return $this->config;
410
        }
411
412
        /**
413
         * Set the database configuration
414
         * 
415
         * @param array $config the configuration to set
416
         *
417
         * @return object the current instance
418
         */
419
        public function setConfig(array $config) {
420
            $this->config = $config;
421
            //populate the properties
422
            $this->populatePropertiesFromConfig();
423
424
            if (!empty($this->config)) {
425
               //For logging
426
                $configInfo = $this->config;
427
                //Hide password from log
428
                $configInfo['password'] = string_hidden($this->getPassword());
429
                $this->logger->info('The database configuration are listed below: ' . stringify_vars($configInfo));
430
            }
431
            return $this;
432
        }
433
        
434
         /**
435
         * Update the properties using the current database configuration
436
         * 
437
         * @return object the current instance
438
         */
439
        protected function populatePropertiesFromConfig() {
440
            foreach ($this->config as $key => $value) {
441
                $setter = 'set' . ucfirst($key);
442
                if (method_exists($this, $setter)) {
443
                    $this->{$setter}($value);
444
                }
445
            }
446
            //determine the port using the hostname like localhost:34455
447
            //hostname will be "localhost", and port "34455"
448
            $part = explode(':', $this->hostname);
449
            if (count($part) >= 2) {
450
                $this->config['hostname'] = $part[0];
451
                $this->config['port'] = $part[1];
452
                $this->hostname = $part[0];
453
                $this->port = (int) $part[1];
454
            }
455
            return $this;
456
        }
457
458
        /**
459
         * Class desctructor this is used to disconnect to server
460
         * and call $this->disconnect
461
         */
462
        public function __destruct() {
463
            $this->disconnect();
464
        }
465
    }
466