Dashboard sipadu mbip
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

HttpKernelTest.php 14KB

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