RouteProcessor.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Bridge\Monolog\Processor;
  11. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  12. use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
  13. use Symfony\Component\HttpKernel\Event\RequestEvent;
  14. use Symfony\Component\HttpKernel\KernelEvents;
  15. use Symfony\Contracts\Service\ResetInterface;
  16. /**
  17. * Adds the current route information to the log entry.
  18. *
  19. * @author Piotr Stankowski <git@trakos.pl>
  20. *
  21. * @final
  22. */
  23. class RouteProcessor implements EventSubscriberInterface, ResetInterface
  24. {
  25. private $routeData;
  26. private $includeParams;
  27. public function __construct(bool $includeParams = true)
  28. {
  29. $this->includeParams = $includeParams;
  30. $this->reset();
  31. }
  32. public function __invoke(array $records): array
  33. {
  34. if ($this->routeData && !isset($records['extra']['requests'])) {
  35. $records['extra']['requests'] = array_values($this->routeData);
  36. }
  37. return $records;
  38. }
  39. public function reset()
  40. {
  41. $this->routeData = [];
  42. }
  43. public function addRouteData(RequestEvent $event)
  44. {
  45. if ($event->isMasterRequest()) {
  46. $this->reset();
  47. }
  48. $request = $event->getRequest();
  49. if (!$request->attributes->has('_controller')) {
  50. return;
  51. }
  52. $currentRequestData = [
  53. 'controller' => $request->attributes->get('_controller'),
  54. 'route' => $request->attributes->get('_route'),
  55. ];
  56. if ($this->includeParams) {
  57. $currentRequestData['route_params'] = $request->attributes->get('_route_params');
  58. }
  59. $this->routeData[spl_object_id($request)] = $currentRequestData;
  60. }
  61. public function removeRouteData(FinishRequestEvent $event)
  62. {
  63. $requestId = spl_object_id($event->getRequest());
  64. unset($this->routeData[$requestId]);
  65. }
  66. public static function getSubscribedEvents(): array
  67. {
  68. return [
  69. KernelEvents::REQUEST => ['addRouteData', 1],
  70. KernelEvents::FINISH_REQUEST => ['removeRouteData', 1],
  71. ];
  72. }
  73. }