Test Failed
Push — 1.0.0-dev ( 72449d...860cec )
by nguereza
02:46
created

DatabaseConnection::setCharset()   A

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
108
            //Note need use the method to set config
109
            $this->setConfig($config);
110
111
            //if we need connect or not
112
            if ($autoConnect) {
113
                $this->connect();
114
            }
115
        }
116
117
         /**
118
         * This is method is used to connect to database
119
         * 
120
         * @return boolean true in case of successfully connection false if error
121
         */
122
        public function connect() {
123
            try {
124
                $options = array(
125
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ
126
                );
127
                $this->pdo = new PDO($this->getDsnValue(), $this->getUsername(), $this->getPassword(), $options);
128
                if($this->getDriver() == 'mysql') {
129
                    $this->pdo->exec("SET NAMES '" . $this->getCharset() . "' COLLATE '" . $this->getCollation() . "'");
130
                    $this->pdo->exec("SET CHARACTER SET '" . $this->getCharset() . "'");
131
                }
132
                return is_object($this->pdo);
133
            } catch (PDOException $e) {
134
                $this->logger->fatal($e->getMessage());
135
                show_error('Cannot connect to Database.');
136
                return false;
137
            }
138
        }
139
140
        /**
141
         * Disconnect from database server
142
         */
143
        public function disconnect() {
144
            $this->pdo = null;
145
        }
146
147
        /**
148
         * Escape the data before execute query useful for security.
149
         * @param  mixed $data the data to be escaped
150
         * @param boolean $escaped whether we can do escape of not 
151
         * @return mixed       the data after escaped or the same data if no
152
         * need escaped
153
         */
154
        public function escape($data, $escaped = true) {
155
            $data = trim($data);
156
            if ($escaped) {
157
                return $this->pdo->quote($data);
158
            }
159
            return $data; 
160
        }
161
162
        /**
163
         * Get the DSN value for the configuration driver
164
         * 
165
         * @return string|null         the dsn value
166
         */
167
        public function getDsnValue() {
168
            $dsn    = '';
169
            $port   = $this->getPort();
170
            $driver = $this->getDriver();
171
172
            $driversDsn = array(
173
                'mysql'  => 'mysql:host=' . $this->getHostname() . ';%sdbname=' . $this->getDatabase() . ';charset=' . $this->getCharset(),
174
                'pgsql'  => 'pgsql:host=' . $this->getHostname() . ';%sdbname=' . $this->getDatabase() . ';charset=' . $this->getCharset(),
175
                'oracle' => 'oci:dbname=' . $this->getHostname() . '%s/' . $this->getDatabase() . ';charset=' . $this->getCharset(),
176
                'sqlite' => 'sqlite:' . $this->getDatabase()
177
            );
178
            if ($port) {
179
                if (in_array($driver, array('mysql', 'pgsql'))) {
180
                    $port = 'port=' . $port . ';';
181
                } else if ($driver == 'oracle') {
182
                    $port = ':' . $port;
183
                }
184
            }
185
            if (isset($driversDsn[$driver])) {
186
                $dsn = sprintf($driversDsn[$driver], $port);
187
            }
188
            return $dsn;
189
        }
190
        
191
        /**
192
         * Return the PDO instance
193
         * @return object
194
         */
195
        public function getPdo() {
196
            return $this->pdo;
197
        }
198
199
        /**
200
         * Set the PDO object
201
         * @param object $pdo the instance of PDO
202
         *
203
         * @return object the current instance
204
         */
205
        public function setPdo(PDO $pdo = null) {
206
            $this->pdo = $pdo;
207
            return $this;
208
        }
209
210
        /**
211
         * Return the driver
212
         * 
213
         * @return string
214
         */
215
        public function getDriver() {
216
            return $this->driver;
217
        }
218
219
        /**
220
         * Set the driver
221
         * 
222
         * @param string $driver the drive to set like "pgsql", "mysql", etc.
223
         *
224
         * @return object the current instance
225
         */
226
        public function setDriver($driver) {
227
            $this->driver = $driver;
228
            return $this;
229
        }
230
231
        /**
232
         * Return the hostname
233
         * @return string
234
         */
235
        public function getHostname() {
236
            return $this->hostname;
237
        }
238
239
        /**
240
         * Set the hostname
241
         * @param string $hostname the hostname to set
242
         *
243
         * @return object the current instance
244
         */
245
        public function setHostname($hostname) {
246
            $this->hostname = $hostname;
247
            return $this;
248
        }
249
250
        /**
251
         * Return the port
252
         * 
253
         * @return int
254
         */
255
        public function getPort() {
256
            return $this->port;
257
        }
258
259
        /**
260
         * Set the port number
261
         * 
262
         * @param int $port the port to set
263
         *
264
         * @return object the current instance
265
         */
266
        public function setPort($port) {
267
            $this->port = $port;
268
            return $this;
269
        }
