|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Germania\Middleware; |
|
4
|
|
|
|
|
5
|
|
|
use Psr\Log\LoggerInterface; |
|
6
|
|
|
use Psr\Http\Message\RequestInterface; |
|
7
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
8
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
9
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
|
10
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
|
11
|
|
|
|
|
12
|
|
|
class ScriptRuntimeMiddleware implements MiddlewareInterface |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* @var LoggerInterface |
|
16
|
|
|
*/ |
|
17
|
|
|
public $log; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* @var float |
|
21
|
|
|
*/ |
|
22
|
|
|
public $start_time; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
5 |
|
* @param LoggerInterface $log |
|
26
|
|
|
* @param float $start_time Script start time as float, defaults to "now" |
|
27
|
5 |
|
*/ |
|
28
|
5 |
|
public function __construct(LoggerInterface $log, $start_time = null) |
|
29
|
5 |
|
{ |
|
30
|
|
|
$this->log = $log; |
|
31
|
|
|
$this->start_time = $start_time ?: microtime('float'); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
|
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* PSR-15 Single Pass |
|
38
|
5 |
|
* |
|
39
|
|
|
* @param ServerRequestInterface $request Server reuest instance |
|
40
|
|
|
* @param RequestHandlerInterface $handler Request handler |
|
41
|
|
|
* @return ResponseInterface |
|
42
|
5 |
|
*/ |
|
43
|
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface |
|
44
|
5 |
|
{ |
|
45
|
5 |
|
$response = $handler->handle($request); |
|
46
|
1 |
|
$this->logRuntime(); |
|
47
|
|
|
return $response; |
|
48
|
5 |
|
} |
|
49
|
|
|
|
|
50
|
|
|
|
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* PSR-7 Double Pass |
|
54
|
|
|
* |
|
55
|
|
|
* @param RequestInterface $request |
|
56
|
|
|
* @param ResponseInterface $response |
|
57
|
|
|
* @param callable $next |
|
58
|
|
|
* |
|
59
|
|
|
* @return ResponseInterface |
|
60
|
|
|
*/ |
|
61
|
|
|
public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next) |
|
62
|
|
|
{ |
|
63
|
|
|
$response = $next($request, $response); |
|
64
|
|
|
$this->logRuntime(); |
|
65
|
|
|
return $response; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
|
|
69
|
|
|
protected function logRuntime() |
|
70
|
|
|
{ |
|
71
|
|
|
$this->log->info('Script runtime: ', [ |
|
72
|
|
|
'seconds' => (microtime('float') - $this->start_time) |
|
73
|
|
|
]); |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|