HttpKernelTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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\Tests;
  11. use PHPUnit\Framework\TestCase;
  12. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  13. use Symfony\Component\HttpFoundation\RequestStack;
  14. use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface;
  15. use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
  16. use Symfony\Component\HttpKernel\Event\FilterControllerArgumentsEvent;
  17. use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
  18. use Symfony\Component\HttpKernel\HttpKernel;
  19. use Symfony\Component\HttpKernel\HttpKernelInterface;
  20. use Symfony\Component\HttpKernel\KernelEvents;
  21. use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
  22. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  23. use Symfony\Component\HttpFoundation\Request;
  24. use Symfony\Component\HttpFoundation\Response;
  25. use Symfony\Component\HttpFoundation\RedirectResponse;
  26. use Symfony\Component\EventDispatcher\EventDispatcher;
  27. class HttpKernelTest extends TestCase
  28. {
  29. /**
  30. * @expectedException \RuntimeException
  31. */
  32. public function testHandleWhenControllerThrowsAnExceptionAndCatchIsTrue()
  33. {
  34. $kernel = $this->getHttpKernel(new EventDispatcher(), function () { throw new \RuntimeException(); });
  35. $kernel->handle(new Request(), HttpKernelInterface::MASTER_REQUEST, true);
  36. }
  37. /**
  38. * @expectedException \RuntimeException
  39. */
  40. public function testHandleWhenControllerThrowsAnExceptionAndCatchIsFalseAndNoListenerIsRegistered()
  41. {
  42. $kernel = $this->getHttpKernel(new EventDispatcher(), function () { throw new \RuntimeException(); });
  43. $kernel->handle(new Request(), HttpKernelInterface::MASTER_REQUEST, false);
  44. }
  45. public function testHandleWhenControllerThrowsAnExceptionAndCatchIsTrueWithAHandlingListener()
  46. {
  47. $dispatcher = new EventDispatcher();
  48. $dispatcher->addListener(KernelEvents::EXCEPTION, function ($event) {
  49. $event->setResponse(new Response($event->getException()->getMessage()));
  50. });
  51. $kernel = $this->getHttpKernel($dispatcher, function () { throw new \RuntimeException('foo'); });
  52. $response = $kernel->handle(new Request(), HttpKernelInterface::MASTER_REQUEST, true);
  53. $this->assertEquals('500', $response->getStatusCode());
  54. $this->assertEquals('foo', $response->getContent());
  55. }
  56. public function testHandleWhenControllerThrowsAnExceptionAndCatchIsTrueWithANonHandlingListener()
  57. {
  58. $exception = new \RuntimeException();
  59. $dispatcher = new EventDispatcher();
  60. $dispatcher->addListener(KernelEvents::EXCEPTION, function ($event) {
  61. // should set a response, but does not
  62. });
  63. $kernel = $this->getHttpKernel($dispatcher, function () use ($exception) { throw $exception; });
  64. try {
  65. $kernel->handle(new Request(), HttpKernelInterface::MASTER_REQUEST, true);
  66. $this->fail('LogicException expected');
  67. } catch (\RuntimeException $e) {
  68. $this->assertSame($exception, $e);
  69. }
  70. }
  71. public function testHandleExceptionWithARedirectionResponse()
  72. {
  73. $dispatcher = new EventDispatcher();
  74. $dispatcher->addListener(KernelEvents::EXCEPTION, function ($event) {
  75. $event->setResponse(new RedirectResponse('/login', 301));
  76. });
  77. $kernel = $this->getHttpKernel($dispatcher, function () { throw new AccessDeniedHttpException(); });
  78. $response = $kernel->handle(new Request());
  79. $this->assertEquals('301', $response->getStatusCode());
  80. $this->assertEquals('/login', $response->headers->get('Location'));
  81. }
  82. public function testHandleHttpException()
  83. {
  84. $dispatcher = new EventDispatcher();
  85. $dispatcher->addListener(KernelEvents::EXCEPTION, function ($event) {
  86. $event->setResponse(new Response($event->getException()->getMessage()));
  87. });
  88. $kernel = $this->getHttpKernel($dispatcher, function () { throw new MethodNotAllowedHttpException(array('POST')); });
  89. $response = $kernel->handle(new Request());
  90. $this->assertEquals('405', $response->getStatusCode());
  91. $this->assertEquals('POST', $response->headers->get('Allow'));
  92. }
  93. /**
  94. * @group legacy
  95. * @dataProvider getStatusCodes
  96. */
  97. public function testLegacyHandleWhenAnExceptionIsHandledWithASpecificStatusCode($responseStatusCode, $expectedStatusCode)
  98. {
  99. $dispatcher = new EventDispatcher();
  100. $dispatcher->addListener(KernelEvents::EXCEPTION, function ($event) use ($responseStatusCode, $expectedStatusCode) {
  101. $event->setResponse(new Response('', $responseStatusCode, array('X-Status-Code' => $expectedStatusCode)));
  102. });
  103. $kernel = $this->getHttpKernel($dispatcher, function () { throw new \RuntimeException(); });
  104. $response = $kernel->handle(new Request());
  105. $this->assertEquals($expectedStatusCode, $response->getStatusCode());
  106. $this->assertFalse($response->headers->has('X-Status-Code'));
  107. }
  108. public function getStatusCodes()
  109. {
  110. return array(
  111. array(200, 404),
  112. array(404, 200),
  113. array(301, 200),
  114. array(500, 200),
  115. );
  116. }
  117. /**
  118. * @dataProvider getSpecificStatusCodes
  119. */
  120. public function testHandleWhenAnExceptionIsHandledWithASpecificStatusCode($expectedStatusCode)
  121. {
  122. $dispatcher = new EventDispatcher();
  123. $dispatcher->addListener(KernelEvents::EXCEPTION, function (GetResponseForExceptionEvent $event) use ($expectedStatusCode) {
  124. $event->allowCustomResponseCode();
  125. $event->setResponse(new Response('', $expectedStatusCode));
  126. });
  127. $kernel = $this->getHttpKernel($dispatcher, function () { throw new \RuntimeException(); });
  128. $response = $kernel->handle(new Request());
  129. $this->assertEquals($expectedStatusCode, $response->getStatusCode());
  130. }
  131. public function getSpecificStatusCodes()
  132. {
  133. return array(
  134. array(200),
  135. array(302),
  136. array(403),
  137. );
  138. }
  139. public function testHandleWhenAListenerReturnsAResponse()
  140. {
  141. $dispatcher = new EventDispatcher();
  142. $dispatcher->addListener(KernelEvents::REQUEST, function ($event) {
  143. $event->setResponse(new Response('hello'));
  144. });
  145. $kernel = $this->getHttpKernel($dispatcher);
  146. $this->assertEquals('hello', $kernel->handle(new Request())->getContent());
  147. }
  148. /**
  149. * @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  150. */
  151. public function testHandleWhenNoControllerIsFound()
  152. {
  153. $dispatcher = new EventDispatcher();
  154. $kernel = $this->getHttpKernel($dispatcher, false);
  155. $kernel->handle(new Request());
  156. }
  157. public function testHandleWhenTheControllerIsAClosure()
  158. {
  159. $response = new Response('foo');
  160. $dispatcher = new EventDispatcher();
  161. $kernel = $this->getHttpKernel($dispatcher, function () use ($response) { return $response; });
  162. $this->assertSame($response, $kernel->handle(new Request()));
  163. }
  164. public function testHandleWhenTheControllerIsAnObjectWithInvoke()
  165. {
  166. $dispatcher = new EventDispatcher();
  167. $kernel = $this->getHttpKernel($dispatcher, new Controller());
  168. $this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
  169. }
  170. public function testHandleWhenTheControllerIsAFunction()
  171. {
  172. $dispatcher = new EventDispatcher();
  173. $kernel = $this->getHttpKernel($dispatcher, 'Symfony\Component\HttpKernel\Tests\controller_func');
  174. $this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
  175. }
  176. public function testHandleWhenTheControllerIsAnArray()
  177. {
  178. $dispatcher = new EventDispatcher();
  179. $kernel = $this->getHttpKernel($dispatcher, array(new Controller(), 'controller'));
  180. $this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
  181. }
  182. public function testHandleWhenTheControllerIsAStaticArray()
  183. {
  184. $dispatcher = new EventDispatcher();
  185. $kernel = $this->getHttpKernel($dispatcher, array('Symfony\Component\HttpKernel\Tests\Controller', 'staticcontroller'));
  186. $this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
  187. }
  188. /**
  189. * @expectedException \LogicException
  190. */
  191. public function testHandleWhenTheControllerDoesNotReturnAResponse()
  192. {
  193. $dispatcher = new EventDispatcher();
  194. $kernel = $this->getHttpKernel($dispatcher, function () { return 'foo'; });
  195. $kernel->handle(new Request());
  196. }
  197. public function testHandleWhenTheControllerDoesNotReturnAResponseButAViewIsRegistered()
  198. {
  199. $dispatcher = new EventDispatcher();
  200. $dispatcher->addListener(KernelEvents::VIEW, function ($event) {
  201. $event->setResponse(new Response($event->getControllerResult()));
  202. });
  203. $kernel = $this->getHttpKernel($dispatcher, function () { return 'foo'; });
  204. $this->assertEquals('foo', $kernel->handle(new Request())->getContent());
  205. }
  206. public function testHandleWithAResponseListener()
  207. {
  208. $dispatcher = new EventDispatcher();
  209. $dispatcher->addListener(KernelEvents::RESPONSE, function ($event) {
  210. $event->setResponse(new Response('foo'));
  211. });
  212. $kernel = $this->getHttpKernel($dispatcher);
  213. $this->assertEquals('foo', $kernel->handle(new Request())->getContent());
  214. }
  215. public function testHandleAllowChangingControllerArguments()
  216. {
  217. $dispatcher = new EventDispatcher();
  218. $dispatcher->addListener(KernelEvents::CONTROLLER_ARGUMENTS, function (FilterControllerArgumentsEvent $event) {
  219. $event->setArguments(array('foo'));
  220. });
  221. $kernel = $this->getHttpKernel($dispatcher, function ($content) { return new Response($content); });
  222. $this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
  223. }
  224. public function testHandleAllowChangingControllerAndArguments()
  225. {
  226. $dispatcher = new EventDispatcher();
  227. $dispatcher->addListener(KernelEvents::CONTROLLER_ARGUMENTS, function (FilterControllerArgumentsEvent $event) {
  228. $oldController = $event->getController();
  229. $oldArguments = $event->getArguments();
  230. $newController = function ($id) use ($oldController, $oldArguments) {
  231. $response = call_user_func_array($oldController, $oldArguments);
  232. $response->headers->set('X-Id', $id);
  233. return $response;
  234. };
  235. $event->setController($newController);
  236. $event->setArguments(array('bar'));
  237. });
  238. $kernel = $this->getHttpKernel($dispatcher, function ($content) { return new Response($content); }, null, array('foo'));
  239. $this->assertResponseEquals(new Response('foo', 200, array('X-Id' => 'bar')), $kernel->handle(new Request()));
  240. }
  241. public function testTerminate()
  242. {
  243. $dispatcher = new EventDispatcher();
  244. $kernel = $this->getHttpKernel($dispatcher);
  245. $dispatcher->addListener(KernelEvents::TERMINATE, function ($event) use (&$called, &$capturedKernel, &$capturedRequest, &$capturedResponse) {
  246. $called = true;
  247. $capturedKernel = $event->getKernel();
  248. $capturedRequest = $event->getRequest();
  249. $capturedResponse = $event->getResponse();
  250. });
  251. $kernel->terminate($request = Request::create('/'), $response = new Response());
  252. $this->assertTrue($called);
  253. $this->assertEquals($kernel, $capturedKernel);
  254. $this->assertEquals($request, $capturedRequest);
  255. $this->assertEquals($response, $capturedResponse);
  256. }
  257. public function testVerifyRequestStackPushPopDuringHandle()
  258. {
  259. $request = new Request();
  260. $stack = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestStack')->setMethods(array('push', 'pop'))->getMock();
  261. $stack->expects($this->at(0))->method('push')->with($this->equalTo($request));
  262. $stack->expects($this->at(1))->method('pop');
  263. $dispatcher = new EventDispatcher();
  264. $kernel = $this->getHttpKernel($dispatcher, null, $stack);
  265. $kernel->handle($request, HttpKernelInterface::MASTER_REQUEST);
  266. }
  267. /**
  268. * @expectedException \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
  269. */
  270. public function testInconsistentClientIpsOnMasterRequests()
  271. {
  272. $request = new Request();
  273. $request->setTrustedProxies(array('1.1.1.1'), Request::HEADER_X_FORWARDED_FOR | Request::HEADER_FORWARDED);
  274. $request->server->set('REMOTE_ADDR', '1.1.1.1');
  275. $request->headers->set('FORWARDED', 'for=2.2.2.2');
  276. $request->headers->set('X_FORWARDED_FOR', '3.3.3.3');
  277. $dispatcher = new EventDispatcher();
  278. $dispatcher->addListener(KernelEvents::REQUEST, function ($event) {
  279. $event->getRequest()->getClientIp();
  280. });
  281. $kernel = $this->getHttpKernel($dispatcher);
  282. $kernel->handle($request, $kernel::MASTER_REQUEST, false);
  283. }
  284. private function getHttpKernel(EventDispatcherInterface $eventDispatcher, $controller = null, RequestStack $requestStack = null, array $arguments = array())
  285. {
  286. if (null === $controller) {
  287. $controller = function () { return new Response('Hello'); };
  288. }
  289. $controllerResolver = $this->getMockBuilder(ControllerResolverInterface::class)->getMock();
  290. $controllerResolver
  291. ->expects($this->any())
  292. ->method('getController')
  293. ->will($this->returnValue($controller));
  294. $argumentResolver = $this->getMockBuilder(ArgumentResolverInterface::class)->getMock();
  295. $argumentResolver
  296. ->expects($this->any())
  297. ->method('getArguments')
  298. ->will($this->returnValue($arguments));
  299. return new HttpKernel($eventDispatcher, $controllerResolver, $requestStack, $argumentResolver);
  300. }
  301. private function assertResponseEquals(Response $expected, Response $actual)
  302. {
  303. $expected->setDate($actual->getDate());
  304. $this->assertEquals($expected, $actual);
  305. }
  306. }
  307. class Controller
  308. {
  309. public function __invoke()
  310. {
  311. return new Response('foo');
  312. }
  313. public function controller()
  314. {
  315. return new Response('foo');
  316. }
  317. public static function staticController()
  318. {
  319. return new Response('foo');
  320. }
  321. }
  322. function controller_func()
  323. {
  324. return new Response('foo');
  325. }