|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Manyou\WorkermanSymfonyRuntime; |
| 6 | + |
| 7 | +use Chubbyphp\WorkermanRequestHandler\OnMessageInterface; |
| 8 | +use Chubbyphp\WorkermanRequestHandler\PsrRequestFactoryInterface; |
| 9 | +use Psr\Http\Server\RequestHandlerInterface; |
| 10 | +use Workerman\Connection\TcpConnection as WorkermanTcpConnection; |
| 11 | +use Workerman\Protocols\Http\Request as WorkermanRequest; |
| 12 | +use Workerman\Protocols\Http\Response as WorkermanResponse; |
| 13 | + |
| 14 | +use function explode; |
| 15 | +use function in_array; |
| 16 | +use function strtolower; |
| 17 | + |
| 18 | +final class OnMessage implements OnMessageInterface |
| 19 | +{ |
| 20 | + public function __construct( |
| 21 | + private PsrRequestFactoryInterface $psrRequestFactory, |
| 22 | + private RequestHandlerInterface $requestHander, |
| 23 | + ) { |
| 24 | + } |
| 25 | + |
| 26 | + public function __invoke(WorkermanTcpConnection $workermanTcpConnection, WorkermanRequest $workermanRequest): void |
| 27 | + { |
| 28 | + $response = $this->requestHander->handle( |
| 29 | + $this->psrRequestFactory->create($workermanTcpConnection, $workermanRequest), |
| 30 | + ); |
| 31 | + |
| 32 | + $workermanTcpConnection->send( |
| 33 | + (new WorkermanResponse()) |
| 34 | + ->withStatus($response->getStatusCode(), $response->getReasonPhrase()) |
| 35 | + ->withHeaders($response->getHeaders()) |
| 36 | + ->withBody((string) $response->getBody()), |
| 37 | + ); |
| 38 | + |
| 39 | + $keepAlive = in_array('keep-alive', explode(',', strtolower($workermanRequest->header('connection', 'close'))), true); |
| 40 | + if (! $keepAlive) { |
| 41 | + $workermanTcpConnection->close(); |
| 42 | + } |
| 43 | + } |
| 44 | +} |
0 commit comments