diff --git a/CHANGELOG.md b/CHANGELOG.md index dac6bd0e..130b5e34 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## Unreleased - Make the transport factory configurable in the bundle's config (#504) +- Add the `sentry_trace_meta()` Twig function to print the `sentry-trace` HTML meta tag (#510) ## 4.1.0 (2021-04-19) diff --git a/src/Resources/config/services.xml b/src/Resources/config/services.xml index 9bfaaea8..2d0fecca 100644 --- a/src/Resources/config/services.xml +++ b/src/Resources/config/services.xml @@ -116,5 +116,11 @@ + + + + + + diff --git a/src/Twig/SentryExtension.php b/src/Twig/SentryExtension.php new file mode 100644 index 00000000..c86a393f --- /dev/null +++ b/src/Twig/SentryExtension.php @@ -0,0 +1,45 @@ +hub = $hub; + } + + /** + * {@inheritdoc} + */ + public function getFunctions(): array + { + return [ + new TwigFunction('sentry_trace_meta', \Closure::fromCallable([$this, 'getTraceMeta']), ['is_safe' => ['html']]), + ]; + } + + /** + * Returns an HTML meta tag named `sentry-trace`. + */ + private function getTraceMeta(): string + { + $span = $this->hub->getSpan(); + + return sprintf('', null !== $span ? $span->toTraceparent() : ''); + } +} diff --git a/tests/Twig/SentryExtensionTest.php b/tests/Twig/SentryExtensionTest.php new file mode 100644 index 00000000..5dd06c52 --- /dev/null +++ b/tests/Twig/SentryExtensionTest.php @@ -0,0 +1,78 @@ +hub = $this->createMock(HubInterface::class); + } + + /** + * @dataProvider traceMetaFunctionDataProvider + */ + public function testTraceMetaFunction(?Span $span, string $expectedTemplate): void + { + $this->hub->expects($this->once()) + ->method('getSpan') + ->willReturn($span); + + $environment = new Environment(new ArrayLoader(['foo.twig' => '{{ sentry_trace_meta() }}'])); + $environment->addExtension(new SentryExtension($this->hub)); + + $this->assertSame($expectedTemplate, $environment->render('foo.twig')); + } + + /** + * @return \Generator + */ + public function traceMetaFunctionDataProvider(): \Generator + { + yield [ + null, + '', + ]; + + $transaction = new Transaction(new TransactionContext()); + $transaction->setTraceId(new TraceId('a3c01c41d7b94b90aee23edac90f4319')); + $transaction->setSpanId(new SpanId('e69c2aef0ec34f2a')); + + yield [ + $transaction, + '', + ]; + } + + private static function isTwigBundlePackageInstalled(): bool + { + return class_exists(TwigBundle::class); + } +}