|
14 | 14 | class Server extends Adapter |
15 | 15 | { |
16 | 16 | protected SwooleServer $server; |
| 17 | + protected const string REQUEST_CONTAINER_CONTEXT_KEY = '__utopia_http_request_container'; |
| 18 | + protected Container $container; |
17 | 19 |
|
18 | | - public function __construct(string $host, ?string $port = null, array $settings = []) |
| 20 | + public function __construct(string $host, ?string $port = null, array $settings = [], Container $container) |
19 | 21 | { |
20 | 22 | $this->server = new SwooleServer($host, $port); |
21 | 23 | $this->server->set(\array_merge($settings, [ |
22 | 24 | 'enable_coroutine' => true, |
23 | 25 | 'http_parse_cookie' => false, |
24 | 26 | ])); |
| 27 | + $this->container = $container; |
25 | 28 | } |
26 | 29 |
|
27 | 30 | public function onRequest(callable $callback) |
28 | 31 | { |
29 | 32 | $this->server->handle('/', function (SwooleRequest $request, SwooleResponse $response) use ($callback) { |
30 | | - $context = \strval(Coroutine::getCid()); |
31 | | - $requestAdapter = new Request($request); |
32 | | - $responseAdapter = new Response($response); |
33 | | - $resources = [ |
34 | | - 'swooleRequest' => $request, |
35 | | - 'swooleResponse' => $response, |
36 | | - ]; |
37 | | - $configureRequestScope = function (Container $requestContainer) use ($request, $response) { |
38 | | - $requestContainer |
39 | | - ->set('swooleRequest', fn () => $request) |
40 | | - ->set('swooleResponse', fn () => $response); |
41 | | - }; |
42 | | - |
43 | | - call_user_func($callback, $requestAdapter, $responseAdapter, $context, $resources, $configureRequestScope); |
| 33 | + Coroutine::getContext()[self::REQUEST_CONTAINER_CONTEXT_KEY] = new Container($this->container); |
| 34 | + |
| 35 | + $utopiaRequest = new Request($request); |
| 36 | + $utopiaResponse = new Response($response); |
| 37 | + |
| 38 | + \call_user_func($callback, $utopiaRequest, $utopiaResponse); |
44 | 39 | }); |
45 | 40 | } |
46 | 41 |
|
| 42 | + public function getContainer(): Container |
| 43 | + { |
| 44 | + return Coroutine::getContext()[self::REQUEST_CONTAINER_CONTEXT_KEY] ?? $this->container; |
| 45 | + } |
| 46 | + |
47 | 47 | public function onStart(callable $callback) |
48 | 48 | { |
49 | | - call_user_func($callback, $this); |
| 49 | + |
| 50 | + \call_user_func($callback, $this); |
50 | 51 | } |
51 | 52 |
|
52 | 53 | public function start() |
|
0 commit comments