Completed
Pull Request — master (#47)
by Robbie
01:30
created

DebugBarMiddleware   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 91
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Importance

Changes 0
Metric Value
wmc 17
lcom 0
cbo 5
dl 0
loc 91
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A process() 0 7 1
A beforeRequest() 0 21 3
C afterRequest() 0 47 13
1
<?php
2
3
namespace LeKoala\DebugBar\Middleware;
4
5
use LeKoala\DebugBar\DebugBar;
6
use SilverStripe\Control\Middleware\HTTPMiddleware;
7
use SilverStripe\Control\Director;
8
use SilverStripe\Control\HTTPRequest;
9
use SilverStripe\Control\HTTPResponse;
10
11
class DebugBarMiddleware implements HTTPMiddleware
12
{
13
    public function process(HTTPRequest $request, callable $delegate)
14
    {
15
        $this->beforeRequest($request);
16
        $response = $delegate($request);
17
        $this->afterRequest($request, $response);
18
        return $response;
19
    }
20
21
    /**
22
     * Track the start up of the framework boot
23
     *
24
     * @param HTTPRequest $request
25
     */
26
    protected function beforeRequest(HTTPRequest $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Coding Style introduced by
beforeRequest uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
27
    {
28
        DebugBar::withDebugBar(function (\DebugBar\DebugBar $debugbar) {
29
            /** @var DebugBar\DataCollector\TimeDataCollector $timeData */
30
            $timeData = $debugbar->getCollector('time');
31
32
            if (!$timeData) {
33
                return;
34
            }
35
36
            if (isset($_SERVER['REQUEST_TIME_FLOAT'])) {
37
                $timeData = $debugbar['time'];
38
                $timeData->addMeasure(
39
                    'framework boot',
40
                    $_SERVER['REQUEST_TIME_FLOAT'],
41
                    microtime(true)
42
                );
43
            }
44
            $timeData->startMeasure('pre_request', 'pre request');
45
        });
46
    }
47
48
    /**
49
     * Inject DebugBar requirements for the frontend
50
     *
51
     * @param HTTPRequest  $request
52
     * @param HTTPResponse $response
53
     */
54
    protected function afterRequest(HTTPRequest $request, HTTPResponse $response)
55
    {
56
        $debugbar = DebugBar::getDebugBar();
57
        if (!$debugbar) {
58
            return;
59
        }
60
        DebugBar::setRequest($request);
61
62
        // All queries have been displayed
63
        if (DebugBar::getShowQueries()) {
64
            exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The method afterRequest() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
65
        }
66
67
        $script = DebugBar::renderDebugBar();
68
69
        // If the bar is not renderable, return early
70
        if (!$script) {
71
            return;
72
        }
73
74
        // Inject init script into the HTML response
75
        $body = $response->getBody();
76
        if (strpos($body, '</body>') !== false) {
77
            $body = str_replace('</body>', $script . '</body>', $body);
78
            $response->setBody($body);
79
        }
80
81
        // Ajax support
82
        if (Director::is_ajax() && !headers_sent()) {
83
            if (DebugBar::isAdminUrl() && !DebugBar::config()->enabled_in_admin) {
84
                return;
85
            }
86
            // Skip anything that is not a GET request
87
            if (!$request->isGET()) {
88
                return;
89
            }
90
            // Always enable in admin because everything is mostly loaded through ajax
91
            if (DebugBar::config()->ajax || DebugBar::isAdminUrl()) {
92
                $headers = $debugbar->getDataAsHeaders();
93
94
                // Prevent throwing js errors in case header size is too large
95
                if (is_array($headers)) {
96
                    $debugbar->sendDataInHeaders();
97
                }
98
            }
99
        }
100
    }
101
}
102