RouterDataCollector.php 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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\Component\HttpKernel\DataCollector;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\HttpFoundation\RedirectResponse;
  14. use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
  15. /**
  16. * RouterDataCollector.
  17. *
  18. * @author Fabien Potencier <fabien@symfony.com>
  19. */
  20. class RouterDataCollector extends DataCollector
  21. {
  22. /**
  23. * @var \SplObjectStorage
  24. */
  25. protected $controllers;
  26. public function __construct()
  27. {
  28. $this->reset();
  29. }
  30. /**
  31. * {@inheritdoc}
  32. */
  33. public function collect(Request $request, Response $response, \Exception $exception = null)
  34. {
  35. if ($response instanceof RedirectResponse) {
  36. $this->data['redirect'] = true;
  37. $this->data['url'] = $response->getTargetUrl();
  38. if ($this->controllers->contains($request)) {
  39. $this->data['route'] = $this->guessRoute($request, $this->controllers[$request]);
  40. }
  41. }
  42. unset($this->controllers[$request]);
  43. }
  44. public function reset()
  45. {
  46. $this->controllers = new \SplObjectStorage();
  47. $this->data = array(
  48. 'redirect' => false,
  49. 'url' => null,
  50. 'route' => null,
  51. );
  52. }
  53. protected function guessRoute(Request $request, $controller)
  54. {
  55. return 'n/a';
  56. }
  57. /**
  58. * Remembers the controller associated to each request.
  59. */
  60. public function onKernelController(FilterControllerEvent $event)
  61. {
  62. $this->controllers[$event->getRequest()] = $event->getController();
  63. }
  64. /**
  65. * @return bool Whether this request will result in a redirect
  66. */
  67. public function getRedirect()
  68. {
  69. return $this->data['redirect'];
  70. }
  71. /**
  72. * @return string|null The target URL
  73. */
  74. public function getTargetUrl()
  75. {
  76. return $this->data['url'];
  77. }
  78. /**
  79. * @return string|null The target route
  80. */
  81. public function getTargetRoute()
  82. {
  83. return $this->data['route'];
  84. }
  85. /**
  86. * {@inheritdoc}
  87. */
  88. public function getName()
  89. {
  90. return 'router';
  91. }
  92. }