1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace SilverStripe\Control\Middleware; |
4
|
|
|
|
5
|
|
|
use SilverStripe\Assets\File; |
6
|
|
|
use SilverStripe\Control\Director; |
7
|
|
|
use SilverStripe\Control\HTTPRequest; |
8
|
|
|
use SilverStripe\Control\HTTPResponse; |
9
|
|
|
use SilverStripe\Dev\Debug; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Display execution metrics for the current request if in dev mode and `execmetric` is provided as a request variable. |
13
|
|
|
*/ |
14
|
|
|
class ExecMetricMiddleware implements HTTPMiddleware |
15
|
|
|
{ |
16
|
|
|
|
17
|
|
|
public function process(HTTPRequest $request, callable $delegate) |
18
|
|
|
{ |
19
|
|
|
if (!$this->showMetric($request)) { |
20
|
|
|
return $delegate($request); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
$start = microtime(true); |
24
|
|
|
try { |
25
|
|
|
return $delegate($request); |
26
|
|
|
} finally { |
27
|
|
|
$end = microtime(true); |
28
|
|
|
Debug::message( |
29
|
|
|
sprintf( |
30
|
|
|
"Execution time: %s, Peak memory usage: %s\n", |
31
|
|
|
$this->formatExecutionTime($start, $end), |
32
|
|
|
$this->formatPeakMemoryUsage() |
33
|
|
|
), |
34
|
|
|
false |
35
|
|
|
); |
36
|
|
|
} |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Check if execution metric should be shown. |
41
|
|
|
* @param HTTPRequest $request |
42
|
|
|
* @return bool |
43
|
|
|
*/ |
44
|
|
|
private function showMetric(HTTPRequest $request) |
45
|
|
|
{ |
46
|
|
|
return Director::isDev() && array_key_exists('execmetric', $request->getVars()); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Convert the provided start and end time to a interval in secs. |
51
|
|
|
* @param float $start |
52
|
|
|
* @param float $end |
53
|
|
|
* @return string |
54
|
|
|
*/ |
55
|
|
|
private function formatExecutionTime($start, $end) |
56
|
|
|
{ |
57
|
|
|
$diff = round($end - $start, 4); |
58
|
|
|
return $diff . ' seconds'; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Get the peak memory usage formatted has a string and a meaningful unit. |
63
|
|
|
* @return string |
64
|
|
|
*/ |
65
|
|
|
private function formatPeakMemoryUsage() |
66
|
|
|
{ |
67
|
|
|
$bytes = memory_get_peak_usage(true); |
68
|
|
|
return File::format_size($bytes); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|