ServerTimingMiddleware::getRequestStartTime()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 6
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace BeyondCode\ServerTiming\Middleware;
4
5
use Closure;
6
use Illuminate\Http\Request;
7
use BeyondCode\ServerTiming\ServerTiming;
8
use Illuminate\Support\Str;
9
use Symfony\Component\HttpFoundation\Response;
10
11
class ServerTimingMiddleware
12
{
13
    /** @var ServerTiming */
14
    protected $timing;
15
16
    /** @var float|mixed|string */
17
    protected $start;
18
19
    public function __construct(ServerTiming $timing)
20
    {
21
        $this->timing = $timing;
22
        $this->start = $this->getRequestStartTime();
23
    }
24
25
    public function handle(Request $request, Closure $next)
26
    {
27
        if(false === config('timing.enabled', true)) {
28
            return $next($request);
29
        }
30
31
        $this->timing->setDuration('Bootstrap', $this->getElapsedTimeInMs());
32
33
        $this->timing->start('App');
34
35
        /** @var Response $response */
36
        $response = $next($request);
37
38
        $this->timing->stop('App');
39
40
        $this->timing->stopAllUnfinishedEvents();
41
42
        $this->timing->setDuration('Total', $this->getElapsedTimeInMs());
43
44
        $response->headers->set('Server-Timing', $this->generateHeaders());
45
46
        return $response;
47
    }
48
49
    protected function getElapsedTimeInMs()
50
    {
51
        return (microtime(true) - $this->start) * 1000;
52
    }
53
54
    protected function getRequestStartTime()
55
    {
56
        if (defined('LARAVEL_START')) {
57
            return LARAVEL_START;
58
        }
59
        return $_SERVER["REQUEST_TIME_FLOAT"] ?? microtime(true);
60
    }
61
62
    protected function generateHeaders(): string
63
    {
64
        $header = '';
65
66
        foreach ($this->timing->events() as $eventName => $duration) {
67
            $eventNameSlug = Str::slug($eventName);
68
69
            $header .= "{$eventNameSlug};desc=\"{$eventName}\";";
70
71
            if (!is_null($duration)) {
72
                $header .= "dur={$duration}";
73
            }
74
75
            $header .= ", ";
76
        }
77
78
        return $header;
79
    }
80
}
81