4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpKernel;
14 use Symfony\Component\EventDispatcher\EventDispatcherInterface;
15 use Symfony\Component\HttpFoundation\Exception\RequestExceptionInterface;
16 use Symfony\Component\HttpFoundation\Request;
17 use Symfony\Component\HttpFoundation\RequestStack;
18 use Symfony\Component\HttpFoundation\Response;
19 use Symfony\Component\HttpKernel\Controller\ArgumentResolver;
20 use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface;
21 use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
22 use Symfony\Component\HttpKernel\Event\FilterControllerArgumentsEvent;
23 use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
24 use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
25 use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
26 use Symfony\Component\HttpKernel\Event\GetResponseEvent;
27 use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
28 use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
29 use Symfony\Component\HttpKernel\Event\PostResponseEvent;
30 use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
31 use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
32 use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
35 * HttpKernel notifies events to convert a Request object to a Response one.
37 * @author Fabien Potencier <fabien@symfony.com>
39 class HttpKernel implements HttpKernelInterface, TerminableInterface
41 protected $dispatcher;
43 protected $requestStack;
44 private $argumentResolver;
46 public function __construct(EventDispatcherInterface $dispatcher, ControllerResolverInterface $resolver, RequestStack $requestStack = null, ArgumentResolverInterface $argumentResolver = null)
48 $this->dispatcher = $dispatcher;
49 $this->resolver = $resolver;
50 $this->requestStack = $requestStack ?: new RequestStack();
51 $this->argumentResolver = $argumentResolver;
53 if (null === $this->argumentResolver) {
54 @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);
55 // fallback in case of deprecations
56 $this->argumentResolver = $resolver;
63 public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
65 $request->headers->set('X-Php-Ob-Level', ob_get_level());
68 return $this->handleRaw($request, $type);
69 } catch (\Exception $e) {
70 if ($e instanceof RequestExceptionInterface) {
71 $e = new BadRequestHttpException($e->getMessage(), $e);
73 if (false === $catch) {
74 $this->finishRequest($request, $type);
79 return $this->handleException($e, $request, $type);
86 public function terminate(Request $request, Response $response)
88 $this->dispatcher->dispatch(KernelEvents::TERMINATE, new PostResponseEvent($this, $request, $response));
94 public function terminateWithException(\Exception $exception, Request $request = null)
96 if (!$request = $request ?: $this->requestStack->getMasterRequest()) {
100 $response = $this->handleException($exception, $request, self::MASTER_REQUEST);
102 $response->sendHeaders();
103 $response->sendContent();
105 $this->terminate($request, $response);
109 * Handles a request to convert it to a response.
111 * Exceptions are not caught.
113 * @param Request $request A Request instance
114 * @param int $type The type of the request (one of HttpKernelInterface::MASTER_REQUEST or HttpKernelInterface::SUB_REQUEST)
116 * @return Response A Response instance
118 * @throws \LogicException If one of the listener does not behave as expected
119 * @throws NotFoundHttpException When controller cannot be found
121 private function handleRaw(Request $request, $type = self::MASTER_REQUEST)
123 $this->requestStack->push($request);
126 $event = new GetResponseEvent($this, $request, $type);
127 $this->dispatcher->dispatch(KernelEvents::REQUEST, $event);
129 if ($event->hasResponse()) {
130 return $this->filterResponse($event->getResponse(), $request, $type);
134 if (false === $controller = $this->resolver->getController($request)) {
135 throw new NotFoundHttpException(sprintf('Unable to find the controller for path "%s". The route is wrongly configured.', $request->getPathInfo()));
138 $event = new FilterControllerEvent($this, $controller, $request, $type);
139 $this->dispatcher->dispatch(KernelEvents::CONTROLLER, $event);
140 $controller = $event->getController();
142 // controller arguments
143 $arguments = $this->argumentResolver->getArguments($request, $controller);
145 $event = new FilterControllerArgumentsEvent($this, $controller, $arguments, $request, $type);
146 $this->dispatcher->dispatch(KernelEvents::CONTROLLER_ARGUMENTS, $event);
147 $controller = $event->getController();
148 $arguments = $event->getArguments();
151 $response = \call_user_func_array($controller, $arguments);
154 if (!$response instanceof Response) {
155 $event = new GetResponseForControllerResultEvent($this, $request, $type, $response);
156 $this->dispatcher->dispatch(KernelEvents::VIEW, $event);
158 if ($event->hasResponse()) {
159 $response = $event->getResponse();
162 if (!$response instanceof Response) {
163 $msg = sprintf('The controller must return a response (%s given).', $this->varToString($response));
165 // the user may have forgotten to return something
166 if (null === $response) {
167 $msg .= ' Did you forget to add a return statement somewhere in your controller?';
169 throw new \LogicException($msg);
173 return $this->filterResponse($response, $request, $type);
177 * Filters a response object.
179 * @param Response $response A Response instance
180 * @param Request $request An error message in case the response is not a Response object
181 * @param int $type The type of the request (one of HttpKernelInterface::MASTER_REQUEST or HttpKernelInterface::SUB_REQUEST)
183 * @return Response The filtered Response instance
185 * @throws \RuntimeException if the passed object is not a Response instance
187 private function filterResponse(Response $response, Request $request, $type)
189 $event = new FilterResponseEvent($this, $request, $type, $response);
191 $this->dispatcher->dispatch(KernelEvents::RESPONSE, $event);
193 $this->finishRequest($request, $type);
195 return $event->getResponse();
199 * Publishes the finish request event, then pop the request from the stack.
201 * Note that the order of the operations is important here, otherwise
202 * operations such as {@link RequestStack::getParentRequest()} can lead to
205 * @param Request $request
208 private function finishRequest(Request $request, $type)
210 $this->dispatcher->dispatch(KernelEvents::FINISH_REQUEST, new FinishRequestEvent($this, $request, $type));
211 $this->requestStack->pop();
215 * Handles an exception by trying to convert it to a Response.
217 * @param \Exception $e An \Exception instance
218 * @param Request $request A Request instance
219 * @param int $type The type of the request
221 * @return Response A Response instance
225 private function handleException(\Exception $e, $request, $type)
227 $event = new GetResponseForExceptionEvent($this, $request, $type, $e);
228 $this->dispatcher->dispatch(KernelEvents::EXCEPTION, $event);
230 // a listener might have replaced the exception
231 $e = $event->getException();
233 if (!$event->hasResponse()) {
234 $this->finishRequest($request, $type);
239 $response = $event->getResponse();
241 // the developer asked for a specific status code
242 if ($response->headers->has('X-Status-Code')) {
243 @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);
245 $response->setStatusCode($response->headers->get('X-Status-Code'));
247 $response->headers->remove('X-Status-Code');
248 } elseif (!$event->isAllowingCustomResponseCode() && !$response->isClientError() && !$response->isServerError() && !$response->isRedirect()) {
249 // ensure that we actually have an error response
250 if ($e instanceof HttpExceptionInterface) {
251 // keep the HTTP status code and headers
252 $response->setStatusCode($e->getStatusCode());
253 $response->headers->add($e->getHeaders());
255 $response->setStatusCode(500);
260 return $this->filterResponse($response, $request, $type);
261 } catch (\Exception $e) {
266 private function varToString($var)
268 if (\is_object($var)) {
269 return sprintf('Object(%s)', \get_class($var));
272 if (\is_array($var)) {
274 foreach ($var as $k => $v) {
275 $a[] = sprintf('%s => %s', $k, $this->varToString($v));
278 return sprintf('Array(%s)', implode(', ', $a));
281 if (\is_resource($var)) {
282 return sprintf('Resource(%s)', get_resource_type($var));
289 if (false === $var) {
297 return (string) $var;