1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Cozy\Database\Relational; |
6
|
|
|
|
7
|
|
|
use Cozy\Database\Relational\Configuration\ConfigurationInterface; |
8
|
|
|
|
9
|
|
|
class ConnectionPool |
10
|
|
|
{ |
11
|
|
|
/** @var array */ |
12
|
|
|
private $pool = []; |
13
|
|
|
/** @var Connection */ |
14
|
|
|
private $current; |
15
|
|
|
private $selectionOrder = 1; |
16
|
|
|
const SELECTION_RANDOM = 1; |
17
|
|
|
const SELECTION_SEQUENTIAL = 2; |
18
|
|
|
|
19
|
|
|
public function __construct(int $selection_order = self::SELECTION_RANDOM) |
20
|
|
|
{ |
21
|
|
|
$this->selectionOrder = $selection_order; |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
public function addConfiguration(ConfigurationInterface $configuration, string $tag = 'main') |
25
|
|
|
{ |
26
|
|
|
if (!isset($this->pool[$tag])) { |
27
|
|
|
$this->pool[$tag] = []; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
$this->pool[$tag][] = $configuration; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function getConnection(string $tag = 'main'): Connection |
34
|
|
|
{ |
35
|
|
|
if (isset($this->current[$tag]) && $this->current[$tag] instanceof Connection) { |
36
|
|
|
if ($this->current[$tag]->isAlive()) { |
37
|
|
|
return $this->current[$tag]; |
38
|
|
|
} else { |
39
|
|
|
$this->current[$tag] = null; |
40
|
|
|
} |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
if (empty($this->pool[$tag])) { |
44
|
|
|
throw new Exception('There are no available configurations in the connection pool.', 'CZ097'); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
if ($this->selectionOrder == self::SELECTION_RANDOM) { |
48
|
|
|
shuffle($this->pool[$tag]); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
$configuration = array_shift($this->pool[$tag]); |
52
|
|
|
|
53
|
|
|
while ($configuration !== null) { |
54
|
|
|
if ($configuration->isValid()) { |
55
|
|
|
$this->current[$tag] = $configuration->buildConnection(); |
56
|
|
|
break; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
$configuration = array_shift($this->pool[$tag]); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
if (!isset($this->current[$tag])) { |
63
|
|
|
throw new Exception('There are no valid configurations to build a database connection.', 'CZ098'); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
return $this->current[$tag]; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|