HttpKernelTest.php 14 KB

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