-
Notifications
You must be signed in to change notification settings - Fork 3
/
runner_test.php
97 lines (74 loc) · 2.08 KB
/
runner_test.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
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
94
95
96
<?php
require 'runner.php';
class Request extends stdClass{};
class Response extends stdClass{};
interface Middleware
{
/**
* Invokable
*
* @param Request $request
* @param Response $response
* @param Callable $next
*/
public function __invoke(Request $request, Response $response, Callable $next);
}
class Route implements Middleware{
public function __invoke(Request $request, Response $response, Callable $next)
{
switch ($request->path) {
case '/':
return new class extends Response {
public function __toString() {
return 'Welcome homepage';
}
};
break;
case '/hello':
return new class extends Response {
public function __toString() {
return 'Welcome User';
}
};
break;
case '/json':
sleep(2);
return new class extends Response {
public function __toString() {
return 'json response';
}
};
break;
default:
throw new Exception("route not found");
break;
}
return $next($request, $response);
}
}
class Cache implements Middleware{
private $file = 'app.cache';
public function __invoke(Request $request, Response $response, Callable $next)
{
$cachedReponse = file_get_contents($this->file);
$cachedReponse = unserialize($cachedReponse);
if (!$cachedReponse) {
$cachedReponse = $next($request, $response);
$cache = serialize($response);
file_put_contents($this->file, $cache);
}
return $cachedReponse;
}
}
set_exception_handler(function($exception) {
echo $exception->getMessage();
});
$middlewares = [
new Cache(),
new Route()
];
$runner = new Runner($middlewares);
$request = new Request();
$request->path = $_SERVER['PATH_INFO'];
$response = $runner($request, new Response());
echo $response;