DatabasePool::getConnection()   D
last analyzed

Complexity

Conditions 9
Paths 3

Size

Total Lines 25
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 9

Importance

Changes 0
Metric Value
cc 9
eloc 17
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 25
ccs 19
cts 19
cp 1
crap 9
rs 4.909
1
<?php
2
/**
3
 * @author    jan huang <[email protected]>
4
 * @copyright 2016
5
 *
6
 * @see      https://www.github.com/janhuang
7
 * @see      https://fastdlabs.com
8
 */
9
10
namespace FastD\Pool;
11
12
use FastD\Model\Database;
13
14
/**
15
 * Class DatabasePool.
16
 */
17
class DatabasePool implements PoolInterface
18
{
19
    /**
20
     * @var Database[]
21
     */
22
    protected $connections = [];
23
24
    /**
25
     * @var array
26
     */
27
    protected $config;
28
29
    /**
30
     * Database constructor.
31
     *
32
     * @param array $config
33
     */
34 35
    public function __construct(array $config)
35
    {
36 35
        $this->config = $config;
37 35
    }
38
39
    /**
40
     * @param $key
41
     *
42
     * @return Database
43
     */
44 35
    public function getConnection($key)
45
    {
46 35
        if (!isset($this->connections[$key])) {
47 35
            if (!isset($this->config[$key])) {
48 1
                throw new \LogicException(sprintf('No set %s database', $key));
49
            }
50 34
            $config = $this->config[$key];
51 34
            $this->connections[$key] = new Database(
52
                [
53 34
                    'database_type' => isset($config['adapter']) ? $config['adapter'] : 'mysql',
54 34
                    'database_name' => $config['name'],
55 34
                    'server' => $config['host'],
56 34
                    'username' => $config['user'],
57 34
                    'password' => $config['pass'],
58 34
                    'charset' => isset($config['charset']) ? $config['charset'] : 'utf8',
59 34
                    'port' => isset($config['port']) ? $config['port'] : 3306,
60 34
                    'prefix' => isset($config['prefix']) ? $config['prefix'] : '',
61 34
                    'option' => isset($config['option']) ? $config['option'] : [],
62 34
                    'command' => isset($config['command']) ? $config['command'] : [],
63
                ]
64 34
            );
65 34
        }
66
67 34
        return $this->connections[$key];
68
    }
69
70
    /**
71
     * {@inheritdoc}
72
     */
73 1
    public function initPool()
74
    {
75 1
        foreach ($this->config as $name => $config) {
76 1
            $this->getConnection($name);
77 1
        }
78 1
    }
79
}
80