1 | <?php |
||
20 | final class FakeServerBuilder |
||
21 | { |
||
22 | private $handler; |
||
23 | private $uri = 'tcp://0.0.0.0:8000'; |
||
24 | private $ttl = 5; |
||
25 | private $logFile; |
||
26 | |||
27 | public function __construct(Handler $handler) |
||
28 | { |
||
29 | $this->handler = $handler; |
||
30 | $this->logFile = sys_get_temp_dir().'/tarantool_php_client_fake_server.log'; |
||
31 | } |
||
32 | |||
33 | public function setUri(string $uri) : self |
||
34 | { |
||
35 | $this->uri = $uri; |
||
36 | |||
37 | return $this; |
||
38 | } |
||
39 | |||
40 | public function setTtl(int $ttl) : self |
||
41 | { |
||
42 | $this->ttl = $ttl; |
||
43 | |||
44 | return $this; |
||
45 | } |
||
46 | |||
47 | public function setLogFile(string $logFile) : self |
||
48 | { |
||
49 | $this->logFile = $logFile; |
||
50 | |||
51 | return $this; |
||
52 | } |
||
53 | |||
54 | public function getCommand() : string |
||
55 | { |
||
56 | return sprintf( |
||
57 | 'php %s/fake_server.php \ |
||
58 | --handler=%s \ |
||
59 | --uri=%s \ |
||
60 | --ttl=%d \ |
||
61 | >> %s 2>&1 &', |
||
62 | __DIR__, |
||
63 | escapeshellarg(base64_encode(serialize($this->handler))), |
||
64 | escapeshellarg($this->uri), |
||
65 | $this->ttl, |
||
66 | escapeshellarg($this->logFile) |
||
67 | ); |
||
68 | } |
||
69 | |||
70 | public function start() : void |
||
71 | { |
||
72 | exec($this->getCommand(), $output, $result); |
||
73 | if (0 !== $result) { |
||
74 | throw new \RuntimeException("Unable to start fake server ($this->uri)"); |
||
75 | } |
||
76 | |||
77 | $stopTime = time() + 5; |
||
78 | while (time() < $stopTime) { |
||
79 | if ($stream = @stream_socket_client($this->uri)) { |
||
80 | fclose($stream); |
||
81 | |||
82 | return; |
||
83 | } |
||
84 | usleep(100); |
||
85 | } |
||
86 | |||
87 | throw new \RuntimeException("Unable to connect to fake server ($this->uri)"); |
||
88 | } |
||
89 | |||
90 | public static function create(Handler ...$handlers) : self |
||
91 | { |
||
92 | if (!$handlers) { |
||
93 | return new self(new NoopHandler()); |
||
94 | } |
||
95 | |||
96 | return count($handlers) > 1 |
||
97 | ? new self(new ChainHandler($handlers)) |
||
98 | : new self($handlers[0]); |
||
99 | } |
||
100 | } |
||
101 |