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|null Function called on connection fail 30 */ 31 protected $_callback; 32 33 public function __construct(array $connections, StrategyInterface $strategy, ?callable $callback = null) 34 { 35 $this->_connections = $connections; 36 $this->_strategy = $strategy; 37 $this->_callback = $callback; 38 } 39 40 /** 41 * @return $this 42 */ 43 public function addConnection(Connection $connection): self 44 { 45 $this->_connections[] = $connection; 46 47 return $this; 48 } 49 50 /** 51 * @param Connection[] $connections 52 * 53 * @return $this 54 */ 55 public function setConnections(array $connections): self 56 { 57 $this->_connections = $connections; 58 59 return $this; 60 } 61 62 public function hasConnection(): bool 63 { 64 foreach ($this->_connections as $connection) { 65 if ($connection->isEnabled()) { 66 return true; 67 } 68 } 69 70 return false; 71 } 72 73 /** 74 * @return Connection[] 75 */ 76 public function getConnections(): array 77 { 78 return $this->_connections; 79 } 80 81 /** 82 * @throws ClientException 83 */ 84 public function getConnection(): Connection 85 { 86 return $this->_strategy->getConnection($this->getConnections()); 87 } 88 89 public function onFail(Connection $connection, Exception $e, Client $client): void 90 { 91 $connection->setEnabled(false); 92 93 if ($this->_callback) { 94 ($this->_callback)($connection, $e, $client); 95 } 96 } 97 98 public function getStrategy(): StrategyInterface 99 { 100 return $this->_strategy; 101 } 102} 103