PageRenderTime 54ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Symfony/Component/HttpKernel/Tests/DataCollector/RequestDataCollectorTest.php

http://github.com/symfony/symfony
PHP | 390 lines | 299 code | 60 blank | 31 comment | 2 complexity | e13ac0370143d649d487d3208b48c604 MD5 | raw file
  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\ControllerEvent;
  23. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  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' => self::class,
  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 ResponseEvent($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 ControllerEvent($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(string $method, array $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(string $method, array $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. /**
  285. * @dataProvider provideJsonContentTypes
  286. */
  287. public function testIsJson($contentType, $expected)
  288. {
  289. $response = $this->createResponse();
  290. $request = $this->createRequest();
  291. $request->headers->set('Content-Type', $contentType);
  292. $c = new RequestDataCollector();
  293. $c->collect($request, $response);
  294. $this->assertSame($expected, $c->isJsonRequest());
  295. }
  296. public function provideJsonContentTypes()
  297. {
  298. return [
  299. ['text/csv', false],
  300. ['application/json', true],
  301. ['application/JSON', true],
  302. ['application/hal+json', true],
  303. ['application/xml+json', true],
  304. ['application/xml', false],
  305. ['', false],
  306. ];
  307. }
  308. /**
  309. * @dataProvider providePrettyJson
  310. */
  311. public function testGetPrettyJsonValidity($content, $expected)
  312. {
  313. $response = $this->createResponse();
  314. $request = Request::create('/', 'POST', [], [], [], [], $content);
  315. $c = new RequestDataCollector();
  316. $c->collect($request, $response);
  317. $this->assertSame($expected, $c->getPrettyJson());
  318. }
  319. public function providePrettyJson()
  320. {
  321. return [
  322. ['null', 'null'],
  323. ['{ "foo": "bar" }', '{
  324. "foo": "bar"
  325. }'],
  326. ['{ "abc" }', null],
  327. ['', null],
  328. ];
  329. }
  330. }