|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Sentry\SentryBundle\DependencyInjection\Compiler; |
| 6 | + |
| 7 | +use Monolog\Handler\BufferHandler; |
| 8 | +use Sentry\Monolog\Handler as SentryHandler; |
| 9 | +use Sentry\SentryBundle\EventListener\SentryBufferFlusher; |
| 10 | +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; |
| 11 | +use Symfony\Component\DependencyInjection\ContainerBuilder; |
| 12 | +use Symfony\Component\DependencyInjection\Definition; |
| 13 | +use Symfony\Component\DependencyInjection\Reference; |
| 14 | + |
| 15 | +class SentryBufferFlushPass implements CompilerPassInterface |
| 16 | +{ |
| 17 | + public function process(ContainerBuilder $container): void |
| 18 | + { |
| 19 | + $sentryBufferHandlers = $this->findSentryBufferHandlers($container); |
| 20 | + |
| 21 | + if (empty($sentryBufferHandlers)) { |
| 22 | + return; |
| 23 | + } |
| 24 | + |
| 25 | + $flusherDefinition = new Definition(SentryBufferFlusher::class); |
| 26 | + $flusherDefinition->setArguments([$sentryBufferHandlers]); |
| 27 | + $flusherDefinition->addTag('kernel.event_subscriber'); |
| 28 | + |
| 29 | + $container->setDefinition('sentry.buffer_flusher', $flusherDefinition); |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * Finds all {@link BufferHandler} that wrap {@link SentryHandler} and register a service |
| 34 | + * that will flush them on KernelEvents::TERMINATE to make sure that all events retain |
| 35 | + * breadcrumbs and context information. |
| 36 | + * |
| 37 | + * @return Reference[] |
| 38 | + */ |
| 39 | + private function findSentryBufferHandlers(ContainerBuilder $container): array |
| 40 | + { |
| 41 | + $sentryBufferHandlers = []; |
| 42 | + |
| 43 | + foreach ($container->getDefinitions() as $serviceId => $definition) { |
| 44 | + if (BufferHandler::class === $definition->getClass()) { |
| 45 | + $arguments = $definition->getArguments(); |
| 46 | + if (!empty($arguments)) { |
| 47 | + // The first argument of BufferHandler is the HandlerInterface, which |
| 48 | + // can be a SentryHandler. |
| 49 | + $firstArgument = $arguments[0]; |
| 50 | + |
| 51 | + if ($firstArgument instanceof Reference) { |
| 52 | + $referencedServiceId = (string) $firstArgument; |
| 53 | + try { |
| 54 | + $referencedDefinition = $container->findDefinition($referencedServiceId); |
| 55 | + |
| 56 | + if (SentryHandler::class === $referencedDefinition->getClass()) { |
| 57 | + $sentryBufferHandlers[] = new Reference($serviceId); |
| 58 | + } |
| 59 | + } catch (\Exception $e) { |
| 60 | + // If the service from the first argument doesn't exist we just keep going |
| 61 | + continue; |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + return $sentryBufferHandlers; |
| 69 | + } |
| 70 | +} |
0 commit comments