|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Runtime\React; |
| 4 | + |
| 5 | +use Psr\Http\Message\ServerRequestInterface; |
| 6 | +use Psr\Http\Server\RequestHandlerInterface; |
| 7 | +use React\EventLoop\Loop; |
| 8 | +use React\EventLoop\LoopInterface; |
| 9 | +use React\Http\HttpServer; |
| 10 | +use React\Socket\SocketServer; |
| 11 | + |
| 12 | +class ServerFactory |
| 13 | +{ |
| 14 | + private const DEFAULT_OPTIONS = [ |
| 15 | + 'host' => '127.0.0.1', |
| 16 | + 'port' => 8080, |
| 17 | + ]; |
| 18 | + private array $options; |
| 19 | + |
| 20 | + public static function getDefaultOptions(): array |
| 21 | + { |
| 22 | + return self::DEFAULT_OPTIONS; |
| 23 | + } |
| 24 | + |
| 25 | + public function __construct(array $options = []) |
| 26 | + { |
| 27 | + $options['host'] = $options['host'] ?? $_SERVER['REACT_HOST'] ?? $_ENV['REACT_HOST'] ?? self::DEFAULT_OPTIONS['host']; |
| 28 | + $options['port'] = $options['port'] ?? $_SERVER['REACT_PORT'] ?? $_ENV['REACT_PORT'] ?? self::DEFAULT_OPTIONS['port']; |
| 29 | + |
| 30 | + $this->options = array_replace_recursive(self::DEFAULT_OPTIONS, $options); |
| 31 | + } |
| 32 | + |
| 33 | + public function createServer(RequestHandlerInterface $requestHandler): LoopInterface |
| 34 | + { |
| 35 | + $loop = Loop::get(); |
| 36 | + $loop->addSignal(SIGTERM, function (int $signal) { |
| 37 | + exit(128 + $signal); |
| 38 | + }); |
| 39 | + $loop->addSignal(SIGKILL, function (int $signal) { |
| 40 | + exit(128 + $signal); |
| 41 | + }); |
| 42 | + $server = new HttpServer($loop, function (ServerRequestInterface $request) use ($requestHandler) { |
| 43 | + return $requestHandler->handle($request); |
| 44 | + }); |
| 45 | + |
| 46 | + $socket = new SocketServer(sprintf('%s:%s', $this->options['host'], $this->options['port']), [], $loop); |
| 47 | + $server->listen($socket); |
| 48 | + |
| 49 | + return $loop; |
| 50 | + } |
| 51 | + |
| 52 | + public function getOptions(): array |
| 53 | + { |
| 54 | + return $this->options; |
| 55 | + } |
| 56 | +} |
0 commit comments