Skip to content

Commit d848280

Browse files
faraweilyasganyicz
andauthored
Fix Blaze Debug Bar Injection for Multi-Line Body Tags (#133)
* fix: fix blaze debug bar injection for multi-line body tags * Inject widget before closing </body> --------- Co-authored-by: Filip Ganyicz <ganyicz.filip@gmail.com>
1 parent 20cb545 commit d848280

File tree

1 file changed

+24
-12
lines changed

1 file changed

+24
-12
lines changed

src/DebuggerMiddleware.php

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55
use Closure;
66
use Illuminate\Contracts\Http\Kernel;
77
use Illuminate\Http\Request;
8+
use Illuminate\Http\Response;
89
use Illuminate\Support\Facades\Route;
9-
use Symfony\Component\HttpFoundation\Response;
1010

1111
class DebuggerMiddleware
1212
{
@@ -88,24 +88,36 @@ protected function storeProfilerTrace(string $url, Debugger $debugger, bool $isB
8888
}
8989

9090
/**
91-
* Inject the debug bar HTML after the opening <body> tag.
91+
* Inject the debug bar HTML before the closing </body> tag.
92+
*
93+
* Based on https://github.com/fruitcake/laravel-debugbar/blob/master/src/LaravelDebugbar.php
9294
*/
9395
protected function injectDebugger(Response $response, Debugger $debugger): void
9496
{
95-
if (! method_exists($response, 'getContent')) {
96-
return;
97-
}
98-
9997
$content = $response->getContent();
10098

101-
if (! $content || ! preg_match('/<body[^>]*>/i', $content, $matches, PREG_OFFSET_CAPTURE)) {
102-
return;
99+
$widget = "<!-- Blaze Widget -->\n" . $debugger->render();
100+
101+
// Try to put the widget at the end, directly before the </body>
102+
$pos = strripos($content, '</body>');
103+
if (false !== $pos) {
104+
$content = substr($content, 0, $pos) . $widget . substr($content, $pos);
105+
} else {
106+
$content = $content . $widget;
107+
}
108+
109+
$original = null;
110+
if ($response->getOriginalContent()) {
111+
$original = $response->getOriginalContent();
103112
}
104113

105-
$insertPos = $matches[0][1] + strlen($matches[0][0]);
114+
// Update the new content and reset the content length
115+
$response->setContent($content);
116+
$response->headers->remove('Content-Length');
106117

107-
$response->setContent(
108-
substr($content, 0, $insertPos) . "\n" . $debugger->render() . substr($content, $insertPos)
109-
);
118+
// Restore original response (e.g. the View or Ajax data)
119+
if ($original) {
120+
$response->original = $original;
121+
}
110122
}
111123
}

0 commit comments

Comments
 (0)