1<?php
2
3declare(strict_types = 1);
4
5namespace Elasticsearch\ConnectionPool\Selectors;
6
7use Elasticsearch\Connections\ConnectionInterface;
8
9/**
10 * Class StickyRoundRobinSelector
11 *
12 * @category Elasticsearch
13 * @package  Elasticsearch\ConnectionPool\Selectors\ConnectionPool
14 * @author   Zachary Tong <zach@elastic.co>
15 * @license  http://www.apache.org/licenses/LICENSE-2.0 Apache2
16 * @link     http://elastic.co
17 */
18class StickyRoundRobinSelector implements SelectorInterface
19{
20    /**
21     * @var int
22     */
23    private $current = 0;
24
25    /**
26     * @var int
27     */
28    private $currentCounter = 0;
29
30    /**
31     * Use current connection unless it is dead, otherwise round-robin
32     *
33     * @param ConnectionInterface[] $connections Array of connections to choose from
34     */
35    public function select(array $connections): ConnectionInterface
36    {
37        /**
38 * @var ConnectionInterface[] $connections
39*/
40        if ($connections[$this->current]->isAlive()) {
41            return $connections[$this->current];
42        }
43
44        $this->currentCounter += 1;
45        $this->current = $this->currentCounter % count($connections);
46
47        return $connections[$this->current];
48    }
49}
50