-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathServer.php
More file actions
73 lines (59 loc) · 2.07 KB
/
Server.php
File metadata and controls
73 lines (59 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php
namespace Utopia\Http\Adapter\SwooleCoroutine;
use Swoole\Coroutine;
use Utopia\Http\Adapter;
use Utopia\DI\Container;
use Swoole\Coroutine\Http\Server as SwooleServer;
use Swoole\Http\Request as SwooleRequest;
use Swoole\Http\Response as SwooleResponse;
class Server extends Adapter
{
protected const REQUEST_CONTAINER_CONTEXT_KEY = '__utopia_http_request_container';
protected SwooleServer $server;
protected Container $container;
/** @var callable|null */
protected $onStartCallback = null;
public function __construct(
string $host,
?string $port = null,
array $settings = [],
?Container $container = null
) {
$this->server = new SwooleServer($host, $port, false, true);
$this->server->set($settings);
$this->container = $container ?? new Container();
}
public function onRequest(callable $callback)
{
$this->server->handle('/', function (SwooleRequest $request, SwooleResponse $response) use ($callback) {
$requestContainer = new Container($this->container);
$requestContainer->set('swooleRequest', fn () => $request);
$requestContainer->set('swooleResponse', fn () => $response);
Coroutine::getContext()[self::REQUEST_CONTAINER_CONTEXT_KEY] = $requestContainer;
try {
\call_user_func($callback, new Request($request), new Response($response));
} finally {
unset(Coroutine::getContext()[self::REQUEST_CONTAINER_CONTEXT_KEY]);
}
});
}
public function getContainer(): Container
{
return Coroutine::getContext()[self::REQUEST_CONTAINER_CONTEXT_KEY] ?? $this->container;
}
public function getServer(): SwooleServer
{
return $this->server;
}
public function onStart(callable $callback)
{
$this->onStartCallback = $callback;
}
public function start()
{
if ($this->onStartCallback) {
\call_user_func($this->onStartCallback, $this);
}
$this->server->start();
}
}