Skip to content

[WebProfilerBundle] add debugbar on StreamedResponse #58789

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: 7.4
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
[WebProfilerBundle] show debugbar on StreamedResponse
  • Loading branch information
damienfern committed Jan 24, 2025
commit c1e7be0ad4e24b0275d3a463b98f8af16c4b8a9e
1 change: 1 addition & 0 deletions src/Symfony/Bundle/WebProfilerBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ CHANGELOG
---

* Add support for displaying profiles of multiple serializer instances
* Show debug bar when using a streamed response

7.1
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Flash\AutoExpireFlashBag;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\DataCollector\DumpDataCollector;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
Expand Down Expand Up @@ -109,7 +110,6 @@ public function onKernelResponse(ResponseEvent $event): void
// keep current flashes for one more request if using AutoExpireFlashBag
$session->getFlashBag()->setAll($session->getFlashBag()->peekAll());
}

$response->setContent($this->twig->render('@WebProfiler/Profiler/toolbar_redirect.html.twig', ['location' => $response->headers->get('Location'), 'host' => $request->getSchemeAndHttpHost()]));
$response->setStatusCode(200);
$response->headers->remove('Location');
Expand All @@ -133,26 +133,59 @@ public function onKernelResponse(ResponseEvent $event): void
*/
protected function injectToolbar(Response $response, Request $request, array $nonces): void
{
$content = $response->getContent();
$pos = strripos($content, '</body>');

if (false !== $pos) {
$toolbar = "\n".str_replace("\n", '', $this->twig->render(
'@WebProfiler/Profiler/toolbar_js.html.twig',
[
'full_stack' => class_exists(FullStack::class),
'excluded_ajax_paths' => $this->excludedAjaxPaths,
'token' => $response->headers->get('X-Debug-Token'),
'request' => $request,
'csp_script_nonce' => $nonces['csp_script_nonce'] ?? null,
'csp_style_nonce' => $nonces['csp_style_nonce'] ?? null,
]
))."\n";
$content = substr($content, 0, $pos).$toolbar.substr($content, $pos);
$response->setContent($content);
if ($response instanceof StreamedResponse) {
$callback = $response->getCallback();
if (false !== strripos($response->headers->get('Content-Type'), 'text/html')) {
$toolbarHTMLContent = $this->getToolbarHTML($request, $response->headers->get('X-Debug-Token'), $nonces);
$injectedCallback = static function () use ($toolbarHTMLContent, $callback): void {
ob_start(function (string $buffer, int $phase) use ($toolbarHTMLContent): string {
$pos = strripos($buffer, '</body>');
if (false !== $pos) {
$buffer = substr($buffer, 0, $pos).$toolbarHTMLContent.substr($buffer, $pos);
}

return $buffer;
}, 8); // length of '</body>'

($callback)();
ob_end_flush();
};
$response->setCallback($injectedCallback);
}
} else {
$content = $response->getContent();
$pos = strripos($content, '</body>');

if (false !== $pos) {
$response->setContent(
$this->renderToolbarInContent($content, $pos, $response->headers->get('X-Debug-Token'), $request, $nonces)
);
}
}
}

protected function renderToolbarInContent(string $content, int $pos, ?string $debugToken, Request $request, array $nonces): string
{
$toolbar = "\n".str_replace("\n", '', $this->getToolbarHTML($request, $debugToken, $nonces))."\n";

return substr($content, 0, $pos).$toolbar.substr($content, $pos);
}

private function getToolbarHTML(Request $request, ?string $debugToken, array $nonces): string
{
return $this->twig->render(
'@WebProfiler/Profiler/toolbar_js.html.twig',
[
'full_stack' => class_exists(FullStack::class),
'excluded_ajax_paths' => $this->excludedAjaxPaths,
'token' => $debugToken,
'request' => $request,
'csp_script_nonce' => $nonces['csp_script_nonce'] ?? null,
'csp_style_nonce' => $nonces['csp_style_nonce'] ?? null,
]
);
}

public static function getSubscribedEvents(): array
{
return [
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\WebProfilerBundle\Tests\EventListener;

use Symfony\Component\HttpFoundation\StreamedResponse;

class MockedStreamedResponse extends StreamedResponse
{
public function getContent(): string|false
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would not override the getContent method of StreamedResponse for that, as it means this MockedStreamedResponse does not actually behave like a StreamedResponse (in which you cannot call getContent to get the actual content), which would potentially hide bugs in tests.

Instead, I would suggest writing a separate test covering the injection of the toolbar in a streamed response, which would perform this output buffering in the test (using $response->sendContent()).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right and indeed I missed a bug on StreamedResponse here.

Let me know if it's ok for you.

{
ob_start();
($this->callback)();
$content = ob_get_contents();
ob_end_clean();

return $content;
}

public static function createFromContent(string $content = ''): self
{
$response = new self();
$response->setCallback(function () use ($content) {
echo $content;
});
$response->headers->set('Content-Type', 'text/html');

return $response;
}
}
Loading