| 199 |
lars |
1 |
<?php namespace Clockwork\Helpers;
|
|
|
2 |
|
|
|
3 |
use Clockwork\Request\Request;
|
|
|
4 |
|
|
|
5 |
// Generates Server-Timing header value
|
|
|
6 |
class ServerTiming
|
|
|
7 |
{
|
|
|
8 |
// Performance metrics to include
|
|
|
9 |
protected $metrics = [];
|
|
|
10 |
|
|
|
11 |
// Add a performance metric
|
|
|
12 |
public function add($metric, $value, $description)
|
|
|
13 |
{
|
|
|
14 |
$this->metrics[] = [ 'metric' => $metric, 'value' => $value, 'description' => $description ];
|
|
|
15 |
|
|
|
16 |
return $this;
|
|
|
17 |
}
|
|
|
18 |
|
|
|
19 |
// Generate the header value
|
|
|
20 |
public function value()
|
|
|
21 |
{
|
|
|
22 |
return implode(', ', array_map(function ($metric) {
|
|
|
23 |
return "{$metric['metric']}; dur={$metric['value']}; desc=\"{$metric['description']}\"";
|
|
|
24 |
}, $this->metrics));
|
|
|
25 |
}
|
|
|
26 |
|
|
|
27 |
// Create a new instance from a Clockwork request
|
|
|
28 |
public static function fromRequest(Request $request, $eventsCount = 10)
|
|
|
29 |
{
|
|
|
30 |
$header = new static;
|
|
|
31 |
|
|
|
32 |
$header->add('app', $request->getResponseDuration(), 'Application');
|
|
|
33 |
|
|
|
34 |
if ($request->getDatabaseDuration()) {
|
|
|
35 |
$header->add('db', $request->getDatabaseDuration(), 'Database');
|
|
|
36 |
}
|
|
|
37 |
|
|
|
38 |
// add timeline events limited to a set number so the header doesn't get too large
|
|
|
39 |
foreach (array_slice($request->timeline()->events, 0, $eventsCount) as $i => $event) {
|
|
|
40 |
$header->add("timeline-event-{$i}", $event->duration(), $event->description);
|
|
|
41 |
}
|
|
|
42 |
|
|
|
43 |
return $header;
|
|
|
44 |
}
|
|
|
45 |
}
|