Completed
Push — master ( dbee2d...aaa992 )
by Adeola
04:02
created

DataBaseConnection   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 71.43%

Importance

Changes 17
Bugs 8 Features 2
Metric Value
wmc 7
c 17
b 8
f 2
lcom 1
cbo 1
dl 0
loc 62
ccs 20
cts 28
cp 0.7143
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getDataBaseDriver() 0 16 4
A __construct() 0 17 1
A loadEnv() 0 6 2
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
    public $servername;
17
    public $username;
18
    public $password;
19
    public $driver;
20
    public $dbname;
21
22
    /**
23
     * This is a constructor; a default method  that will be called automatically during class instantiation.
24
     */
25 21
    public function __construct($path = null)
26
    {
27 21
        $this->loadEnv($path = null);
28
29 21
        $this->servername = getenv('DB_HOST');
30 21
        $this->username = getenv('DB_USERNAME');
31 21
        $this->password = getenv('DB_PASSWORD');
32 21
        $this->driver = getenv('DB_DRIVER');
33 21
        $this->dbname = getenv('DB_NAME');
34
35
        $options = [
36 21
            PDO::ATTR_PERSISTENT => true,
37 14
            PDO::ATTR_ERRMODE    => PDO::ERRMODE_EXCEPTION,
38 14
        ];
39
40 21
        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 21
    public function getDataBaseDriver()
50
    {
51 21
        if ($this->driver === 'mysql') {
52 21
            $dns = 'mysql:host='.$this->servername.';dbname='.$this->dbname;
53
54 21
            return $dns;
55
        } elseif ($this->driver === 'sqlite') {
56
            $dns = 'sqlite:host='.$this->servername.';dbname='.$this->dbname;
57
58
            return $dns;
59
        } elseif ($this->driver === 'pgsqlsql') {
60
            $dns = 'pgsqlsql:host='.$this->servername.';dbname='.$this->dbname;
61
62
            return $dns;
63
        }
64
    }
65
66
    /**
67
     * Load Dotenv to grant getenv() access to environment variables in .env file.
68
     */
69 21
    public function loadEnv($path = null)
70
    {
71 21
        $envPath = $path == null ? __DIR__.'/../../' : $path;
72 21
        $dotenv = new Dotenv($envPath);
73 21
        $dotenv->load();
74 21
    }
75
}
76