270
271
        /**
272
         * Return the username
273
         * 
274
         * @return string
275
         */
276
        public function getUsername() {
277
            return $this->username;
278
        }
279
280
        /**
281
         * Set the username
282
         * 
283
         * @param string $username the username to set
284
         *
285
         * @return object the current instance
286
         */
287
        public function setUsername($username) {
288
            $this->username = $username;
289
            return $this;
290
        }
291
292
        /**
293
         * Return the password
294
         * @return string
295
         */
296
        public function getPassword() {
297
            return $this->password;
298
        }
299
300
        /**
301
         * Set the password
302
         * 
303
         * @param string $password the password to set
304
         *
305
         * @return object the current instance
306
         */
307
        public function setPassword($password) {
308
            $this->password = $password;
309
            return $this;
310
        }
311
312
        /**
313
         * Return the database name
314
         * @return string
315
         */
316
        public function getDatabase() {
317
            return $this->databaseName;
318
        }
319
320
        /**
321
         * Set the database name
322
         * 
323
         * @param string $database the name of the database to set
324
         *
325
         * @return object the current instance
326
         */
327
        public function setDatabase($database) {
328
            $this->databaseName = $database;
329
            return $this;
330
        }
331
332
        /**
333
         * Return the charset
334
         * 
335
         * @return string
336
         */
337
        public function getCharset() {
338
            return $this->charset;
339
        }
340
341
        /**
342
         * Set the charset
343
         * 
344
         * @param string $charset the charset to set
345
         *
346
         * @return object the current instance
347
         */
348
        public function setCharset($charset) {
349
            $this->charset = $charset;
350
            return $this;
351
        }
352
353
        /**
354
         * Return the collation
355
         * 
356
         * @return string
357
         */
358
        public function getCollation() {
359
            return $this->collation;
360
        }
361
362
        /**
363
         * Set the collation
364
         * 
365
         * @param string $collation the collation to set
366
         *
367
         * @return object the current instance
368
         */
369
        public function setCollation($collation) {
370
            $this->collation = $collation;
371
            return $this;
372
        }
373
374
        /**
375
         * Return the prefix
376
         * 
377
         * @return string
378
         */
379
        public function getPrefix() {
380
            return $this->prefix;
381
        }
382
383
        /**
384
         * Set the tables prefix
385
         * 
386
         * @param string $prefix the prefix to set
387
         *
388
         * @return object the current instance
389
         */
390
        public function setPrefix($prefix) {
391
            $this->prefix = $prefix;
392
            return $this;
393
        }
394
395
        /**
396
         * Return the database configuration
397
         * 
398
         * @return array
399
         */
400
        public function getConfig() {
401
            return $this->config;
402
        }
403
404
        /**
405
         * Set the database configuration
406
         * 
407
         * @param array $config the configuration to set
408
         *
409
         * @return object the current instance
410
         */
411
        public function setConfig(array $config) {
412
            $this->config = $config;
413
            //populate the properties
414
            $this->populatePropertiesFromConfig();
415
416
            if (!empty($this->config)) {
417
               //For logging
418
                $configInfo = $this->config;
419
                //Hide password from log
420
                $configInfo['password'] = string_hidden($this->getPassword());
421
                $this->logger->info('The database configuration are listed below: ' . stringfy_vars($configInfo));
422
            }
423
            return $this;
424
        }
425
426
         /**
427
         * Get the database configuration using the configuration file
428
         
429
         * @return array the database configuration from file
430
         */
431
        public function getDatabaseConfigFromFile() {
432
            $db = array();
433
            if (file_exists(CONFIG_PATH . 'database.php')) {
434
                //here don't use require_once because somewhere user can create database instance directly
435
                require CONFIG_PATH . 'database.php';
436
            }
437
            return $db;
438
        }
439
440
         /**
441
         * Update the properties using the current database configuration
442
         * 
443
         * @return object the current instance
444
         */
445
        protected function populatePropertiesFromConfig() {
446
            foreach ($this->config as $key => $value) {
447
                $setter = 'set' . ucfirst($key);
448
                if (method_exists($this, $setter)) {
449
                    $this->{$setter}($value);
450
                }
451
            }
452
            //determine the port using the hostname like localhost:34455
453
            //hostname will be "localhost", and port "34455"
454
            $part = explode(':', $this->hostname);
455
            if (count($part) >= 2) {
456
                $this->config['hostname'] = $part[0];
457
                $this->config['port'] = $part[1];
458
                $this->hostname = $part[0];
459
                $this->port = (int) $part[1];
460
            }
461
            return $this;
462
        }
463
464
        /**
465
         * Class desctructor this is used to disconnect to server
466
         * and call $this->disconnect
467
         */
468
        function __destruct() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

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

Loading history...
469
            $this->disconnect();
470
        }
471
    }
472