설명 없음

HttpKernel.php 10KB

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