Completed
Push — master ( 16ac69...c5173b )
by Jay
04:00
created

Manager::set()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 2
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
namespace FMUP\Db;
3
4
use FMUP\Config;
5
use FMUP\Logger;
6
use FMUP\Db;
7
8
/**
9
 * Class Db
10
 * @package FMUP\Helper
11
 */
12
class Manager implements Logger\LoggerInterface
13
{
14
    use Logger\LoggerTrait;
15
    use Config\RequiredTrait;
16
17
    const DEFAULT_NAME = 'DEFAULT_NAME';
18
    private static $instance = null;
19
    private $instances = array();
20
21 1
    private function __construct()
22
    {
23 1
    }
24
25
    /**
26
     * @codeCoverageIgnore
27
     */
28
    private function __clone()
29
    {
30
    }
31
32
    /**
33
     * @param string $name
34
     * @return Db
35
     * @throws \InvalidArgumentException
36
     * @throws \OutOfRangeException
37
     */
38 5
    public function get($name = self::DEFAULT_NAME)
39
    {
40 5
        if (empty($name)) {
41 1
            throw new \InvalidArgumentException('Name must be set');
42
        }
43 4
        $name = (string)$name;
44 4
        if (!isset($this->instances[$name])) {
45 3
            if ($name == self::DEFAULT_NAME) {
46 1
                $params = $this->getConfig()->get('parametres_connexion_db');
47 1
            } else {
48 2
                $dbSettings = $this->getConfig()->get('db');
49 2
                if (isset($dbSettings[$name])) {
50 1
                    $params = $dbSettings[$name];
51 1
                } else {
52 1
                    throw new \OutOfRangeException('Trying to access a database name ' . $name . ' that not exists');
53
                }
54
            }
55 2
            $instance = new Db((array)$params);
56 2
            if ($this->hasLogger()) {
57 1
                $instance->setLogger($this->getLogger());
58 1
            }
59 2
            $this->instances[$name] = $instance;
60 2
        }
61
62 3
        return $this->instances[$name];
63
    }
64
65
    /**
66
     * Close or change a connection by its name
67
     * @param string $name
68
     * @param Db|null $db
69
     * @return $this
70
     */
71 1
    public function set($name = self::DEFAULT_NAME, Db $db = null)
72
    {
73 1
        $this->instances[(string) $name] = $db;
74 1
        return $this;
75
    }
76
77
    /**
78
     * @return $this
79
     */
80 3
    final public static function getInstance()
81
    {
82 3
        if (!self::$instance) {
83 1
            $class = get_called_class();
84 1
            self::$instance = new $class();
85 1
        }
86 3
        return self::$instance;
87
    }
88
}
89