-
Notifications
You must be signed in to change notification settings - Fork 1
/
bootstrap.php
61 lines (54 loc) · 1.85 KB
/
bootstrap.php
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
<?php
declare(strict_types=1);
use BEAR\Resource\ResourceObject;
use BEAR\Swoole\App;
use BEAR\Swoole\SuperGlobals;
use BEAR\Swoole\SwooleModule;
use Ray\Di\Injector;
use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\Http\Server;
use BEAR\AppMeta\Meta;
use BEAR\Package\Module;
if (! class_exists(Server::class)) {
throw new \RuntimeException('Swoole is not installed. See https://github.com/swoole/swoole-src/wiki/Installing');
}
return function (
string $context,
string $name,
string $ip,
int $port,
int $mode = SWOOLE_PROCESS,
int $sockType = SWOOLE_SOCK_TCP,
array $settings = ['worker_num' => 4]
) : int {
$http = new Server($ip, $port, $mode, $sockType);
$http->set($settings);
$http->on('start', function () use ($ip, $port) {
echo "Swoole http server is started at http://{$ip}:{$port}" . PHP_EOL;
return 1;
});
$appModule = (new Module)(new Meta($name, $context), $context);
$appModule->override(new SwooleModule());
$injector = new Injector(new SwooleModule($appModule));
$app = $injector->getInstance(App::class);
$superGlobals = new SuperGlobals;
$http->on('request', function (Request $request, Response $response) use ($app, $superGlobals) {
if ($app->httpCache->isNotModified($request->header)) {
$app->httpCache->transfer($response);
return;
}
$superGlobals($request);
$match = $app->router->match($GLOBALS, $_SERVER);
try {
/* @var ResourceObject $ro */
$ro = $app->resource->{$match->method}->uri($match->path)($match->query);
$app->responder->setResponse($response);
$ro->transfer($app->responder, []);
} catch (\Exception $e) {
$app->error->transfer($e, $request, $response);
}
});
$http->start();
return 0;
};