Completed
Pull Request — master (#70)
by
unknown
02:33
created

Database::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Zewa;
4
5
/**
6
 * Abstract class for model extension
7
 *
8
 * @author Zechariah Walden<zech @ zewadesign.com>
9
 */
10
class Database
11
{
12
    private $configuration;
13
14
    /**
15
     * Database object reference
16
     *
17
     * @access private
18
     * @var    object
19
     */
20
    protected static $dbh = [];
21
22 18
    public function __construct($name = 'default')
23
    {
24 18
        $app = App::getInstance();
25 18
        $this->configuration = $app->getConfiguration('database');
26
27
        //@TODO: lazyload connection
28 18
        $this->establishConnection($name);
29 18
    }
30
31 18
    public function establishConnection($name = 'default')
32
    {
33 18
        if ($this->configuration !== false) {
34
            if (! empty($this->configuration->$name)) {
35
                $dbConfig = $this->configuration->$name;
36
                self::$dbh[$name] = new \PDO($dbConfig->dsn, $dbConfig->user, $dbConfig->pass);
37
                self::$dbh[$name]->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
38
            } else {
39
                throw new \PDOException(
40
                    'Please specify a valid database configuration, or provide a default configuration.'
41
                );
42
            }
43
        }
44 18
    }
45
46
    public function fetchConnection($name = 'default')
47
    {
48
        if (!empty(self::$dbh[$name])) {
49
            return self::$dbh[$name];
50
        } elseif (!empty($this->configuration->$name)) {
51
            $this->establishConnection($name);
52
            return self::$dbh[$name];
53
        } else {
54
            throw new Exception\LookupException('Cannot find a valid database config for: ' . $name);
55
        }
56
    }
57
}
58