HttpKernel.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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\EventDispatcher\EventDispatcherInterface;
  12. use Symfony\Component\HttpFoundation\Exception\RequestExceptionInterface;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\RequestStack;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\HttpKernel\Controller\ArgumentResolver;
  17. use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface;
  18. use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
  19. use Symfony\Component\HttpKernel\Event\FilterControllerArgumentsEvent;
  20. use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
  21. use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
  22. use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
  23. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  24. use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
  25. use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
  26. use Symfony\Component\HttpKernel\Event\PostResponseEvent;
  27. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  28. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  29. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  30. /**
  31. * HttpKernel notifies events to convert a Request object to a Response one.
  32. *
  33. * @author Fabien Potencier <fabien@symfony.com>
  34. */
  35. class HttpKernel implements HttpKernelInterface, TerminableInterface
  36. {
  37. protected $dispatcher;
  38. protected $resolver;
  39. protected $requestStack;
  40. private $argumentResolver;
  41. public function __construct(EventDispatcherInterface $dispatcher, ControllerResolverInterface $resolver, RequestStack $requestStack = null, ArgumentResolverInterface $argumentResolver = null)
  42. {
  43. $this->dispatcher = $dispatcher;
  44. $this->resolver = $resolver;
  45. $this->requestStack = $requestStack ?: new RequestStack();
  46. $this->argumentResolver = $argumentResolver;
  47. if (null === $this->argumentResolver) {
  48. @trigger_error(sprintf('As of 3.1 an %s is used to resolve arguments. In 4.0 the $argumentResolver becomes the %s if no other is provided instead of using the $resolver argument.', ArgumentResolverInterface::class, ArgumentResolver::class), E_USER_DEPRECATED);
  49. // fallback in case of deprecations
  50. $this->argumentResolver = $resolver;
  51. }
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
  57. {
  58. $request->headers->set('X-Php-Ob-Level', ob_get_level());
  59. try {
  60. return $this->handleRaw($request, $type);
  61. } catch (\Exception $e) {
  62. if ($e instanceof RequestExceptionInterface) {
  63. $e = new BadRequestHttpException($e->getMessage(), $e);
  64. }
  65. if (false === $catch) {
  66. $this->finishRequest($request, $type);
  67. throw $e;
  68. }
  69. return $this->handleException($e, $request, $type);
  70. }
  71. }
  72. /**
  73. * {@inheritdoc}
  74. */
  75. public function terminate(Request $request, Response $response)
  76. {
  77. $this->dispatcher->dispatch(KernelEvents::TERMINATE, new PostResponseEvent($this, $request, $response));
  78. }
  79. /**
  80. * @internal
  81. */
  82. public function terminateWithException(\Exception $exception, Request $request = null)
  83. {
  84. if (!$request = $request ?: $this->requestStack->getMasterRequest()) {
  85. throw $exception;
  86. }
  87. $response = $this->handleException($exception, $request, self::MASTER_REQUEST);
  88. $response->sendHeaders();
  89. $response->sendContent();
  90. $this->terminate($request, $response);
  91. }
  92. /**
  93. * Handles a request to convert it to a response.
  94. *
  95. * Exceptions are not caught.
  96. *
  97. * @param Request $request A Request instance
  98. * @param int $type The type of the request (one of HttpKernelInterface::MASTER_REQUEST or HttpKernelInterface::SUB_REQUEST)
  99. *
  100. * @return Response A Response instance
  101. *
  102. * @throws \LogicException If one of the listener does not behave as expected
  103. * @throws NotFoundHttpException When controller cannot be found
  104. */
  105. private function handleRaw(Request $request, $type = self::MASTER_REQUEST)
  106. {
  107. $this->requestStack->push($request);
  108. // request
  109. $event = new GetResponseEvent($this, $request, $type);
  110. $this->dispatcher->dispatch(KernelEvents::REQUEST, $event);
  111. if ($event->hasResponse()) {
  112. return $this->filterResponse($event->getResponse(), $request, $type);
  113. }
  114. // load controller
  115. if (false === $controller = $this->resolver->getController($request)) {
  116. throw new NotFoundHttpException(sprintf('Unable to find the controller for path "%s". The route is wrongly configured.', $request->getPathInfo()));
  117. }
  118. $event = new FilterControllerEvent($this, $controller, $request, $type);
  119. $this->dispatcher->dispatch(KernelEvents::CONTROLLER, $event);
  120. $controller = $event->getController();
  121. // controller arguments
  122. $arguments = $this->argumentResolver->getArguments($request, $controller);
  123. $event = new FilterControllerArgumentsEvent($this, $controller, $arguments, $request, $type);
  124. $this->dispatcher->dispatch(KernelEvents::CONTROLLER_ARGUMENTS, $event);
  125. $controller = $event->getController();
  126. $arguments = $event->getArguments();
  127. // call controller
  128. $response = \call_user_func_array($controller, $arguments);
  129. // view
  130. if (!$response instanceof Response) {
  131. $event = new GetResponseForControllerResultEvent($this, $request, $type, $response);
  132. $this->dispatcher->dispatch(KernelEvents::VIEW, $event);
  133. if ($event->hasResponse()) {
  134. $response = $event->getResponse();
  135. }
  136. if (!$response instanceof Response) {
  137. $msg = sprintf('The controller must return a response (%s given).', $this->varToString($response));
  138. // the user may have forgotten to return something
  139. if (null === $response) {
  140. $msg .= ' Did you forget to add a return statement somewhere in your controller?';
  141. }
  142. throw new \LogicException($msg);
  143. }
  144. }
  145. return $this->filterResponse($response, $request, $type);
  146. }
  147. /**
  148. * Filters a response object.
  149. *
  150. * @param Response $response A Response instance
  151. * @param Request $request An error message in case the response is not a Response object
  152. * @param int $type The type of the request (one of HttpKernelInterface::MASTER_REQUEST or HttpKernelInterface::SUB_REQUEST)
  153. *
  154. * @return Response The filtered Response instance
  155. *
  156. * @throws \RuntimeException if the passed object is not a Response instance
  157. */
  158. private function filterResponse(Response $response, Request $request, $type)
  159. {
  160. $event = new FilterResponseEvent($this, $request, $type, $response);
  161. $this->dispatcher->dispatch(KernelEvents::RESPONSE, $event);
  162. $this->finishRequest($request, $type);
  163. return $event->getResponse();
  164. }
  165. /**
  166. * Publishes the finish request event, then pop the request from the stack.
  167. *
  168. * Note that the order of the operations is important here, otherwise
  169. * operations such as {@link RequestStack::getParentRequest()} can lead to
  170. * weird results.
  171. *
  172. * @param Request $request
  173. * @param int $type
  174. */
  175. private function finishRequest(Request $request, $type)
  176. {
  177. $this->dispatcher->dispatch(KernelEvents::FINISH_REQUEST, new FinishRequestEvent($this, $request, $type));
  178. $this->requestStack->pop();
  179. }
  180. /**
  181. * Handles an exception by trying to convert it to a Response.
  182. *
  183. * @param \Exception $e An \Exception instance
  184. * @param Request $request A Request instance
  185. * @param int $type The type of the request
  186. *
  187. * @return Response A Response instance
  188. *
  189. * @throws \Exception
  190. */
  191. private function handleException(\Exception $e, $request, $type)
  192. {
  193. $event = new GetResponseForExceptionEvent($this, $request, $type, $e);
  194. $this->dispatcher->dispatch(KernelEvents::EXCEPTION, $event);
  195. // a listener might have replaced the exception
  196. $e = $event->getException();
  197. if (!$event->hasResponse()) {
  198. $this->finishRequest($request, $type);
  199. throw $e;
  200. }
  201. $response = $event->getResponse();
  202. // the developer asked for a specific status code
  203. if ($response->headers->has('X-Status-Code')) {
  204. @trigger_error(sprintf('Using the X-Status-Code header is deprecated since Symfony 3.3 and will be removed in 4.0. Use %s::allowCustomResponseCode() instead.', GetResponseForExceptionEvent::class), E_USER_DEPRECATED);
  205. $response->setStatusCode($response->headers->get('X-Status-Code'));
  206. $response->headers->remove('X-Status-Code');
  207. } elseif (!$event->isAllowingCustomResponseCode() && !$response->isClientError() && !$response->isServerError() && !$response->isRedirect()) {
  208. // ensure that we actually have an error response
  209. if ($e instanceof HttpExceptionInterface) {
  210. // keep the HTTP status code and headers
  211. $response->setStatusCode($e->getStatusCode());
  212. $response->headers->add($e->getHeaders());
  213. } else {
  214. $response->setStatusCode(500);
  215. }
  216. }
  217. try {
  218. return $this->filterResponse($response, $request, $type);
  219. } catch (\Exception $e) {
  220. return $response;
  221. }
  222. }
  223. private function varToString($var)
  224. {
  225. if (\is_object($var)) {
  226. return sprintf('Object(%s)', \get_class($var));
  227. }
  228. if (\is_array($var)) {
  229. $a = array();
  230. foreach ($var as $k => $v) {
  231. $a[] = sprintf('%s => %s', $k, $this->varToString($v));
  232. }
  233. return sprintf('Array(%s)', implode(', ', $a));
  234. }
  235. if (\is_resource($var)) {
  236. return sprintf('Resource(%s)', get_resource_type($var));
  237. }
  238. if (null === $var) {
  239. return 'null';
  240. }
  241. if (false === $var) {
  242. return 'false';
  243. }
  244. if (true === $var) {
  245. return 'true';
  246. }
  247. return (string) $var;
  248. }
  249. }