Brak opisu

HttpKernel.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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\ArgumentResolver;
  12. use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface;
  13. use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
  14. use Symfony\Component\HttpKernel\Event\FilterControllerArgumentsEvent;
  15. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  16. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  17. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  18. use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
  19. use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
  20. use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
  21. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  22. use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
  23. use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
  24. use Symfony\Component\HttpKernel\Event\PostResponseEvent;
  25. use Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException;
  26. use Symfony\Component\HttpFoundation\Request;
  27. use Symfony\Component\HttpFoundation\RequestStack;
  28. use Symfony\Component\HttpFoundation\Response;
  29. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  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 ConflictingHeadersException) {
  63. $e = new BadRequestHttpException('The request headers contain conflicting information regarding the origin of this request.', $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. * @throws \LogicException If the request stack is empty
  81. *
  82. * @internal
  83. */
  84. public function terminateWithException(\Exception $exception)
  85. {
  86. if (!$request = $this->requestStack->getMasterRequest()) {
  87. throw new \LogicException('Request stack is empty', 0, $exception);
  88. }
  89. $response = $this->handleException($exception, $request, self::MASTER_REQUEST);
  90. $response->sendHeaders();
  91. $response->sendContent();
  92. $this->terminate($request, $response);
  93. }
  94. /**
  95. * Handles a request to convert it to a response.
  96. *
  97. * Exceptions are not caught.
  98. *
  99. * @param Request $request A Request instance
  100. * @param int $type The type of the request (one of HttpKernelInterface::MASTER_REQUEST or HttpKernelInterface::SUB_REQUEST)
  101. *
  102. * @return Response A Response instance
  103. *
  104. * @throws \LogicException If one of the listener does not behave as expected
  105. * @throws NotFoundHttpException When controller cannot be found
  106. */
  107. private function handleRaw(Request $request, $type = self::MASTER_REQUEST)
  108. {
  109. $this->requestStack->push($request);
  110. // request
  111. $event = new GetResponseEvent($this, $request, $type);
  112. $this->dispatcher->dispatch(KernelEvents::REQUEST, $event);
  113. if ($event->hasResponse()) {
  114. return $this->filterResponse($event->getResponse(), $request, $type);
  115. }
  116. // load controller
  117. if (false === $controller = $this->resolver->getController($request)) {
  118. throw new NotFoundHttpException(sprintf('Unable to find the controller for path "%s". The route is wrongly configured.', $request->getPathInfo()));
  119. }
  120. $event = new FilterControllerEvent($this, $controller, $request, $type);
  121. $this->dispatcher->dispatch(KernelEvents::CONTROLLER, $event);
  122. $controller = $event->getController();
  123. // controller arguments
  124. $arguments = $this->argumentResolver->getArguments($request, $controller);
  125. $event = new FilterControllerArgumentsEvent($this, $controller, $arguments, $request, $type);
  126. $this->dispatcher->dispatch(KernelEvents::CONTROLLER_ARGUMENTS, $event);
  127. $controller = $event->getController();
  128. $arguments = $event->getArguments();
  129. // call controller
  130. $response = call_user_func_array($controller, $arguments);
  131. // view
  132. if (!$response instanceof Response) {
  133. $event = new GetResponseForControllerResultEvent($this, $request, $type, $response);
  134. $this->dispatcher->dispatch(KernelEvents::VIEW, $event);
  135. if ($event->hasResponse()) {
  136. $response = $event->getResponse();
  137. }
  138. if (!$response instanceof Response) {
  139. $msg = sprintf('The controller must return a response (%s given).', $this->varToString($response));
  140. // the user may have forgotten to return something
  141. if (null === $response) {
  142. $msg .= ' Did you forget to add a return statement somewhere in your controller?';
  143. }
  144. throw new \LogicException($msg);
  145. }
  146. }
  147. return $this->filterResponse($response, $request, $type);
  148. }
  149. /**
  150. * Filters a response object.
  151. *
  152. * @param Response $response A Response instance
  153. * @param Request $request An error message in case the response is not a Response object
  154. * @param int $type The type of the request (one of HttpKernelInterface::MASTER_REQUEST or HttpKernelInterface::SUB_REQUEST)
  155. *
  156. * @return Response The filtered Response instance
  157. *
  158. * @throws \RuntimeException if the passed object is not a Response instance
  159. */
  160. private function filterResponse(Response $response, Request $request, $type)
  161. {
  162. $event = new FilterResponseEvent($this, $request, $type, $response);
  163. $this->dispatcher->dispatch(KernelEvents::RESPONSE, $event);
  164. $this->finishRequest($request, $type);
  165. return $event->getResponse();
  166. }
  167. /**
  168. * Publishes the finish request event, then pop the request from the stack.
  169. *
  170. * Note that the order of the operations is important here, otherwise
  171. * operations such as {@link RequestStack::getParentRequest()} can lead to
  172. * weird results.
  173. *
  174. * @param Request $request
  175. * @param int $type
  176. */
  177. private function finishRequest(Request $request, $type)
  178. {
  179. $this->dispatcher->dispatch(KernelEvents::FINISH_REQUEST, new FinishRequestEvent($this, $request, $type));
  180. $this->requestStack->pop();
  181. }
  182. /**
  183. * Handles an exception by trying to convert it to a Response.
  184. *
  185. * @param \Exception $e An \Exception instance
  186. * @param Request $request A Request instance
  187. * @param int $type The type of the request
  188. *
  189. * @return Response A Response instance
  190. *
  191. * @throws \Exception
  192. */
  193. private function handleException(\Exception $e, $request, $type)
  194. {
  195. $event = new GetResponseForExceptionEvent($this, $request, $type, $e);
  196. $this->dispatcher->dispatch(KernelEvents::EXCEPTION, $event);
  197. // a listener might have replaced the exception
  198. $e = $event->getException();
  199. if (!$event->hasResponse()) {
  200. $this->finishRequest($request, $type);
  201. throw $e;
  202. }
  203. $response = $event->getResponse();
  204. // the developer asked for a specific status code
  205. if ($response->headers->has('X-Status-Code')) {
  206. $response->setStatusCode($response->headers->get('X-Status-Code'));
  207. $response->headers->remove('X-Status-Code');
  208. } elseif (!$response->isClientError() && !$response->isServerError() && !$response->isRedirect()) {
  209. // ensure that we actually have an error response
  210. if ($e instanceof HttpExceptionInterface) {
  211. // keep the HTTP status code and headers
  212. $response->setStatusCode($e->getStatusCode());
  213. $response->headers->add($e->getHeaders());
  214. } else {
  215. $response->setStatusCode(500);
  216. }
  217. }
  218. try {
  219. return $this->filterResponse($response, $request, $type);
  220. } catch (\Exception $e) {
  221. return $response;
  222. }
  223. }
  224. private function varToString($var)
  225. {
  226. if (is_object($var)) {
  227. return sprintf('Object(%s)', get_class($var));
  228. }
  229. if (is_array($var)) {
  230. $a = array();
  231. foreach ($var as $k => $v) {
  232. $a[] = sprintf('%s => %s', $k, $this->varToString($v));
  233. }
  234. return sprintf('Array(%s)', implode(', ', $a));
  235. }
  236. if (is_resource($var)) {
  237. return sprintf('Resource(%s)', get_resource_type($var));
  238. }
  239. if (null === $var) {
  240. return 'null';
  241. }
  242. if (false === $var) {
  243. return 'false';
  244. }
  245. if (true === $var) {
  246. return 'true';
  247. }
  248. return (string) $var;
  249. }
  250. }