Pool::__construct()   A
last analyzed

Complexity

Conditions 6
Paths 5

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 10
c 1
b 0
f 1
dl 0
loc 18
rs 9.2222
cc 6
nc 5
nop 1
1
<?php
2
3
/**
4
 * Platine Database
5
 *
6
 * Platine Database is the abstraction layer using PDO with support of query and schema builder
7
 *
8
 * This content is released under the MIT License (MIT)
9
 *
10
 * Copyright (c) 2020 Platine Database
11
 *
12
 * Permission is hereby granted, free of charge, to any person obtaining a copy
13
 * of this software and associated documentation files (the "Software"), to deal
14
 * in the Software without restriction, including without limitation the rights
15
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
 * copies of the Software, and to permit persons to whom the Software is
17
 * furnished to do so, subject to the following conditions:
18
 *
19
 * The above copyright notice and this permission notice shall be included in all
20
 * copies or substantial portions of the Software.
21
 *
22
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
 * SOFTWARE.
29
 */
30
31
/**
32
 *  @file Pool.php
33
 *
34
 *  The Database Connection pool class
35
 *
36
 *  @package    Platine\Database
37
 *  @author Platine Developers Team
38
 *  @copyright  Copyright (c) 2020
39
 *  @license    http://opensource.org/licenses/MIT  MIT License
40
 *  @link   https://www.platine-php.com
41
 *  @version 1.0.0
42
 *  @filesource
43
 */
44
declare(strict_types=1);
45
46
namespace Platine\Database;
47
48
use Platine\Database\Exception\ConnectionAlreadyExistsException;
49
use Platine\Database\Exception\ConnectionNotFoundException;
50
use Platine\Logger\Logger;
51
52
/**
53
 * @class Pool
54
 * @package Platine\Database
55
 */
56
class Pool
57
{
58
    /**
59
     * The default connection name
60
     * @var string
61
     */
62
    protected string $default = 'default';
63
64
    /**
65
     * The list of connections
66
     * @var array<string, array<string, mixed>>
67
     */
68
    protected array $connections = [];
69
70
    /**
71
     * Class constructor
72
     * @param array<string, mixed> $config
73
     */
74
    public function __construct(array $config = [])
75
    {
76
        if (count($config) > 0) {
77
            if (
78
                is_array($config['connections']) &&
79
                count($config['connections']) > 0
80
            ) {
81
                 /** @var array<string, array<string, mixed>> $connections */
82
                $connections = $config['connections'];
83
84
                foreach ($connections as $name => $connection) {
85
                    $connection['name'] = $name;
86
                    $this->addConnection($connection);
87
                }
88
            }
89
90
            if (isset($config['default'])) {
91
                $this->setDefault($config['default']);
92
            }
93
        }
94
    }
95
96
    /**
97
     * Add new connection to the pool
98
     * @param array<string, mixed> $config
99
     * @return void
100
     * @throws ConnectionAlreadyExistsException
101
     */
102
    public function addConnection(array $config): void
103
    {
104
        /** @var Configuration $cfg */
105
        $cfg = new Configuration($config);
106
107
        $name = $cfg->getName();
108
109
        if ($this->has($name)) {
110
            throw new ConnectionAlreadyExistsException(
111
                sprintf('The connection [%s] already exists', $name)
112
            );
113
        }
114
115
        $actives = count($this->connections);
116
117
        $this->storeConnectionInfos($cfg);
118
119
        if ($actives === 0) {
120
            $this->default = $name;
121
        }
122
    }
123
124
    /**
125
     * Check whether the connection exists
126
     * @param string $name
127
     * @return bool
128
     */
129
    public function has(string $name): bool
130
    {
131
        return isset($this->connections[$name]);
132
    }
133
134
    /**
135
     * Get the connection instance for the given name
136
     * if $name is null the default will be returned
137
     * @param string|null $name
138
     * @param Logger|null $logger
139
     * @return Connection
140
     * @throws ConnectionNotFoundException
141
     */
142
    public function getConnection(
143
        ?string $name = null,
144
        ?Logger $logger = null
145
    ): Connection {
146
        if ($name === null) {
147
            $name = $this->default;
148
        }
149
150
        $this->checkConnectionName($name);
151
152
        $connection = $this->createConnection($name, $logger);
153
154
        return $connection;
155
    }
156
157
    /**
158
     * Set the default connection to use
159
     * @param string $name
160
     * @return void
161
     * @throws ConnectionNotFoundException
162
     */
163
    public function setDefault(string $name): void
164
    {
165
        $this->checkConnectionName($name);
166
167
        $this->default = $name;
168
    }
169
170
171
    /**
172
     * Remove the given connection
173
     * @param string $name
174
     * @return void
175
     */
176
    public function remove(string $name): void
177
    {
178
        unset($this->connections[$name]);
179
    }
180
181
    /**
182
     *
183
     * @param string $name
184
     * @return void
185
     * @throws ConnectionNotFoundException
186
     */
187
    protected function checkConnectionName(string $name): void
188
    {
189
        if ($this->has($name) === false) {
190
            throw new ConnectionNotFoundException(
191
                sprintf('The connection [%s] does not exist', $name)
192
            );
193
        }
194
    }
195
196
    /**
197
     * Store the connection information
198
     * @param Configuration $config
199
     * @return void
200
     */
201
    protected function storeConnectionInfos(Configuration $config): void
202
    {
203
        $name = $config->getName();
204
205
        $this->connections[$name] = [
206
            'config' => $config,
207
            'instance' => null
208
        ];
209
    }
210
211
    /**
212
     * Create the connection
213
     * @param string $name
214
     * @param Logger|null $logger
215
     * @return Connection
216
     */
217
    protected function createConnection(string $name, ?Logger $logger = null): Connection
218
    {
219
        /** @var array<string, mixed>|null $infos */
220
        $infos = $this->connections[$name];
221
222
        if (is_array($infos)) {
223
            if (is_null($infos['instance'])) {
224
                $this->connections[$name]['instance'] = new Connection(
225
                    $infos['config'],
226
                    $logger
227
                );
228
            }
229
        }
230
231
        return $this->connections[$name]['instance'];
232
    }
233
}
234