Completed
Push — master ( af423c...f81b31 )
by Adeola
02:40
created

DataBaseConnection   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 15
Bugs 7 Features 1
Metric Value
wmc 6
c 15
b 7
f 1
lcom 1
cbo 1
dl 0
loc 58
ccs 0
cts 17
cp 0
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 17 1
A getDataBaseDriver() 0 13 4
A loadEnv() 0 5 1
1
<?php
2
3
/**
4
 * This class is involve in connection to the database.
5
 *
6
 * @author   Raimi Ademola <[email protected]>
7
 * @copyright: 2016 Andela
8
 */
9
namespace Demo;
10
11
use Dotenv\Dotenv;
12
use PDO;
13
14
class DataBaseConnection extends PDO
15
{
16
    private $servername;
17
    private $username;
18
    private $password;
19
    private $driver;
20
    private $dbname;
21
22
    /**
23
     * This is a constructor; a default method  that will be called automatically during class instantiation.
24
     */
25
    public function __construct()
26
    {
27
        $this->loadEnv();
28
29
        $this->servername = getenv('DB_HOST');
30
        $this->username   = getenv('DB_USERNAME');
31
        $this->password   = getenv('DB_PASSWORD');
32
        $this->driver     = getenv('DB_DRIVER');
33
        $this->dbname     = getenv('DB_NAME');
34
35
        $options = [
36
            PDO::ATTR_PERSISTENT => true,
37
            PDO::ATTR_ERRMODE    => PDO::ERRMODE_EXCEPTION,
38
        ];
39
40
        parent::__construct($this->getDataBaseDriver(), $this->username, $this->password, $options);
41
    }
42
43
    /**
44
     * This method determines the driver to be used for appropriate database server.
45
     *
46
     *
47
     * @return string dsn
48
     */
49
    public function getDataBaseDriver()
50
    {
51
        if ($this->driver === 'mysql') {
52
            $dns = 'mysql:host='.$this->servername.';dbname='.$this->dbname;
53
            return $dns;
54
        } elseif ($this->driver === 'sqlite') {
55
            $dns = 'sqlite:host='.$this->servername.';dbname='.$this->dbname;
56
            return $dns;    
57
        } elseif ($this->driver === 'pgsqlsql') {
58
             $dns = 'pgsqlsql:host='.$this->servername.';dbname='.$this->dbname;
59
             return $dns;
60
        }
61
    }
62
63
    /**
64
     * Load Dotenv to grant getenv() access to environment variables in .env file.
65
     */
66
    private function loadEnv()
67
    {
68
        $dotenv = new Dotenv(__DIR__.'/../../');
69
        $dotenv->load();
70
    }
71
}
72