vendor/sentry/sentry-symfony/src/EventListener/RequestListener.php line 72

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Sentry\SentryBundle\EventListener;
  4. use Sentry\State\HubInterface;
  5. use Sentry\State\Scope;
  6. use Sentry\UserDataBag;
  7. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  8. use Symfony\Component\HttpKernel\Event\RequestEvent;
  9. /**
  10. * This listener ensures that a new {@see Scope} is created for
  11. * each request and that it is filled with useful information, e.g. the IP
  12. * address of the client.
  13. */
  14. final class RequestListener
  15. {
  16. use KernelEventForwardCompatibilityTrait;
  17. /**
  18. * @var HubInterface The current hub
  19. */
  20. private $hub;
  21. /**
  22. * Constructor.
  23. *
  24. * @param HubInterface $hub The current hub
  25. */
  26. public function __construct(HubInterface $hub/* , ?TokenStorageInterface $tokenStorage */)
  27. {
  28. $this->hub = $hub;
  29. }
  30. /**
  31. * This method is called for each request handled by the framework and
  32. * fills the Sentry scope with information about the current user.
  33. *
  34. * @param RequestEvent $event The event
  35. */
  36. public function handleKernelRequestEvent(RequestEvent $event): void
  37. {
  38. if (!$this->isMainRequest($event)) {
  39. return;
  40. }
  41. $client = $this->hub->getClient();
  42. if (null === $client || !$client->getOptions()->shouldSendDefaultPii()) {
  43. return;
  44. }
  45. $this->hub->configureScope(static function (Scope $scope) use ($event): void {
  46. $user = $scope->getUser() ?? new UserDataBag();
  47. if (null === $user->getIpAddress()) {
  48. $user->setIpAddress($event->getRequest()->getClientIp());
  49. }
  50. $scope->setUser($user);
  51. });
  52. }
  53. /**
  54. * This method is called for each request handled by the framework and
  55. * sets the route on the current Sentry scope.
  56. *
  57. * @param ControllerEvent $event The event
  58. */
  59. public function handleKernelControllerEvent(ControllerEvent $event): void
  60. {
  61. if (!$this->isMainRequest($event)) {
  62. return;
  63. }
  64. $route = $event->getRequest()->attributes->get('_route');
  65. if (!\is_string($route)) {
  66. return;
  67. }
  68. $this->hub->configureScope(static function (Scope $scope) use ($route): void {
  69. $scope->setTag('route', $route);
  70. });
  71. }
  72. }