1<?php
2
3declare(strict_types = 1);
4
5namespace Elasticsearch\ConnectionPool;
6
7use Elasticsearch\Common\Exceptions\InvalidArgumentException;
8use Elasticsearch\ConnectionPool\Selectors\SelectorInterface;
9use Elasticsearch\Connections\ConnectionFactoryInterface;
10use Elasticsearch\Connections\ConnectionInterface;
11
12/**
13 * Class AbstractConnectionPool
14 *
15 * @category Elasticsearch
16 * @package  Elasticsearch\ConnectionPool
17 * @author   Zachary Tong <zach@elastic.co>
18 * @license  http://www.apache.org/licenses/LICENSE-2.0 Apache2
19 * @link     http://elastic.co
20 */
21abstract class AbstractConnectionPool implements ConnectionPoolInterface
22{
23    /**
24     * Array of connections
25     *
26     * @var ConnectionInterface[]
27     */
28    protected $connections;
29
30    /**
31     * Array of initial seed connections
32     *
33     * @var ConnectionInterface[]
34     */
35    protected $seedConnections;
36
37    /**
38     * Selector object, used to select a connection on each request
39     *
40     * @var SelectorInterface
41     */
42    protected $selector;
43
44    /**
45     * @var array
46     */
47    protected $connectionPoolParams;
48
49    /**
50     * @var \Elasticsearch\Connections\ConnectionFactory
51     */
52    protected $connectionFactory;
53
54    /**
55     * Constructor
56     *
57     * @param ConnectionInterface[]      $connections          The Connections to choose from
58     * @param SelectorInterface          $selector             A Selector instance to perform the selection logic for the available connections
59     * @param ConnectionFactoryInterface $factory              ConnectionFactory instance
60     * @param array                      $connectionPoolParams
61     */
62    public function __construct(array $connections, SelectorInterface $selector, ConnectionFactoryInterface $factory, array $connectionPoolParams)
63    {
64        $paramList = array('connections', 'selector', 'connectionPoolParams');
65        foreach ($paramList as $param) {
66            if (isset($$param) === false) {
67                throw new InvalidArgumentException('`' . $param . '` parameter must not be null');
68            }
69        }
70
71        if (isset($connectionPoolParams['randomizeHosts']) === true
72            && $connectionPoolParams['randomizeHosts'] === true
73        ) {
74            shuffle($connections);
75        }
76
77        $this->connections          = $connections;
78        $this->seedConnections      = $connections;
79        $this->selector             = $selector;
80        $this->connectionPoolParams = $connectionPoolParams;
81        $this->connectionFactory    = $factory;
82    }
83
84    abstract public function nextConnection(bool $force = false): ConnectionInterface;
85
86    abstract public function scheduleCheck(): void;
87}
88