1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Psr7Middlewares\Middleware; |
4
|
|
|
|
5
|
|
|
use DebugBar\DebugBar as Bar; |
6
|
|
|
use Psr7Middlewares\Middleware; |
7
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
9
|
|
|
use RuntimeException; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Middleware to render a debugbar in html responses. |
13
|
|
|
*/ |
14
|
|
|
class DebugBar |
15
|
|
|
{ |
16
|
|
|
private $debugBar; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Constructor. Set the debug bar. |
20
|
|
|
* |
21
|
|
|
* @param Bar|null $debugBar |
22
|
|
|
*/ |
23
|
|
|
public function __construct(Bar $debugBar = null) |
24
|
|
|
{ |
25
|
|
|
if ($debugBar !== null) { |
26
|
|
|
$this->debugBar($debugBar); |
27
|
|
|
} |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Set the debug bar. |
32
|
|
|
* |
33
|
|
|
* @param Bar $debugBar |
34
|
|
|
* |
35
|
|
|
* @return self |
36
|
|
|
*/ |
37
|
|
|
public function debugBar(Bar $debugBar) |
38
|
|
|
{ |
39
|
|
|
$this->debugBar = $debugBar; |
40
|
|
|
|
41
|
|
|
return $this; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* Execute the middleware. |
46
|
|
|
* |
47
|
|
|
* @param ServerRequestInterface $request |
48
|
|
|
* @param ResponseInterface $response |
49
|
|
|
* @param callable $next |
50
|
|
|
* |
51
|
|
|
* @return ResponseInterface |
52
|
|
|
*/ |
53
|
|
|
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) |
54
|
|
|
{ |
55
|
|
|
$response = $next($request, $response); |
56
|
|
|
|
57
|
|
|
if ($this->isValid($request)) { |
58
|
|
|
$renderer = $this->debugBar->getJavascriptRenderer(); |
59
|
|
|
|
60
|
|
|
ob_start(); |
61
|
|
|
echo '<style>'; |
62
|
|
|
$renderer->dumpCssAssets(); |
63
|
|
|
echo '</style>'; |
64
|
|
|
|
65
|
|
|
echo '<script>'; |
66
|
|
|
$renderer->dumpJsAssets(); |
67
|
|
|
echo '</script>'; |
68
|
|
|
|
69
|
|
|
echo $renderer->render(); |
70
|
|
|
|
71
|
|
|
$response->getBody()->write(ob_get_clean()); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return $response; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* Check whether the request is valid to insert a debugbar in the response. |
79
|
|
|
* |
80
|
|
|
* @param ServerRequestInterface $request |
81
|
|
|
* |
82
|
|
|
* @return bool |
83
|
|
|
*/ |
84
|
|
|
private function isValid(ServerRequestInterface $request) |
85
|
|
|
{ |
86
|
|
|
if (!Middleware::hasAttribute($request, FormatNegotiator::KEY)) { |
87
|
|
|
throw new RuntimeException('DebugBar middleware needs FormatNegotiator executed before'); |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
//is not html? |
91
|
|
|
if (FormatNegotiator::getFormat($request) !== 'html') { |
92
|
|
|
return false; |
93
|
|
|
} |
94
|
|
|
|
95
|
|
|
//is ajax? |
96
|
|
|
if (strtolower($request->getHeaderLine('X-Requested-With')) === 'xmlhttprequest') { |
97
|
|
|
return false; |
98
|
|
|
} |
99
|
|
|
|
100
|
|
|
return true; |
101
|
|
|
} |
102
|
|
|
} |
103
|
|
|
|