|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Runtime\Swoole; |
| 4 | + |
| 5 | +use Psr\Http\Server\RequestHandlerInterface; |
| 6 | +use Swoole\Http\Request; |
| 7 | +use Swoole\Http\Response; |
| 8 | +use Symfony\Component\Runtime\RunnerInterface; |
| 9 | + |
| 10 | +class RequestHandlerRunner implements RunnerInterface |
| 11 | +{ |
| 12 | + /** |
| 13 | + * @var int |
| 14 | + */ |
| 15 | + private const CHUNK_SIZE = 2097152; // 2MB |
| 16 | + /** |
| 17 | + * @var ServerFactory |
| 18 | + */ |
| 19 | + private $serverFactory; |
| 20 | + /** |
| 21 | + * @var RequestHandlerInterface |
| 22 | + */ |
| 23 | + private $application; |
| 24 | + |
| 25 | + public function __construct(ServerFactory $serverFactory, RequestHandlerInterface $application) |
| 26 | + { |
| 27 | + $this->serverFactory = $serverFactory; |
| 28 | + $this->application = $application; |
| 29 | + } |
| 30 | + |
| 31 | + public function run(): int |
| 32 | + { |
| 33 | + $this->serverFactory->createServer([$this, 'handle'])->start(); |
| 34 | + |
| 35 | + return 0; |
| 36 | + } |
| 37 | + |
| 38 | + public function handle(Request $request, Response $response): void |
| 39 | + { |
| 40 | + $psrRequest = (new \Nyholm\Psr7\ServerRequest( |
| 41 | + $request->getMethod(), |
| 42 | + $request->server['request_uri'] ?? '/', |
| 43 | + array_change_key_case($request->server ?? [], CASE_UPPER), |
| 44 | + $request->rawContent(), |
| 45 | + '1.1', |
| 46 | + $request->server ?? [] |
| 47 | + )) |
| 48 | + ->withQueryParams($request->get ?? []); |
| 49 | + |
| 50 | + $psrResponse = $this->application->handle($psrRequest); |
| 51 | + |
| 52 | + $response->setStatusCode($psrResponse->getStatusCode(), $psrResponse->getReasonPhrase()); |
| 53 | + |
| 54 | + foreach ($psrResponse->getHeaders() as $name => $values) { |
| 55 | + foreach ($values as $value) { |
| 56 | + $response->setHeader($name, $value); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + $body = $psrResponse->getBody(); |
| 61 | + $body->rewind(); |
| 62 | + |
| 63 | + if ($body->isReadable()) { |
| 64 | + if ($body->getSize() <= self::CHUNK_SIZE) { |
| 65 | + if ($contents = $body->getContents()) { |
| 66 | + $response->write($contents); |
| 67 | + } |
| 68 | + } else { |
| 69 | + while (!$body->eof() && ($contents = $body->read(self::CHUNK_SIZE))) { |
| 70 | + $response->write($contents); |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + $response->end(); |
| 75 | + } else { |
| 76 | + $response->end((string) $body); |
| 77 | + } |
| 78 | + |
| 79 | + $body->close(); |
| 80 | + } |
| 81 | +} |
0 commit comments