WebprofilerEventSubscriber.php in Devel 8
File
webprofiler/src/EventSubscriber/WebprofilerEventSubscriber.php
View source
<?php
namespace Drupal\webprofiler\EventSubscriber;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Routing\UrlGeneratorInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class WebprofilerEventSubscriber implements EventSubscriberInterface {
private $currentUser;
protected $urlGenerator;
protected $renderer;
public function __construct(AccountInterface $currentUser, UrlGeneratorInterface $urlGenerator, RendererInterface $renderer) {
$this->currentUser = $currentUser;
$this->urlGenerator = $urlGenerator;
$this->renderer = $renderer;
}
public function onKernelResponse(FilterResponseEvent $event) {
$response = $event
->getResponse();
$request = $event
->getRequest();
if ($response->headers
->has('X-Debug-Token') && NULL !== $this->urlGenerator) {
$response->headers
->set('X-Debug-Token-Link', $this->urlGenerator
->generate('webprofiler.dashboard', [
'profile' => $response->headers
->get('X-Debug-Token'),
]));
}
if ($request
->isXmlHttpRequest()) {
return;
}
if ($this->currentUser
->hasPermission('view webprofiler toolbar')) {
$this
->injectToolbar($response);
}
}
protected function injectToolbar(Response $response) {
$content = $response
->getContent();
$pos = mb_strripos($content, '</body>');
if (FALSE !== $pos) {
if ($token = $response->headers
->get('X-Debug-Token')) {
$loader = [
'#theme' => 'webprofiler_loader',
'#token' => $token,
'#profiler_url' => $this->urlGenerator
->generate('webprofiler.toolbar', [
'profile' => $token,
]),
];
$content = mb_substr($content, 0, $pos) . $this->renderer
->renderRoot($loader) . mb_substr($content, $pos);
$response
->setContent($content);
}
}
}
public static function getSubscribedEvents() {
return [
KernelEvents::RESPONSE => [
'onKernelResponse',
-128,
],
];
}
}