1 | <?php |
||
2 | |||
3 | namespace Tsukasa\QueryBuilder; |
||
4 | |||
5 | use Doctrine\DBAL\DriverManager; |
||
6 | |||
7 | /** |
||
8 | * Class ConnectionManager |
||
9 | * @package Tsukasa\QueryBuilder |
||
10 | */ |
||
11 | class ConnectionManager |
||
12 | { |
||
13 | /** |
||
14 | * @var string |
||
15 | */ |
||
16 | protected $defaultConnection = 'default'; |
||
17 | |||
18 | /** |
||
19 | * @var array|\Doctrine\DBAL\Connection[] |
||
20 | */ |
||
21 | protected $connections = []; |
||
22 | protected $configuration; |
||
23 | protected $eventManager; |
||
24 | |||
25 | /** |
||
26 | * ConnectionManager constructor. |
||
27 | * @param array $config |
||
28 | */ |
||
29 | public function __construct(array $config = []) |
||
30 | { |
||
31 | $this->configure($config); |
||
32 | } |
||
33 | |||
34 | /** |
||
35 | * @param array $connections |
||
36 | * @throws \Doctrine\DBAL\DBALException |
||
37 | */ |
||
38 | public function setConnections(array $connections) |
||
39 | { |
||
40 | foreach ($connections as $name => $config) { |
||
41 | $this->connections[$name] = DriverManager::getConnection($config, $this->configuration, $this->eventManager); |
||
42 | } |
||
43 | } |
||
44 | |||
45 | /** |
||
46 | * @param array $config |
||
47 | */ |
||
48 | protected function configure(array $config) |
||
49 | { |
||
50 | foreach ($config as $key => $value) { |
||
51 | if (method_exists($this, 'set' . ucfirst($key))) { |
||
52 | $this->{'set' . ucfirst($key)}($value); |
||
53 | } |
||
54 | else { |
||
55 | $this->{$key} = $value; |
||
56 | } |
||
57 | } |
||
58 | } |
||
59 | |||
60 | /** |
||
61 | * @param string $name |
||
62 | * @return $this |
||
63 | */ |
||
64 | public function setDefaultConnection($name) |
||
65 | { |
||
66 | $this->defaultConnection = $name; |
||
67 | return $this; |
||
68 | } |
||
69 | |||
70 | /** |
||
71 | * @param null $name |
||
0 ignored issues
–
show
Documentation
Bug
introduced
by
![]() |
|||
72 | * @return \Doctrine\DBAL\Connection|null |
||
73 | */ |
||
74 | public function getConnection($name = null) |
||
75 | { |
||
76 | if (empty($name)) { |
||
77 | $name = $this->defaultConnection; |
||
78 | } |
||
79 | return $this->connections[$name]; |
||
80 | } |
||
81 | } |