-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.php
More file actions
93 lines (69 loc) · 2.64 KB
/
server.php
File metadata and controls
93 lines (69 loc) · 2.64 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php
declare(strict_types=1);
require __DIR__ . '/../vendor/autoload.php';
use PivotPHP\Core\Core\Application;
use PivotPHP\Core\Http\Response;
use PivotPHP\Core\Routing\Router;
use PivotPHP\ReactPHP\Providers\ReactPHPServiceProvider;
use PivotPHP\ReactPHP\Server\ReactServer;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
$app = new Application(__DIR__);
$app->register(ReactPHPServiceProvider::class);
$router = $app->make(Router::class);
$router->get('/', function (): ResponseInterface {
return Response::json([
'message' => 'Welcome to PivotPHP with ReactPHP!',
'timestamp' => time(),
'memory' => memory_get_usage(true),
]);
});
$router->get('/hello/{name}', function (ServerRequestInterface $request, array $args): ResponseInterface {
return Response::json([
'message' => sprintf('Hello, %s!', $args['name']),
'method' => $request->getMethod(),
'headers' => $request->getHeaders(),
]);
});
$router->post('/echo', function (ServerRequestInterface $request): ResponseInterface {
$body = json_decode((string) $request->getBody(), true);
return Response::json([
'received' => $body,
'timestamp' => microtime(true),
]);
});
$router->get('/stream', function (): ResponseInterface {
$data = '';
for ($i = 0; $i < 10; $i++) {
$data .= sprintf("Event %d: %s\n", $i, date('Y-m-d H:i:s'));
}
return Response::create($data)
->withHeader('Content-Type', 'text/plain')
->withHeader('X-Powered-By', 'PivotPHP/ReactPHP');
});
$router->get('/benchmark', function (): ResponseInterface {
$start = microtime(true);
$iterations = 10000;
for ($i = 0; $i < $iterations; $i++) {
$hash = hash('sha256', (string) $i);
}
$duration = microtime(true) - $start;
return Response::json([
'iterations' => $iterations,
'duration_ms' => round($duration * 1000, 2),
'ops_per_second' => round($iterations / $duration),
]);
});
$app->use(function (ServerRequestInterface $request, ResponseInterface $response, callable $next): ResponseInterface {
$start = microtime(true);
$response = $next($request, $response);
$duration = round((microtime(true) - $start) * 1000, 2);
return $response
->withHeader('X-Response-Time', $duration . 'ms')
->withHeader('X-Server', 'PivotPHP/ReactPHP');
});
$server = $app->make(ReactServer::class);
$address = $_SERVER['argv'][1] ?? '0.0.0.0:8080';
echo "Starting PivotPHP ReactPHP server on http://{$address}\n";
echo "Press Ctrl+C to stop the server\n\n";
$server->listen($address);