HttpKernelTest.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. public function getStatusCodes()
  94. {
  95. return array(
  96. array(200, 404),
  97. array(404, 200),
  98. array(301, 200),
  99. array(500, 200),
  100. );
  101. }
  102. /**
  103. * @dataProvider getSpecificStatusCodes
  104. */
  105. public function testHandleWhenAnExceptionIsHandledWithASpecificStatusCode($expectedStatusCode)
  106. {
  107. $dispatcher = new EventDispatcher();
  108. $dispatcher->addListener(KernelEvents::EXCEPTION, function (GetResponseForExceptionEvent $event) use ($expectedStatusCode) {
  109. $event->allowCustomResponseCode();
  110. $event->setResponse(new Response('', $expectedStatusCode));
  111. });
  112. $kernel = $this->getHttpKernel($dispatcher, function () { throw new \RuntimeException(); });
  113. $response = $kernel->handle(new Request());
  114. $this->assertEquals($expectedStatusCode, $response->getStatusCode());
  115. }
  116. public function getSpecificStatusCodes()
  117. {
  118. return array(
  119. array(200),
  120. array(302),
  121. array(403),
  122. );
  123. }
  124. public function testHandleWhenAListenerReturnsAResponse()
  125. {
  126. $dispatcher = new EventDispatcher();
  127. $dispatcher->addListener(KernelEvents::REQUEST, function ($event) {
  128. $event->setResponse(new Response('hello'));
  129. });
  130. $kernel = $this->getHttpKernel($dispatcher);
  131. $this->assertEquals('hello', $kernel->handle(new Request())->getContent());
  132. }
  133. /**
  134. * @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  135. */
  136. public function testHandleWhenNoControllerIsFound()
  137. {
  138. $dispatcher = new EventDispatcher();
  139. $kernel = $this->getHttpKernel($dispatcher, false);
  140. $kernel->handle(new Request());
  141. }
  142. public function testHandleWhenTheControllerIsAClosure()
  143. {
  144. $response = new Response('foo');
  145. $dispatcher = new EventDispatcher();
  146. $kernel = $this->getHttpKernel($dispatcher, function () use ($response) { return $response; });
  147. $this->assertSame($response, $kernel->handle(new Request()));
  148. }
  149. public function testHandleWhenTheControllerIsAnObjectWithInvoke()
  150. {
  151. $dispatcher = new EventDispatcher();
  152. $kernel = $this->getHttpKernel($dispatcher, new Controller());
  153. $this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
  154. }
  155. public function testHandleWhenTheControllerIsAFunction()
  156. {
  157. $dispatcher = new EventDispatcher();
  158. $kernel = $this->getHttpKernel($dispatcher, 'Symfony\Component\HttpKernel\Tests\controller_func');
  159. $this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
  160. }
  161. public function testHandleWhenTheControllerIsAnArray()
  162. {
  163. $dispatcher = new EventDispatcher();
  164. $kernel = $this->getHttpKernel($dispatcher, array(new Controller(), 'controller'));
  165. $this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
  166. }
  167. public function testHandleWhenTheControllerIsAStaticArray()
  168. {
  169. $dispatcher = new EventDispatcher();
  170. $kernel = $this->getHttpKernel($dispatcher, array('Symfony\Component\HttpKernel\Tests\Controller', 'staticcontroller'));
  171. $this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
  172. }
  173. /**
  174. * @expectedException \LogicException
  175. */
  176. public function testHandleWhenTheControllerDoesNotReturnAResponse()
  177. {
  178. $dispatcher = new EventDispatcher();
  179. $kernel = $this->getHttpKernel($dispatcher, function () { return 'foo'; });
  180. $kernel->handle(new Request());
  181. }
  182. public function testHandleWhenTheControllerDoesNotReturnAResponseButAViewIsRegistered()
  183. {
  184. $dispatcher = new EventDispatcher();
  185. $dispatcher->addListener(KernelEvents::VIEW, function ($event) {
  186. $event->setResponse(new Response($event->getControllerResult()));
  187. });
  188. $kernel = $this->getHttpKernel($dispatcher, function () { return 'foo'; });
  189. $this->assertEquals('foo', $kernel->handle(new Request())->getContent());
  190. }
  191. public function testHandleWithAResponseListener()
  192. {
  193. $dispatcher = new EventDispatcher();
  194. $dispatcher->addListener(KernelEvents::RESPONSE, function ($event) {
  195. $event->setResponse(new Response('foo'));
  196. });
  197. $kernel = $this->getHttpKernel($dispatcher);
  198. $this->assertEquals('foo', $kernel->handle(new Request())->getContent());
  199. }
  200. public function testHandleAllowChangingControllerArguments()
  201. {
  202. $dispatcher = new EventDispatcher();
  203. $dispatcher->addListener(KernelEvents::CONTROLLER_ARGUMENTS, function (FilterControllerArgumentsEvent $event) {
  204. $event->setArguments(array('foo'));
  205. });
  206. $kernel = $this->getHttpKernel($dispatcher, function ($content) { return new Response($content); });
  207. $this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
  208. }
  209. public function testHandleAllowChangingControllerAndArguments()
  210. {
  211. $dispatcher = new EventDispatcher();
  212. $dispatcher->addListener(KernelEvents::CONTROLLER_ARGUMENTS, function (FilterControllerArgumentsEvent $event) {
  213. $oldController = $event->getController();
  214. $oldArguments = $event->getArguments();
  215. $newController = function ($id) use ($oldController, $oldArguments) {
  216. $response = call_user_func_array($oldController, $oldArguments);
  217. $response->headers->set('X-Id', $id);
  218. return $response;
  219. };
  220. $event->setController($newController);
  221. $event->setArguments(array('bar'));
  222. });
  223. $kernel = $this->getHttpKernel($dispatcher, function ($content) { return new Response($content); }, null, array('foo'));
  224. $this->assertResponseEquals(new Response('foo', 200, array('X-Id' => 'bar')), $kernel->handle(new Request()));
  225. }
  226. public function testTerminate()
  227. {
  228. $dispatcher = new EventDispatcher();
  229. $kernel = $this->getHttpKernel($dispatcher);
  230. $dispatcher->addListener(KernelEvents::TERMINATE, function ($event) use (&$called, &$capturedKernel, &$capturedRequest, &$capturedResponse) {
  231. $called = true;
  232. $capturedKernel = $event->getKernel();
  233. $capturedRequest = $event->getRequest();
  234. $capturedResponse = $event->getResponse();
  235. });
  236. $kernel->terminate($request = Request::create('/'), $response = new Response());
  237. $this->assertTrue($called);
  238. $this->assertEquals($kernel, $capturedKernel);
  239. $this->assertEquals($request, $capturedRequest);
  240. $this->assertEquals($response, $capturedResponse);
  241. }
  242. public function testVerifyRequestStackPushPopDuringHandle()
  243. {
  244. $request = new Request();
  245. $stack = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestStack')->setMethods(array('push', 'pop'))->getMock();
  246. $stack->expects($this->at(0))->method('push')->with($this->equalTo($request));
  247. $stack->expects($this->at(1))->method('pop');
  248. $dispatcher = new EventDispatcher();
  249. $kernel = $this->getHttpKernel($dispatcher, null, $stack);
  250. $kernel->handle($request, HttpKernelInterface::MASTER_REQUEST);
  251. }
  252. /**
  253. * @expectedException \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
  254. */
  255. public function testInconsistentClientIpsOnMasterRequests()
  256. {
  257. $request = new Request();
  258. $request->setTrustedProxies(array('1.1.1.1'), Request::HEADER_X_FORWARDED_FOR | Request::HEADER_FORWARDED);
  259. $request->server->set('REMOTE_ADDR', '1.1.1.1');
  260. $request->headers->set('FORWARDED', 'for=2.2.2.2');
  261. $request->headers->set('X_FORWARDED_FOR', '3.3.3.3');
  262. $dispatcher = new EventDispatcher();
  263. $dispatcher->addListener(KernelEvents::REQUEST, function ($event) {
  264. $event->getRequest()->getClientIp();
  265. });
  266. $kernel = $this->getHttpKernel($dispatcher);
  267. $kernel->handle($request, $kernel::MASTER_REQUEST, false);
  268. }
  269. private function getHttpKernel(EventDispatcherInterface $eventDispatcher, $controller = null, RequestStack $requestStack = null, array $arguments = array())
  270. {
  271. if (null === $controller) {
  272. $controller = function () { return new Response('Hello'); };
  273. }
  274. $controllerResolver = $this->getMockBuilder(ControllerResolverInterface::class)->getMock();
  275. $controllerResolver
  276. ->expects($this->any())
  277. ->method('getController')
  278. ->will($this->returnValue($controller));
  279. $argumentResolver = $this->getMockBuilder(ArgumentResolverInterface::class)->getMock();
  280. $argumentResolver
  281. ->expects($this->any())
  282. ->method('getArguments')
  283. ->will($this->returnValue($arguments));
  284. return new HttpKernel($eventDispatcher, $controllerResolver, $requestStack, $argumentResolver);
  285. }
  286. private function assertResponseEquals(Response $expected, Response $actual)
  287. {
  288. $expected->setDate($actual->getDate());
  289. $this->assertEquals($expected, $actual);
  290. }
  291. }
  292. class Controller
  293. {
  294. public function __invoke()
  295. {
  296. return new Response('foo');
  297. }
  298. public function controller()
  299. {
  300. return new Response('foo');
  301. }
  302. public static function staticController()
  303. {
  304. return new Response('foo');
  305. }
  306. }
  307. function controller_func()
  308. {
  309. return new Response('foo');
  310. }