RequestDataCollectorTest.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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\DataCollector;
  11. use PHPUnit\Framework\TestCase;
  12. use Symfony\Component\EventDispatcher\EventDispatcher;
  13. use Symfony\Component\HttpFoundation\Cookie;
  14. use Symfony\Component\HttpFoundation\ParameterBag;
  15. use Symfony\Component\HttpFoundation\RedirectResponse;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\HttpFoundation\Response;
  18. use Symfony\Component\HttpFoundation\Session\Session;
  19. use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
  20. use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface;
  21. use Symfony\Component\HttpKernel\DataCollector\RequestDataCollector;
  22. use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
  23. use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
  24. use Symfony\Component\HttpKernel\HttpKernel;
  25. use Symfony\Component\HttpKernel\HttpKernelInterface;
  26. class RequestDataCollectorTest extends TestCase
  27. {
  28. public function testCollect()
  29. {
  30. $c = new RequestDataCollector();
  31. $c->collect($request = $this->createRequest(), $this->createResponse());
  32. $c->lateCollect();
  33. $attributes = $c->getRequestAttributes();
  34. $this->assertSame('request', $c->getName());
  35. $this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $c->getRequestHeaders());
  36. $this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $c->getRequestServer());
  37. $this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $c->getRequestCookies());
  38. $this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $attributes);
  39. $this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $c->getRequestRequest());
  40. $this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $c->getRequestQuery());
  41. $this->assertInstanceOf(ParameterBag::class, $c->getResponseCookies());
  42. $this->assertSame('html', $c->getFormat());
  43. $this->assertEquals('foobar', $c->getRoute());
  44. $this->assertEquals(['name' => 'foo'], $c->getRouteParams());
  45. $this->assertSame([], $c->getSessionAttributes());
  46. $this->assertSame('en', $c->getLocale());
  47. $this->assertContains(__FILE__, $attributes->get('resource'));
  48. $this->assertSame('stdClass', $attributes->get('object')->getType());
  49. $this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $c->getResponseHeaders());
  50. $this->assertSame('OK', $c->getStatusText());
  51. $this->assertSame(200, $c->getStatusCode());
  52. $this->assertSame('application/json', $c->getContentType());
  53. }
  54. public function testCollectWithoutRouteParams()
  55. {
  56. $request = $this->createRequest([]);
  57. $c = new RequestDataCollector();
  58. $c->collect($request, $this->createResponse());
  59. $c->lateCollect();
  60. $this->assertEquals([], $c->getRouteParams());
  61. }
  62. /**
  63. * @dataProvider provideControllerCallables
  64. */
  65. public function testControllerInspection($name, $callable, $expected)
  66. {
  67. $c = new RequestDataCollector();
  68. $request = $this->createRequest();
  69. $response = $this->createResponse();
  70. $this->injectController($c, $callable, $request);
  71. $c->collect($request, $response);
  72. $c->lateCollect();
  73. $this->assertSame($expected, $c->getController()->getValue(true), sprintf('Testing: %s', $name));
  74. }
  75. public function provideControllerCallables()
  76. {
  77. // make sure we always match the line number
  78. $r1 = new \ReflectionMethod($this, 'testControllerInspection');
  79. $r2 = new \ReflectionMethod($this, 'staticControllerMethod');
  80. $r3 = new \ReflectionClass($this);
  81. // test name, callable, expected
  82. return [
  83. [
  84. '"Regular" callable',
  85. [$this, 'testControllerInspection'],
  86. [
  87. 'class' => __NAMESPACE__.'\RequestDataCollectorTest',
  88. 'method' => 'testControllerInspection',
  89. 'file' => __FILE__,
  90. 'line' => $r1->getStartLine(),
  91. ],
  92. ],
  93. [
  94. 'Closure',
  95. function () { return 'foo'; },
  96. [
  97. 'class' => __NAMESPACE__.'\{closure}',
  98. 'method' => null,
  99. 'file' => __FILE__,
  100. 'line' => __LINE__ - 5,
  101. ],
  102. ],
  103. [
  104. 'Static callback as string',
  105. __NAMESPACE__.'\RequestDataCollectorTest::staticControllerMethod',
  106. [
  107. 'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
  108. 'method' => 'staticControllerMethod',
  109. 'file' => __FILE__,
  110. 'line' => $r2->getStartLine(),
  111. ],
  112. ],
  113. [
  114. 'Static callable with instance',
  115. [$this, 'staticControllerMethod'],
  116. [
  117. 'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
  118. 'method' => 'staticControllerMethod',
  119. 'file' => __FILE__,
  120. 'line' => $r2->getStartLine(),
  121. ],
  122. ],
  123. [
  124. 'Static callable with class name',
  125. ['Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest', 'staticControllerMethod'],
  126. [
  127. 'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
  128. 'method' => 'staticControllerMethod',
  129. 'file' => __FILE__,
  130. 'line' => $r2->getStartLine(),
  131. ],
  132. ],
  133. [
  134. 'Callable with instance depending on __call()',
  135. [$this, 'magicMethod'],
  136. [
  137. 'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
  138. 'method' => 'magicMethod',
  139. 'file' => 'n/a',
  140. 'line' => 'n/a',
  141. ],
  142. ],
  143. [
  144. 'Callable with class name depending on __callStatic()',
  145. ['Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest', 'magicMethod'],
  146. [
  147. 'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
  148. 'method' => 'magicMethod',
  149. 'file' => 'n/a',
  150. 'line' => 'n/a',
  151. ],
  152. ],
  153. [
  154. 'Invokable controller',
  155. $this,
  156. [
  157. 'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
  158. 'method' => null,
  159. 'file' => __FILE__,
  160. 'line' => $r3->getStartLine(),
  161. ],
  162. ],
  163. ];
  164. }
  165. public function testItIgnoresInvalidCallables()
  166. {
  167. $request = $this->createRequestWithSession();
  168. $response = new RedirectResponse('/');
  169. $c = new RequestDataCollector();
  170. $c->collect($request, $response);
  171. $this->assertSame('n/a', $c->getController());
  172. }
  173. public function testItAddsRedirectedAttributesWhenRequestContainsSpecificCookie()
  174. {
  175. $request = $this->createRequest();
  176. $request->cookies->add([
  177. 'sf_redirect' => '{}',
  178. ]);
  179. $kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock();
  180. $c = new RequestDataCollector();
  181. $c->onKernelResponse(new FilterResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST, $this->createResponse()));
  182. $this->assertTrue($request->attributes->get('_redirected'));
  183. }
  184. public function testItSetsARedirectCookieIfTheResponseIsARedirection()
  185. {
  186. $c = new RequestDataCollector();
  187. $response = $this->createResponse();
  188. $response->setStatusCode(302);
  189. $response->headers->set('Location', '/somewhere-else');
  190. $c->collect($request = $this->createRequest(), $response);
  191. $c->lateCollect();
  192. $cookie = $this->getCookieByName($response, 'sf_redirect');
  193. $this->assertNotEmpty($cookie->getValue());
  194. $this->assertSame('lax', $cookie->getSameSite());
  195. $this->assertFalse($cookie->isSecure());
  196. }
  197. public function testItCollectsTheRedirectionAndClearTheCookie()
  198. {
  199. $c = new RequestDataCollector();
  200. $request = $this->createRequest();
  201. $request->attributes->set('_redirected', true);
  202. $request->cookies->add([
  203. 'sf_redirect' => '{"method": "POST"}',
  204. ]);
  205. $c->collect($request, $response = $this->createResponse());
  206. $c->lateCollect();
  207. $this->assertEquals('POST', $c->getRedirect()['method']);
  208. $cookie = $this->getCookieByName($response, 'sf_redirect');
  209. $this->assertNull($cookie->getValue());
  210. }
  211. protected function createRequest($routeParams = ['name' => 'foo'])
  212. {
  213. $request = Request::create('http://test.com/foo?bar=baz');
  214. $request->attributes->set('foo', 'bar');
  215. $request->attributes->set('_route', 'foobar');
  216. $request->attributes->set('_route_params', $routeParams);
  217. $request->attributes->set('resource', fopen(__FILE__, 'r'));
  218. $request->attributes->set('object', new \stdClass());
  219. return $request;
  220. }
  221. private function createRequestWithSession()
  222. {
  223. $request = $this->createRequest();
  224. $request->attributes->set('_controller', 'Foo::bar');
  225. $request->setSession(new Session(new MockArraySessionStorage()));
  226. $request->getSession()->start();
  227. return $request;
  228. }
  229. protected function createResponse()
  230. {
  231. $response = new Response();
  232. $response->setStatusCode(200);
  233. $response->headers->set('Content-Type', 'application/json');
  234. $response->headers->set('X-Foo-Bar', null);
  235. $response->headers->setCookie(new Cookie('foo', 'bar', 1, '/foo', 'localhost', true, true, false, null));
  236. $response->headers->setCookie(new Cookie('bar', 'foo', new \DateTime('@946684800'), '/', null, false, true, false, null));
  237. $response->headers->setCookie(new Cookie('bazz', 'foo', '2000-12-12', '/', null, false, true, false, null));
  238. return $response;
  239. }
  240. /**
  241. * Inject the given controller callable into the data collector.
  242. */
  243. protected function injectController($collector, $controller, $request)
  244. {
  245. $resolver = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface')->getMock();
  246. $httpKernel = new HttpKernel(new EventDispatcher(), $resolver, null, $this->getMockBuilder(ArgumentResolverInterface::class)->getMock());
  247. $event = new FilterControllerEvent($httpKernel, $controller, $request, HttpKernelInterface::MASTER_REQUEST);
  248. $collector->onKernelController($event);
  249. }
  250. /**
  251. * Dummy method used as controller callable.
  252. */
  253. public static function staticControllerMethod()
  254. {
  255. throw new \LogicException('Unexpected method call');
  256. }
  257. /**
  258. * Magic method to allow non existing methods to be called and delegated.
  259. */
  260. public function __call($method, $args)
  261. {
  262. throw new \LogicException('Unexpected method call');
  263. }
  264. /**
  265. * Magic method to allow non existing methods to be called and delegated.
  266. */
  267. public static function __callStatic($method, $args)
  268. {
  269. throw new \LogicException('Unexpected method call');
  270. }
  271. public function __invoke()
  272. {
  273. throw new \LogicException('Unexpected method call');
  274. }
  275. private function getCookieByName(Response $response, $name)
  276. {
  277. foreach ($response->headers->getCookies() as $cookie) {
  278. if ($cookie->getName() == $name) {
  279. return $cookie;
  280. }
  281. }
  282. throw new \InvalidArgumentException(sprintf('Cookie named "%s" is not in response', $name));
  283. }
  284. }