|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/* |
| 6 | + * This file is part of the Micro framework package. |
| 7 | + * |
| 8 | + * (c) Stanislau Komar <kost@micro-php.net> |
| 9 | + * |
| 10 | + * For the full copyright and license information, please view the LICENSE |
| 11 | + * file that was distributed with this source code. |
| 12 | + */ |
| 13 | + |
| 14 | +namespace Micro\Plugin\Http\Listener; |
| 15 | + |
| 16 | +use Micro\Component\EventEmitter\EventInterface; |
| 17 | +use Micro\Kernel\App\Business\Event\ApplicationReadyEvent; |
| 18 | +use Micro\Kernel\App\Business\Event\ApplicationReadyEventInterface; |
| 19 | +use Micro\Plugin\Http\Facade\HttpFacadeInterface; |
| 20 | +use Nyholm\Psr7\Factory\Psr17Factory; |
| 21 | +use Spiral\RoadRunner; |
| 22 | +use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory; |
| 23 | +use Symfony\Bridge\PsrHttpMessage\Factory\PsrHttpFactory; |
| 24 | + |
| 25 | +final readonly class ApplicationRoadrunnerStartedListener |
| 26 | +{ |
| 27 | + public function __construct( |
| 28 | + private HttpFacadeInterface $httpFacade |
| 29 | + ) { |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * @param ApplicationReadyEvent $event |
| 34 | + * |
| 35 | + * @psalm-suppress MoreSpecificImplementedParamType |
| 36 | + * |
| 37 | + * @throws \JsonException |
| 38 | + */ |
| 39 | + public function on(EventInterface $event): void |
| 40 | + { |
| 41 | + $sysenv = $event->systemEnvironment(); |
| 42 | + if ('cli' !== $sysenv || !getenv('RR_MODE')) { |
| 43 | + return; |
| 44 | + } |
| 45 | + |
| 46 | + $httpFoundationFactory = new HttpFoundationFactory(); |
| 47 | + $psr17Factory = new Psr17Factory(); |
| 48 | + $httpMessageFactory = new PsrHttpFactory($psr17Factory, $psr17Factory, $psr17Factory, $psr17Factory); |
| 49 | + |
| 50 | + $worker = RoadRunner\Worker::create(); |
| 51 | + $worker = new RoadRunner\Http\PSR7Worker($worker, $psr17Factory, $psr17Factory, $psr17Factory); |
| 52 | + while ($request = $worker->waitRequest()) { |
| 53 | + try { |
| 54 | + $appRequest = $httpFoundationFactory->createRequest($request); |
| 55 | + $appResponse = $this->httpFacade->execute($appRequest); |
| 56 | + $worker->respond($httpMessageFactory->createResponse($appResponse)); |
| 57 | + } catch (\Throwable $e) { |
| 58 | + $worker->getWorker()->error((string) $e); |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + public static function supports(EventInterface $event): bool |
| 64 | + { |
| 65 | + return $event instanceof ApplicationReadyEventInterface; |
| 66 | + } |
| 67 | +} |
0 commit comments