XHProfEventSubscriber.php in XHProf 8
File
src/EventSubscriber/XHProfEventSubscriber.php
View source
<?php
namespace Drupal\xhprof\EventSubscriber;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\xhprof\ProfilerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class XHProfEventSubscriber implements EventSubscriberInterface {
public $profiler;
private $currentUser;
private $xhprofRunId;
private $moduleHandler;
public function __construct(ProfilerInterface $profiler, AccountInterface $currentUser, ModuleHandlerInterface $module_handler) {
$this->profiler = $profiler;
$this->currentUser = $currentUser;
$this->moduleHandler = $module_handler;
}
static function getSubscribedEvents() {
return [
KernelEvents::REQUEST => [
'onKernelRequest',
0,
],
KernelEvents::RESPONSE => [
'onKernelResponse',
0,
],
KernelEvents::TERMINATE => [
'onKernelTerminate',
0,
],
];
}
public function onKernelRequest(GetResponseEvent $event) {
if ($this->profiler
->canEnable($event
->getRequest())) {
$this->profiler
->enable();
}
}
public function onKernelResponse(FilterResponseEvent $event) {
if ($this->profiler
->isEnabled()) {
$this->xhprofRunId = $this->profiler
->createRunId();
if (!$this->moduleHandler
->moduleExists('webprofiler')) {
$response = $event
->getResponse();
$formats = [
'xml',
'javascript',
'json',
'plain',
'image',
'application',
'csv',
'x-comma-separated-values',
];
foreach ($formats as $format) {
if ($response->headers
->get($format)) {
return;
}
}
if ($this->currentUser
->hasPermission('access xhprof data')) {
$this
->injectLink($response, $this->xhprofRunId);
}
}
}
}
public function onKernelTerminate() {
if ($this->profiler
->isEnabled()) {
$this->profiler
->shutdown($this->xhprofRunId);
}
}
protected function injectLink(Response $response, $xhprofRunId) {
$content = $response
->getContent();
$pos = mb_strripos($content, '</body>');
if (FALSE !== $pos) {
$output = '<div class="xhprof-ui">' . $this->profiler
->link($xhprofRunId) . '</div>';
$content = mb_substr($content, 0, $pos) . $output . mb_substr($content, $pos);
$response
->setContent($content);
}
}
}