1<?php
2
3namespace Elastica\Connection;
4
5use Elastica\Client;
6use Elastica\Connection;
7use Elastica\Connection\Strategy\StrategyInterface;
8use Elastica\Exception\ClientException;
9use Exception;
10
11/**
12 * Description of ConnectionPool.
13 *
14 * @author chabior
15 */
16class ConnectionPool
17{
18    /**
19     * @var array|Connection[] Connections array
20     */
21    protected $_connections;
22
23    /**
24     * @var StrategyInterface Strategy for connection
25     */
26    protected $_strategy;
27
28    /**
29     * @var callable Function called on connection fail
30     */
31    protected $_callback;
32
33    /**
34     * @param array             $connections
35     * @param StrategyInterface $strategy
36     * @param callback|null     $callback
37     */
38    public function __construct(array $connections, StrategyInterface $strategy, callable $callback = null)
39    {
40        $this->_connections = $connections;
41
42        $this->_strategy = $strategy;
43
44        $this->_callback = $callback;
45    }
46
47    /**
48     * @param Connection $connection
49     *
50     * @return $this
51     */
52    public function addConnection(Connection $connection): self
53    {
54        $this->_connections[] = $connection;
55
56        return $this;
57    }
58
59    /**
60     * @param Connection[] $connections
61     *
62     * @return $this
63     */
64    public function setConnections(array $connections): self
65    {
66        $this->_connections = $connections;
67
68        return $this;
69    }
70
71    /**
72     * @return bool
73     */
74    public function hasConnection(): bool
75    {
76        foreach ($this->_connections as $connection) {
77            if ($connection->isEnabled()) {
78                return true;
79            }
80        }
81
82        return false;
83    }
84
85    /**
86     * @return Connection[]
87     */
88    public function getConnections(): array
89    {
90        return $this->_connections;
91    }
92
93    /**
94     * @throws ClientException
95     *
96     * @return Connection
97     */
98    public function getConnection(): Connection
99    {
100        return $this->_strategy->getConnection($this->getConnections());
101    }
102
103    /**
104     * @param Connection $connection
105     * @param \Exception $e
106     * @param Client     $client
107     */
108    public function onFail(Connection $connection, Exception $e, Client $client)
109    {
110        $connection->setEnabled(false);
111
112        if ($this->_callback) {
113            \call_user_func($this->_callback, $connection, $e, $client);
114        }
115    }
116
117    /**
118     * @return StrategyInterface
119     */
120    public function getStrategy(): StrategyInterface
121    {
122        return $this->_strategy;
123    }
124}
125