Passed
Push — 1.0.0-dev ( 29a38b...3f14f3 )
by nguereza
02:39
created

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

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
441
            }
442
            return $this;
443
        }
444
    }
445