-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathServerFactory.php
More file actions
53 lines (43 loc) · 1.53 KB
/
ServerFactory.php
File metadata and controls
53 lines (43 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
namespace Runtime\React;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use React\EventLoop\Loop;
use React\EventLoop\LoopInterface;
use React\Http\HttpServer;
use React\Socket\SocketServer;
class ServerFactory
{
private const DEFAULT_OPTIONS = [
'host' => '127.0.0.1',
'port' => 8080,
];
private array $options;
public static function getDefaultOptions(): array
{
return self::DEFAULT_OPTIONS;
}
public function __construct(array $options = [])
{
$options['host'] = $options['host'] ?? $_SERVER['REACT_HOST'] ?? $_ENV['REACT_HOST'] ?? self::DEFAULT_OPTIONS['host'];
$options['port'] = $options['port'] ?? $_SERVER['REACT_PORT'] ?? $_ENV['REACT_PORT'] ?? self::DEFAULT_OPTIONS['port'];
$this->options = array_replace_recursive(self::DEFAULT_OPTIONS, $options);
}
public function createServer(RequestHandlerInterface $requestHandler): LoopInterface
{
$loop = Loop::get();
$loop->addSignal(SIGTERM, function (int $signal) {
exit(128 + $signal);
});
$server = new HttpServer($loop, function (ServerRequestInterface $request) use ($requestHandler) {
return $requestHandler->handle($request);
});
$socket = new SocketServer(sprintf('%s:%s', $this->options['host'], $this->options['port']), [], $loop);
$server->listen($socket);
return $loop;
}
public function getOptions(): array
{
return $this->options;
}
}