TwigTracingExtension.php in Raven: Sentry Integration 3.x
File
src/Twig/TwigTracingExtension.php
View source
<?php
declare (strict_types=1);
namespace Drupal\raven\Twig;
use Drupal\Core\Config\ConfigFactoryInterface;
use Sentry\SentrySdk;
use Sentry\Tracing\SpanContext;
use Twig\Extension\AbstractExtension;
use Twig\Profiler\NodeVisitor\ProfilerNodeVisitor;
use Twig\Profiler\Profile;
class TwigTracingExtension extends AbstractExtension {
protected $configFactory;
private $spans;
public function __construct(ConfigFactoryInterface $config_factory) {
$this->configFactory = $config_factory;
$this->spans = new \SplObjectStorage();
}
public function enter(Profile $profile) : void {
if (!$this->configFactory
->get('raven.settings')
->get('twig_tracing') || !class_exists(SentrySdk::class)) {
return;
}
$transaction = SentrySdk::getCurrentHub()
->getTransaction();
if (NULL === $transaction) {
return;
}
$spanContext = new SpanContext();
$spanContext
->setOp('twig.render');
$spanContext
->setDescription($this
->getSpanDescription($profile));
$this->spans[$profile] = $transaction
->startChild($spanContext);
}
public function leave(Profile $profile) : void {
if (!isset($this->spans[$profile])) {
return;
}
$this->spans[$profile]
->finish();
unset($this->spans[$profile]);
}
public function getNodeVisitors() : array {
return [
new ProfilerNodeVisitor(self::class),
];
}
private function getSpanDescription(Profile $profile) : string {
switch (TRUE) {
case $profile
->isRoot():
return $profile
->getName();
case $profile
->isTemplate():
return $profile
->getTemplate();
default:
return sprintf('%s::%s(%s)', $profile
->getTemplate(), $profile
->getType(), $profile
->getName());
}
}
}