HttpKernel.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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;
  11. use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
  12. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  13. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  14. use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
  15. use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
  16. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  17. use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
  18. use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
  19. use Symfony\Component\HttpKernel\Event\PostResponseEvent;
  20. use Symfony\Component\HttpFoundation\Request;
  21. use Symfony\Component\HttpFoundation\Response;
  22. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  23. /**
  24. * HttpKernel notifies events to convert a Request object to a Response one.
  25. *
  26. * @author Fabien Potencier <fabien@symfony.com>
  27. *
  28. * @api
  29. */
  30. class HttpKernel implements HttpKernelInterface, TerminableInterface
  31. {
  32. protected $dispatcher;
  33. protected $resolver;
  34. /**
  35. * Constructor
  36. *
  37. * @param EventDispatcherInterface $dispatcher An EventDispatcherInterface instance
  38. * @param ControllerResolverInterface $resolver A ControllerResolverInterface instance
  39. *
  40. * @api
  41. */
  42. public function __construct(EventDispatcherInterface $dispatcher, ControllerResolverInterface $resolver)
  43. {
  44. $this->dispatcher = $dispatcher;
  45. $this->resolver = $resolver;
  46. }
  47. /**
  48. * {@inheritdoc}
  49. *
  50. * @api
  51. */
  52. public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
  53. {
  54. try {
  55. return $this->handleRaw($request, $type);
  56. } catch (\Exception $e) {
  57. if (false === $catch) {
  58. throw $e;
  59. }
  60. return $this->handleException($e, $request, $type);
  61. }
  62. }
  63. /**
  64. * {@inheritdoc}
  65. *
  66. * @api
  67. */
  68. public function terminate(Request $request, Response $response)
  69. {
  70. $this->dispatcher->dispatch(KernelEvents::TERMINATE, new PostResponseEvent($this, $request, $response));
  71. }
  72. /**
  73. * Handles a request to convert it to a response.
  74. *
  75. * Exceptions are not caught.
  76. *
  77. * @param Request $request A Request instance
  78. * @param integer $type The type of the request (one of HttpKernelInterface::MASTER_REQUEST or HttpKernelInterface::SUB_REQUEST)
  79. *
  80. * @return Response A Response instance
  81. *
  82. * @throws \LogicException If one of the listener does not behave as expected
  83. * @throws NotFoundHttpException When controller cannot be found
  84. */
  85. private function handleRaw(Request $request, $type = self::MASTER_REQUEST)
  86. {
  87. // request
  88. $event = new GetResponseEvent($this, $request, $type);
  89. $this->dispatcher->dispatch(KernelEvents::REQUEST, $event);
  90. if ($event->hasResponse()) {
  91. return $this->filterResponse($event->getResponse(), $request, $type);
  92. }
  93. // load controller
  94. if (false === $controller = $this->resolver->getController($request)) {
  95. throw new NotFoundHttpException(sprintf('Unable to find the controller for path "%s". Maybe you forgot to add the matching route in your routing configuration?', $request->getPathInfo()));
  96. }
  97. $event = new FilterControllerEvent($this, $controller, $request, $type);
  98. $this->dispatcher->dispatch(KernelEvents::CONTROLLER, $event);
  99. $controller = $event->getController();
  100. // controller arguments
  101. $arguments = $this->resolver->getArguments($request, $controller);
  102. // call controller
  103. $response = call_user_func_array($controller, $arguments);
  104. // view
  105. if (!$response instanceof Response) {
  106. $event = new GetResponseForControllerResultEvent($this, $request, $type, $response);
  107. $this->dispatcher->dispatch(KernelEvents::VIEW, $event);
  108. if ($event->hasResponse()) {
  109. $response = $event->getResponse();
  110. }
  111. if (!$response instanceof Response) {
  112. $msg = sprintf('The controller must return a response (%s given).', $this->varToString($response));
  113. // the user may have forgotten to return something
  114. if (null === $response) {
  115. $msg .= ' Did you forget to add a return statement somewhere in your controller?';
  116. }
  117. throw new \LogicException($msg);
  118. }
  119. }
  120. return $this->filterResponse($response, $request, $type);
  121. }
  122. /**
  123. * Filters a response object.
  124. *
  125. * @param Response $response A Response instance
  126. * @param Request $request An error message in case the response is not a Response object
  127. * @param integer $type The type of the request (one of HttpKernelInterface::MASTER_REQUEST or HttpKernelInterface::SUB_REQUEST)
  128. *
  129. * @return Response The filtered Response instance
  130. *
  131. * @throws \RuntimeException if the passed object is not a Response instance
  132. */
  133. private function filterResponse(Response $response, Request $request, $type)
  134. {
  135. $event = new FilterResponseEvent($this, $request, $type, $response);
  136. $this->dispatcher->dispatch(KernelEvents::RESPONSE, $event);
  137. return $event->getResponse();
  138. }
  139. /**
  140. * Handles an exception by trying to convert it to a Response.
  141. *
  142. * @param \Exception $e An \Exception instance
  143. * @param Request $request A Request instance
  144. * @param integer $type The type of the request
  145. *
  146. * @return Response A Response instance
  147. *
  148. * @throws \Exception
  149. */
  150. private function handleException(\Exception $e, $request, $type)
  151. {
  152. $event = new GetResponseForExceptionEvent($this, $request, $type, $e);
  153. $this->dispatcher->dispatch(KernelEvents::EXCEPTION, $event);
  154. // a listener might have replaced the exception
  155. $e = $event->getException();
  156. if (!$event->hasResponse()) {
  157. throw $e;
  158. }
  159. $response = $event->getResponse();
  160. // the developer asked for a specific status code
  161. if ($response->headers->has('X-Status-Code')) {
  162. $response->setStatusCode($response->headers->get('X-Status-Code'));
  163. $response->headers->remove('X-Status-Code');
  164. } elseif (!$response->isClientError() && !$response->isServerError() && !$response->isRedirect()) {
  165. // ensure that we actually have an error response
  166. if ($e instanceof HttpExceptionInterface) {
  167. // keep the HTTP status code and headers
  168. $response->setStatusCode($e->getStatusCode());
  169. $response->headers->add($e->getHeaders());
  170. } else {
  171. $response->setStatusCode(500);
  172. }
  173. }
  174. try {
  175. return $this->filterResponse($response, $request, $type);
  176. } catch (\Exception $e) {
  177. return $response;
  178. }
  179. }
  180. private function varToString($var)
  181. {
  182. if (is_object($var)) {
  183. return sprintf('Object(%s)', get_class($var));
  184. }
  185. if (is_array($var)) {
  186. $a = array();
  187. foreach ($var as $k => $v) {
  188. $a[] = sprintf('%s => %s', $k, $this->varToString($v));
  189. }
  190. return sprintf("Array(%s)", implode(', ', $a));
  191. }
  192. if (is_resource($var)) {
  193. return sprintf('Resource(%s)', get_resource_type($var));
  194. }
  195. if (null === $var) {
  196. return 'null';
  197. }
  198. if (false === $var) {
  199. return 'false';
  200. }
  201. if (true === $var) {
  202. return 'true';
  203. }
  204. return (string) $var;
  205. }
  206. }