1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
|
4
|
|
|
namespace Beanie\Server; |
5
|
|
|
|
6
|
|
|
|
7
|
|
|
use Beanie\Command\CommandInterface; |
8
|
|
|
use Beanie\Exception\InvalidArgumentException; |
9
|
|
|
use Beanie\Tube\TubeAwareInterface; |
10
|
|
|
use Beanie\Tube\TubeStatus; |
11
|
|
|
|
12
|
|
|
class Pool implements TubeAwareInterface |
13
|
|
|
{ |
14
|
|
|
use TubeAwareTrait; |
15
|
|
|
|
16
|
|
|
/** @var Server[] */ |
17
|
|
|
protected $servers = []; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @param Server[] $servers |
21
|
|
|
* @throws InvalidArgumentException |
22
|
|
|
*/ |
23
|
7 |
|
public function __construct(array $servers) |
24
|
|
|
{ |
25
|
7 |
|
if (!count($servers)) { |
26
|
1 |
|
throw new InvalidArgumentException('Pool needs servers'); |
27
|
|
|
} |
28
|
|
|
|
29
|
6 |
|
foreach ($servers as $server) { |
30
|
6 |
|
$this->addServer($server); |
31
|
6 |
|
} |
32
|
|
|
|
33
|
6 |
|
$this->tubeStatus = new TubeStatus(); |
34
|
6 |
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* @param Server $server |
38
|
|
|
* @return $this |
39
|
|
|
*/ |
40
|
6 |
|
protected function addServer(Server $server) |
41
|
|
|
{ |
42
|
6 |
|
$this->servers[(string) $server] = $server; |
43
|
6 |
|
return $this; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @return Server[] |
48
|
|
|
*/ |
49
|
3 |
|
public function getServers() |
50
|
|
|
{ |
51
|
3 |
|
return $this->servers; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @param string $name |
56
|
|
|
* @return Server |
57
|
|
|
* @throws InvalidArgumentException |
58
|
|
|
*/ |
59
|
2 |
|
public function getServer($name) |
60
|
|
|
{ |
61
|
2 |
|
if (!isset($this->servers[$name])) { |
62
|
1 |
|
throw new InvalidArgumentException('Server not found by name: ' . $name); |
63
|
|
|
} |
64
|
|
|
|
65
|
1 |
|
return $this->servers[$name]; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @param CommandInterface $command |
70
|
|
|
* @return \Beanie\Server\ResponseOath |
71
|
|
|
*/ |
72
|
2 |
|
public function dispatchCommand(CommandInterface $command) |
73
|
|
|
{ |
74
|
2 |
|
return $this |
75
|
2 |
|
->getRandomServer() |
76
|
2 |
|
->transformTubeStatusTo($this->tubeStatus, TubeStatus::TRANSFORM_USE) |
77
|
2 |
|
->dispatchCommand($command); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* @return Server |
82
|
|
|
*/ |
83
|
1 |
|
public function getRandomServer() |
84
|
|
|
{ |
85
|
1 |
|
return $this->servers[array_rand($this->servers, 1)]; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|