Completed
Pull Request — 2.11.x (#2448)
by
unknown
12:14
created

HighAvailabilityConnector   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Test Coverage

Coverage 75%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 17
c 1
b 0
f 0
dl 0
loc 68
rs 10
ccs 12
cts 16
cp 0.75

6 Methods

Rating   Name   Duplication   Size   Complexity  
connectToSlave() 0 31 ?
A connectToMaster() 0 3 1
A connectTo() 0 5 2
A hp$0 ➔ connectToSlave() 0 31 3
A hp$0 ➔ getErrorCode() 0 3 1
A hp$0 ➔ getSQLState() 0 3 1
1
<?php
2
3
namespace Doctrine\DBAL\Connections\Connector;
4
5
use Doctrine\DBAL\Driver;
6
use Doctrine\DBAL\Driver\DriverException;
7
use Doctrine\DBAL\Exception\ConnectionException;
8
use Exception;
9
use function array_pop;
10
use function shuffle;
11
12
/**
13
 * HighAvailabilityConnector is connection to the first random slave connection that is available
14
 */
15
class HighAvailabilityConnector extends AbstractMasterSlaveConnector implements Connector
16
{
17
    public const STRATEGY = 'high_availability';
18
19
    /**
20
     * Connects to a specific connection.
21
     *
22
     * @param string $connectionName
23
     *
24
     * @return Driver\Connection
25
     *
26
     * @throws ConnectionException
27
     */
28 96
    public function connectTo($connectionName)
29
    {
30 96
        return $connectionName === 'master' ?
31 96
            $this->connectToMaster() :
32 96
            $this->connectToSlave();
33
    }
34
35
    /**
36
     * Connets to a master
37
     *
38
     * @return Driver\Connection
39
     */
40 96
    private function connectToMaster()
41
    {
42 96
        return $this->connectWithParams($this->_params['master']);
43
    }
44
45
    /**
46
     * Connets to a random slave and tries others until if found a server that is alive
47
     *
48
     * @return Driver\Connection
49
     *
50
     * @throws ConnectionException
51
     */
52 96
    private function connectToSlave()
53
    {
54 96
        $params = $this->_params;
55
56 96
        shuffle($params['slaves']);
57
58 96
        while ($config = array_pop($params['slaves'])) {
59
            try {
60 96
                return $this->connectWithParams($config);
61 48
            } catch (ConnectionException $e) {
62
                // try next one
63
            }
64
        }
65
66
        $previous = new /** @psalm-immutable */ class() extends Exception implements DriverException {
67
            public function getErrorCode()
68
            {
69
                return null;
70
            }
71
72
            public function getSQLState()
73
            {
74
                return null;
75
            }
76
        };
77
78
        if (isset($e) && $e->getPrevious() instanceof DriverException) {
79
            $previous = $e->getPrevious();
80
        }
81
82
        throw new ConnectionException('No slaves are available', $previous);
83
    }
84
}
85