ConnectionPool.php 2.6 KB

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