1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Igni\Storage\Driver; |
4
|
|
|
|
5
|
|
|
use Igni\Storage\Exception\StorageException; |
6
|
|
|
|
7
|
|
|
final class ConnectionManager |
8
|
|
|
{ |
9
|
|
|
private static $defaultConnection; |
10
|
|
|
/** @var Connection[] */ |
11
|
|
|
private static $connections = []; |
12
|
|
|
|
13
|
49 |
|
public static function release(): void |
14
|
|
|
{ |
15
|
49 |
|
foreach (self::$connections as $connection) { |
16
|
48 |
|
$connection->close(); |
17
|
|
|
} |
18
|
|
|
|
19
|
49 |
|
self::$defaultConnection = null; |
20
|
49 |
|
self::$connections = []; |
21
|
49 |
|
} |
22
|
|
|
|
23
|
49 |
|
public static function addConnection(Connection $connection, string $name = 'default'): void |
24
|
|
|
{ |
25
|
49 |
|
if (!self::hasDefaultConnection()) { |
26
|
49 |
|
self::$defaultConnection = $connection; |
27
|
|
|
} |
28
|
|
|
|
29
|
49 |
|
if (self::hasConnection($name)) { |
30
|
|
|
throw StorageException::forAlreadyExistingConnection($name); |
31
|
|
|
} |
32
|
|
|
|
33
|
49 |
|
self::$connections[$name] = $connection; |
34
|
49 |
|
} |
35
|
|
|
|
36
|
49 |
|
public static function hasConnection(string $name): bool |
37
|
|
|
{ |
38
|
49 |
|
return isset(self::$connections[$name]); |
39
|
|
|
} |
40
|
|
|
|
41
|
49 |
|
public static function hasDefaultConnection(): bool |
42
|
|
|
{ |
43
|
49 |
|
return self::$defaultConnection !== null; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public static function getDefaultConnection(): Connection |
47
|
|
|
{ |
48
|
|
|
if (!self::hasDefaultConnection()) { |
49
|
|
|
throw StorageException::forNotRegisteredConnection('default'); |
50
|
|
|
} |
51
|
|
|
return self::$defaultConnection; |
52
|
|
|
} |
53
|
|
|
|
54
|
22 |
|
public static function getConnection(string $name): Connection |
55
|
|
|
{ |
56
|
22 |
|
if (!self::hasConnection($name)) { |
57
|
|
|
throw StorageException::forNotRegisteredConnection($name); |
58
|
|
|
} |
59
|
|
|
|
60
|
22 |
|
return self::$connections[$name]; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|