RequestTest.php 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080
  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\HttpFoundation\Tests;
  11. use PHPUnit\Framework\TestCase;
  12. use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
  13. use Symfony\Component\HttpFoundation\Session\Session;
  14. use Symfony\Component\HttpFoundation\Request;
  15. class RequestTest extends TestCase
  16. {
  17. public function testInitialize()
  18. {
  19. $request = new Request();
  20. $request->initialize(array('foo' => 'bar'));
  21. $this->assertEquals('bar', $request->query->get('foo'), '->initialize() takes an array of query parameters as its first argument');
  22. $request->initialize(array(), array('foo' => 'bar'));
  23. $this->assertEquals('bar', $request->request->get('foo'), '->initialize() takes an array of request parameters as its second argument');
  24. $request->initialize(array(), array(), array('foo' => 'bar'));
  25. $this->assertEquals('bar', $request->attributes->get('foo'), '->initialize() takes an array of attributes as its third argument');
  26. $request->initialize(array(), array(), array(), array(), array(), array('HTTP_FOO' => 'bar'));
  27. $this->assertEquals('bar', $request->headers->get('FOO'), '->initialize() takes an array of HTTP headers as its sixth argument');
  28. }
  29. public function testGetLocale()
  30. {
  31. $request = new Request();
  32. $request->setLocale('pl');
  33. $locale = $request->getLocale();
  34. $this->assertEquals('pl', $locale);
  35. }
  36. public function testGetUser()
  37. {
  38. $request = Request::create('http://user_test:password_test@test.com/');
  39. $user = $request->getUser();
  40. $this->assertEquals('user_test', $user);
  41. }
  42. public function testGetPassword()
  43. {
  44. $request = Request::create('http://user_test:password_test@test.com/');
  45. $password = $request->getPassword();
  46. $this->assertEquals('password_test', $password);
  47. }
  48. public function testIsNoCache()
  49. {
  50. $request = new Request();
  51. $isNoCache = $request->isNoCache();
  52. $this->assertFalse($isNoCache);
  53. }
  54. public function testGetContentType()
  55. {
  56. $request = new Request();
  57. $contentType = $request->getContentType();
  58. $this->assertNull($contentType);
  59. }
  60. public function testSetDefaultLocale()
  61. {
  62. $request = new Request();
  63. $request->setDefaultLocale('pl');
  64. $locale = $request->getLocale();
  65. $this->assertEquals('pl', $locale);
  66. }
  67. public function testCreate()
  68. {
  69. $request = Request::create('http://test.com/foo?bar=baz');
  70. $this->assertEquals('http://test.com/foo?bar=baz', $request->getUri());
  71. $this->assertEquals('/foo', $request->getPathInfo());
  72. $this->assertEquals('bar=baz', $request->getQueryString());
  73. $this->assertEquals(80, $request->getPort());
  74. $this->assertEquals('test.com', $request->getHttpHost());
  75. $this->assertFalse($request->isSecure());
  76. $request = Request::create('http://test.com/foo', 'GET', array('bar' => 'baz'));
  77. $this->assertEquals('http://test.com/foo?bar=baz', $request->getUri());
  78. $this->assertEquals('/foo', $request->getPathInfo());
  79. $this->assertEquals('bar=baz', $request->getQueryString());
  80. $this->assertEquals(80, $request->getPort());
  81. $this->assertEquals('test.com', $request->getHttpHost());
  82. $this->assertFalse($request->isSecure());
  83. $request = Request::create('http://test.com/foo?bar=foo', 'GET', array('bar' => 'baz'));
  84. $this->assertEquals('http://test.com/foo?bar=baz', $request->getUri());
  85. $this->assertEquals('/foo', $request->getPathInfo());
  86. $this->assertEquals('bar=baz', $request->getQueryString());
  87. $this->assertEquals(80, $request->getPort());
  88. $this->assertEquals('test.com', $request->getHttpHost());
  89. $this->assertFalse($request->isSecure());
  90. $request = Request::create('https://test.com/foo?bar=baz');
  91. $this->assertEquals('https://test.com/foo?bar=baz', $request->getUri());
  92. $this->assertEquals('/foo', $request->getPathInfo());
  93. $this->assertEquals('bar=baz', $request->getQueryString());
  94. $this->assertEquals(443, $request->getPort());
  95. $this->assertEquals('test.com', $request->getHttpHost());
  96. $this->assertTrue($request->isSecure());
  97. $request = Request::create('test.com:90/foo');
  98. $this->assertEquals('http://test.com:90/foo', $request->getUri());
  99. $this->assertEquals('/foo', $request->getPathInfo());
  100. $this->assertEquals('test.com', $request->getHost());
  101. $this->assertEquals('test.com:90', $request->getHttpHost());
  102. $this->assertEquals(90, $request->getPort());
  103. $this->assertFalse($request->isSecure());
  104. $request = Request::create('https://test.com:90/foo');
  105. $this->assertEquals('https://test.com:90/foo', $request->getUri());
  106. $this->assertEquals('/foo', $request->getPathInfo());
  107. $this->assertEquals('test.com', $request->getHost());
  108. $this->assertEquals('test.com:90', $request->getHttpHost());
  109. $this->assertEquals(90, $request->getPort());
  110. $this->assertTrue($request->isSecure());
  111. $request = Request::create('https://127.0.0.1:90/foo');
  112. $this->assertEquals('https://127.0.0.1:90/foo', $request->getUri());
  113. $this->assertEquals('/foo', $request->getPathInfo());
  114. $this->assertEquals('127.0.0.1', $request->getHost());
  115. $this->assertEquals('127.0.0.1:90', $request->getHttpHost());
  116. $this->assertEquals(90, $request->getPort());
  117. $this->assertTrue($request->isSecure());
  118. $request = Request::create('https://[::1]:90/foo');
  119. $this->assertEquals('https://[::1]:90/foo', $request->getUri());
  120. $this->assertEquals('/foo', $request->getPathInfo());
  121. $this->assertEquals('[::1]', $request->getHost());
  122. $this->assertEquals('[::1]:90', $request->getHttpHost());
  123. $this->assertEquals(90, $request->getPort());
  124. $this->assertTrue($request->isSecure());
  125. $request = Request::create('https://[::1]/foo');
  126. $this->assertEquals('https://[::1]/foo', $request->getUri());
  127. $this->assertEquals('/foo', $request->getPathInfo());
  128. $this->assertEquals('[::1]', $request->getHost());
  129. $this->assertEquals('[::1]', $request->getHttpHost());
  130. $this->assertEquals(443, $request->getPort());
  131. $this->assertTrue($request->isSecure());
  132. $json = '{"jsonrpc":"2.0","method":"echo","id":7,"params":["Hello World"]}';
  133. $request = Request::create('http://example.com/jsonrpc', 'POST', array(), array(), array(), array(), $json);
  134. $this->assertEquals($json, $request->getContent());
  135. $this->assertFalse($request->isSecure());
  136. $request = Request::create('http://test.com');
  137. $this->assertEquals('http://test.com/', $request->getUri());
  138. $this->assertEquals('/', $request->getPathInfo());
  139. $this->assertEquals('', $request->getQueryString());
  140. $this->assertEquals(80, $request->getPort());
  141. $this->assertEquals('test.com', $request->getHttpHost());
  142. $this->assertFalse($request->isSecure());
  143. $request = Request::create('http://test.com?test=1');
  144. $this->assertEquals('http://test.com/?test=1', $request->getUri());
  145. $this->assertEquals('/', $request->getPathInfo());
  146. $this->assertEquals('test=1', $request->getQueryString());
  147. $this->assertEquals(80, $request->getPort());
  148. $this->assertEquals('test.com', $request->getHttpHost());
  149. $this->assertFalse($request->isSecure());
  150. $request = Request::create('http://test.com:90/?test=1');
  151. $this->assertEquals('http://test.com:90/?test=1', $request->getUri());
  152. $this->assertEquals('/', $request->getPathInfo());
  153. $this->assertEquals('test=1', $request->getQueryString());
  154. $this->assertEquals(90, $request->getPort());
  155. $this->assertEquals('test.com:90', $request->getHttpHost());
  156. $this->assertFalse($request->isSecure());
  157. $request = Request::create('http://username:password@test.com');
  158. $this->assertEquals('http://test.com/', $request->getUri());
  159. $this->assertEquals('/', $request->getPathInfo());
  160. $this->assertEquals('', $request->getQueryString());
  161. $this->assertEquals(80, $request->getPort());
  162. $this->assertEquals('test.com', $request->getHttpHost());
  163. $this->assertEquals('username', $request->getUser());
  164. $this->assertEquals('password', $request->getPassword());
  165. $this->assertFalse($request->isSecure());
  166. $request = Request::create('http://username@test.com');
  167. $this->assertEquals('http://test.com/', $request->getUri());
  168. $this->assertEquals('/', $request->getPathInfo());
  169. $this->assertEquals('', $request->getQueryString());
  170. $this->assertEquals(80, $request->getPort());
  171. $this->assertEquals('test.com', $request->getHttpHost());
  172. $this->assertEquals('username', $request->getUser());
  173. $this->assertSame('', $request->getPassword());
  174. $this->assertFalse($request->isSecure());
  175. $request = Request::create('http://test.com/?foo');
  176. $this->assertEquals('/?foo', $request->getRequestUri());
  177. $this->assertEquals(array('foo' => ''), $request->query->all());
  178. // assume rewrite rule: (.*) --> app/app.php; app/ is a symlink to a symfony web/ directory
  179. $request = Request::create('http://test.com/apparthotel-1234', 'GET', array(), array(), array(),
  180. array(
  181. 'DOCUMENT_ROOT' => '/var/www/www.test.com',
  182. 'SCRIPT_FILENAME' => '/var/www/www.test.com/app/app.php',
  183. 'SCRIPT_NAME' => '/app/app.php',
  184. 'PHP_SELF' => '/app/app.php/apparthotel-1234',
  185. ));
  186. $this->assertEquals('http://test.com/apparthotel-1234', $request->getUri());
  187. $this->assertEquals('/apparthotel-1234', $request->getPathInfo());
  188. $this->assertEquals('', $request->getQueryString());
  189. $this->assertEquals(80, $request->getPort());
  190. $this->assertEquals('test.com', $request->getHttpHost());
  191. $this->assertFalse($request->isSecure());
  192. }
  193. public function testCreateCheckPrecedence()
  194. {
  195. // server is used by default
  196. $request = Request::create('/', 'DELETE', array(), array(), array(), array(
  197. 'HTTP_HOST' => 'example.com',
  198. 'HTTPS' => 'on',
  199. 'SERVER_PORT' => 443,
  200. 'PHP_AUTH_USER' => 'fabien',
  201. 'PHP_AUTH_PW' => 'pa$$',
  202. 'QUERY_STRING' => 'foo=bar',
  203. 'CONTENT_TYPE' => 'application/json',
  204. ));
  205. $this->assertEquals('example.com', $request->getHost());
  206. $this->assertEquals(443, $request->getPort());
  207. $this->assertTrue($request->isSecure());
  208. $this->assertEquals('fabien', $request->getUser());
  209. $this->assertEquals('pa$$', $request->getPassword());
  210. $this->assertEquals('', $request->getQueryString());
  211. $this->assertEquals('application/json', $request->headers->get('CONTENT_TYPE'));
  212. // URI has precedence over server
  213. $request = Request::create('http://thomas:pokemon@example.net:8080/?foo=bar', 'GET', array(), array(), array(), array(
  214. 'HTTP_HOST' => 'example.com',
  215. 'HTTPS' => 'on',
  216. 'SERVER_PORT' => 443,
  217. ));
  218. $this->assertEquals('example.net', $request->getHost());
  219. $this->assertEquals(8080, $request->getPort());
  220. $this->assertFalse($request->isSecure());
  221. $this->assertEquals('thomas', $request->getUser());
  222. $this->assertEquals('pokemon', $request->getPassword());
  223. $this->assertEquals('foo=bar', $request->getQueryString());
  224. }
  225. public function testDuplicate()
  226. {
  227. $request = new Request(array('foo' => 'bar'), array('foo' => 'bar'), array('foo' => 'bar'), array(), array(), array('HTTP_FOO' => 'bar'));
  228. $dup = $request->duplicate();
  229. $this->assertEquals($request->query->all(), $dup->query->all(), '->duplicate() duplicates a request an copy the current query parameters');
  230. $this->assertEquals($request->request->all(), $dup->request->all(), '->duplicate() duplicates a request an copy the current request parameters');
  231. $this->assertEquals($request->attributes->all(), $dup->attributes->all(), '->duplicate() duplicates a request an copy the current attributes');
  232. $this->assertEquals($request->headers->all(), $dup->headers->all(), '->duplicate() duplicates a request an copy the current HTTP headers');
  233. $dup = $request->duplicate(array('foo' => 'foobar'), array('foo' => 'foobar'), array('foo' => 'foobar'), array(), array(), array('HTTP_FOO' => 'foobar'));
  234. $this->assertEquals(array('foo' => 'foobar'), $dup->query->all(), '->duplicate() overrides the query parameters if provided');
  235. $this->assertEquals(array('foo' => 'foobar'), $dup->request->all(), '->duplicate() overrides the request parameters if provided');
  236. $this->assertEquals(array('foo' => 'foobar'), $dup->attributes->all(), '->duplicate() overrides the attributes if provided');
  237. $this->assertEquals(array('foo' => array('foobar')), $dup->headers->all(), '->duplicate() overrides the HTTP header if provided');
  238. }
  239. public function testDuplicateWithFormat()
  240. {
  241. $request = new Request(array(), array(), array('_format' => 'json'));
  242. $dup = $request->duplicate();
  243. $this->assertEquals('json', $dup->getRequestFormat());
  244. $this->assertEquals('json', $dup->attributes->get('_format'));
  245. $request = new Request();
  246. $request->setRequestFormat('xml');
  247. $dup = $request->duplicate();
  248. $this->assertEquals('xml', $dup->getRequestFormat());
  249. }
  250. /**
  251. * @dataProvider getFormatToMimeTypeMapProvider
  252. */
  253. public function testGetFormatFromMimeType($format, $mimeTypes)
  254. {
  255. $request = new Request();
  256. foreach ($mimeTypes as $mime) {
  257. $this->assertEquals($format, $request->getFormat($mime));
  258. }
  259. $request->setFormat($format, $mimeTypes);
  260. foreach ($mimeTypes as $mime) {
  261. $this->assertEquals($format, $request->getFormat($mime));
  262. }
  263. }
  264. public function testGetFormatFromMimeTypeWithParameters()
  265. {
  266. $request = new Request();
  267. $this->assertEquals('json', $request->getFormat('application/json; charset=utf-8'));
  268. }
  269. /**
  270. * @dataProvider getFormatToMimeTypeMapProvider
  271. */
  272. public function testGetMimeTypeFromFormat($format, $mimeTypes)
  273. {
  274. if (null !== $format) {
  275. $request = new Request();
  276. $this->assertEquals($mimeTypes[0], $request->getMimeType($format));
  277. }
  278. }
  279. /**
  280. * @dataProvider getFormatToMimeTypeMapProvider
  281. */
  282. public function testGetMimeTypesFromFormat($format, $mimeTypes)
  283. {
  284. if (null !== $format) {
  285. $this->assertEquals($mimeTypes, Request::getMimeTypes($format));
  286. }
  287. }
  288. public function testGetMimeTypesFromInexistentFormat()
  289. {
  290. $request = new Request();
  291. $this->assertNull($request->getMimeType('foo'));
  292. $this->assertEquals(array(), Request::getMimeTypes('foo'));
  293. }
  294. public function testGetFormatWithCustomMimeType()
  295. {
  296. $request = new Request();
  297. $request->setFormat('custom', 'application/vnd.foo.api;myversion=2.3');
  298. $this->assertEquals('custom', $request->getFormat('application/vnd.foo.api;myversion=2.3'));
  299. }
  300. public function getFormatToMimeTypeMapProvider()
  301. {
  302. return array(
  303. array(null, array(null, 'unexistent-mime-type')),
  304. array('txt', array('text/plain')),
  305. array('js', array('application/javascript', 'application/x-javascript', 'text/javascript')),
  306. array('css', array('text/css')),
  307. array('json', array('application/json', 'application/x-json')),
  308. array('xml', array('text/xml', 'application/xml', 'application/x-xml')),
  309. array('rdf', array('application/rdf+xml')),
  310. array('atom', array('application/atom+xml')),
  311. );
  312. }
  313. public function testGetUri()
  314. {
  315. $server = array();
  316. // Standard Request on non default PORT
  317. // http://host:8080/index.php/path/info?query=string
  318. $server['HTTP_HOST'] = 'host:8080';
  319. $server['SERVER_NAME'] = 'servername';
  320. $server['SERVER_PORT'] = '8080';
  321. $server['QUERY_STRING'] = 'query=string';
  322. $server['REQUEST_URI'] = '/index.php/path/info?query=string';
  323. $server['SCRIPT_NAME'] = '/index.php';
  324. $server['PATH_INFO'] = '/path/info';
  325. $server['PATH_TRANSLATED'] = 'redirect:/index.php/path/info';
  326. $server['PHP_SELF'] = '/index_dev.php/path/info';
  327. $server['SCRIPT_FILENAME'] = '/some/where/index.php';
  328. $request = new Request();
  329. $request->initialize(array(), array(), array(), array(), array(), $server);
  330. $this->assertEquals('http://host:8080/index.php/path/info?query=string', $request->getUri(), '->getUri() with non default port');
  331. // Use std port number
  332. $server['HTTP_HOST'] = 'host';
  333. $server['SERVER_NAME'] = 'servername';
  334. $server['SERVER_PORT'] = '80';
  335. $request->initialize(array(), array(), array(), array(), array(), $server);
  336. $this->assertEquals('http://host/index.php/path/info?query=string', $request->getUri(), '->getUri() with default port');
  337. // Without HOST HEADER
  338. unset($server['HTTP_HOST']);
  339. $server['SERVER_NAME'] = 'servername';
  340. $server['SERVER_PORT'] = '80';
  341. $request->initialize(array(), array(), array(), array(), array(), $server);
  342. $this->assertEquals('http://servername/index.php/path/info?query=string', $request->getUri(), '->getUri() with default port without HOST_HEADER');
  343. // Request with URL REWRITING (hide index.php)
  344. // RewriteCond %{REQUEST_FILENAME} !-f
  345. // RewriteRule ^(.*)$ index.php [QSA,L]
  346. // http://host:8080/path/info?query=string
  347. $server = array();
  348. $server['HTTP_HOST'] = 'host:8080';
  349. $server['SERVER_NAME'] = 'servername';
  350. $server['SERVER_PORT'] = '8080';
  351. $server['REDIRECT_QUERY_STRING'] = 'query=string';
  352. $server['REDIRECT_URL'] = '/path/info';
  353. $server['SCRIPT_NAME'] = '/index.php';
  354. $server['QUERY_STRING'] = 'query=string';
  355. $server['REQUEST_URI'] = '/path/info?toto=test&1=1';
  356. $server['SCRIPT_NAME'] = '/index.php';
  357. $server['PHP_SELF'] = '/index.php';
  358. $server['SCRIPT_FILENAME'] = '/some/where/index.php';
  359. $request->initialize(array(), array(), array(), array(), array(), $server);
  360. $this->assertEquals('http://host:8080/path/info?query=string', $request->getUri(), '->getUri() with rewrite');
  361. // Use std port number
  362. // http://host/path/info?query=string
  363. $server['HTTP_HOST'] = 'host';
  364. $server['SERVER_NAME'] = 'servername';
  365. $server['SERVER_PORT'] = '80';
  366. $request->initialize(array(), array(), array(), array(), array(), $server);
  367. $this->assertEquals('http://host/path/info?query=string', $request->getUri(), '->getUri() with rewrite and default port');
  368. // Without HOST HEADER
  369. unset($server['HTTP_HOST']);
  370. $server['SERVER_NAME'] = 'servername';
  371. $server['SERVER_PORT'] = '80';
  372. $request->initialize(array(), array(), array(), array(), array(), $server);
  373. $this->assertEquals('http://servername/path/info?query=string', $request->getUri(), '->getUri() with rewrite, default port without HOST_HEADER');
  374. // With encoded characters
  375. $server = array(
  376. 'HTTP_HOST' => 'host:8080',
  377. 'SERVER_NAME' => 'servername',
  378. 'SERVER_PORT' => '8080',
  379. 'QUERY_STRING' => 'query=string',
  380. 'REQUEST_URI' => '/ba%20se/index_dev.php/foo%20bar/in+fo?query=string',
  381. 'SCRIPT_NAME' => '/ba se/index_dev.php',
  382. 'PATH_TRANSLATED' => 'redirect:/index.php/foo bar/in+fo',
  383. 'PHP_SELF' => '/ba se/index_dev.php/path/info',
  384. 'SCRIPT_FILENAME' => '/some/where/ba se/index_dev.php',
  385. );
  386. $request->initialize(array(), array(), array(), array(), array(), $server);
  387. $this->assertEquals(
  388. 'http://host:8080/ba%20se/index_dev.php/foo%20bar/in+fo?query=string',
  389. $request->getUri()
  390. );
  391. // with user info
  392. $server['PHP_AUTH_USER'] = 'fabien';
  393. $request->initialize(array(), array(), array(), array(), array(), $server);
  394. $this->assertEquals('http://host:8080/ba%20se/index_dev.php/foo%20bar/in+fo?query=string', $request->getUri());
  395. $server['PHP_AUTH_PW'] = 'symfony';
  396. $request->initialize(array(), array(), array(), array(), array(), $server);
  397. $this->assertEquals('http://host:8080/ba%20se/index_dev.php/foo%20bar/in+fo?query=string', $request->getUri());
  398. }
  399. public function testGetUriForPath()
  400. {
  401. $request = Request::create('http://test.com/foo?bar=baz');
  402. $this->assertEquals('http://test.com/some/path', $request->getUriForPath('/some/path'));
  403. $request = Request::create('http://test.com:90/foo?bar=baz');
  404. $this->assertEquals('http://test.com:90/some/path', $request->getUriForPath('/some/path'));
  405. $request = Request::create('https://test.com/foo?bar=baz');
  406. $this->assertEquals('https://test.com/some/path', $request->getUriForPath('/some/path'));
  407. $request = Request::create('https://test.com:90/foo?bar=baz');
  408. $this->assertEquals('https://test.com:90/some/path', $request->getUriForPath('/some/path'));
  409. $server = array();
  410. // Standard Request on non default PORT
  411. // http://host:8080/index.php/path/info?query=string
  412. $server['HTTP_HOST'] = 'host:8080';
  413. $server['SERVER_NAME'] = 'servername';
  414. $server['SERVER_PORT'] = '8080';
  415. $server['QUERY_STRING'] = 'query=string';
  416. $server['REQUEST_URI'] = '/index.php/path/info?query=string';
  417. $server['SCRIPT_NAME'] = '/index.php';
  418. $server['PATH_INFO'] = '/path/info';
  419. $server['PATH_TRANSLATED'] = 'redirect:/index.php/path/info';
  420. $server['PHP_SELF'] = '/index_dev.php/path/info';
  421. $server['SCRIPT_FILENAME'] = '/some/where/index.php';
  422. $request = new Request();
  423. $request->initialize(array(), array(), array(), array(), array(), $server);
  424. $this->assertEquals('http://host:8080/index.php/some/path', $request->getUriForPath('/some/path'), '->getUriForPath() with non default port');
  425. // Use std port number
  426. $server['HTTP_HOST'] = 'host';
  427. $server['SERVER_NAME'] = 'servername';
  428. $server['SERVER_PORT'] = '80';
  429. $request->initialize(array(), array(), array(), array(), array(), $server);
  430. $this->assertEquals('http://host/index.php/some/path', $request->getUriForPath('/some/path'), '->getUriForPath() with default port');
  431. // Without HOST HEADER
  432. unset($server['HTTP_HOST']);
  433. $server['SERVER_NAME'] = 'servername';
  434. $server['SERVER_PORT'] = '80';
  435. $request->initialize(array(), array(), array(), array(), array(), $server);
  436. $this->assertEquals('http://servername/index.php/some/path', $request->getUriForPath('/some/path'), '->getUriForPath() with default port without HOST_HEADER');
  437. // Request with URL REWRITING (hide index.php)
  438. // RewriteCond %{REQUEST_FILENAME} !-f
  439. // RewriteRule ^(.*)$ index.php [QSA,L]
  440. // http://host:8080/path/info?query=string
  441. $server = array();
  442. $server['HTTP_HOST'] = 'host:8080';
  443. $server['SERVER_NAME'] = 'servername';
  444. $server['SERVER_PORT'] = '8080';
  445. $server['REDIRECT_QUERY_STRING'] = 'query=string';
  446. $server['REDIRECT_URL'] = '/path/info';
  447. $server['SCRIPT_NAME'] = '/index.php';
  448. $server['QUERY_STRING'] = 'query=string';
  449. $server['REQUEST_URI'] = '/path/info?toto=test&1=1';
  450. $server['SCRIPT_NAME'] = '/index.php';
  451. $server['PHP_SELF'] = '/index.php';
  452. $server['SCRIPT_FILENAME'] = '/some/where/index.php';
  453. $request->initialize(array(), array(), array(), array(), array(), $server);
  454. $this->assertEquals('http://host:8080/some/path', $request->getUriForPath('/some/path'), '->getUri() with rewrite');
  455. // Use std port number
  456. // http://host/path/info?query=string
  457. $server['HTTP_HOST'] = 'host';
  458. $server['SERVER_NAME'] = 'servername';
  459. $server['SERVER_PORT'] = '80';
  460. $request->initialize(array(), array(), array(), array(), array(), $server);
  461. $this->assertEquals('http://host/some/path', $request->getUriForPath('/some/path'), '->getUriForPath() with rewrite and default port');
  462. // Without HOST HEADER
  463. unset($server['HTTP_HOST']);
  464. $server['SERVER_NAME'] = 'servername';
  465. $server['SERVER_PORT'] = '80';
  466. $request->initialize(array(), array(), array(), array(), array(), $server);
  467. $this->assertEquals('http://servername/some/path', $request->getUriForPath('/some/path'), '->getUriForPath() with rewrite, default port without HOST_HEADER');
  468. $this->assertEquals('servername', $request->getHttpHost());
  469. // with user info
  470. $server['PHP_AUTH_USER'] = 'fabien';
  471. $request->initialize(array(), array(), array(), array(), array(), $server);
  472. $this->assertEquals('http://servername/some/path', $request->getUriForPath('/some/path'));
  473. $server['PHP_AUTH_PW'] = 'symfony';
  474. $request->initialize(array(), array(), array(), array(), array(), $server);
  475. $this->assertEquals('http://servername/some/path', $request->getUriForPath('/some/path'));
  476. }
  477. /**
  478. * @dataProvider getRelativeUriForPathData()
  479. */
  480. public function testGetRelativeUriForPath($expected, $pathinfo, $path)
  481. {
  482. $this->assertEquals($expected, Request::create($pathinfo)->getRelativeUriForPath($path));
  483. }
  484. public function getRelativeUriForPathData()
  485. {
  486. return array(
  487. array('me.png', '/foo', '/me.png'),
  488. array('../me.png', '/foo/bar', '/me.png'),
  489. array('me.png', '/foo/bar', '/foo/me.png'),
  490. array('../baz/me.png', '/foo/bar/b', '/foo/baz/me.png'),
  491. array('../../fooz/baz/me.png', '/foo/bar/b', '/fooz/baz/me.png'),
  492. array('baz/me.png', '/foo/bar/b', 'baz/me.png'),
  493. );
  494. }
  495. public function testGetUserInfo()
  496. {
  497. $request = new Request();
  498. $server = array('PHP_AUTH_USER' => 'fabien');
  499. $request->initialize(array(), array(), array(), array(), array(), $server);
  500. $this->assertEquals('fabien', $request->getUserInfo());
  501. $server['PHP_AUTH_USER'] = '0';
  502. $request->initialize(array(), array(), array(), array(), array(), $server);
  503. $this->assertEquals('0', $request->getUserInfo());
  504. $server['PHP_AUTH_PW'] = '0';
  505. $request->initialize(array(), array(), array(), array(), array(), $server);
  506. $this->assertEquals('0:0', $request->getUserInfo());
  507. }
  508. public function testGetSchemeAndHttpHost()
  509. {
  510. $request = new Request();
  511. $server = array();
  512. $server['SERVER_NAME'] = 'servername';
  513. $server['SERVER_PORT'] = '90';
  514. $request->initialize(array(), array(), array(), array(), array(), $server);
  515. $this->assertEquals('http://servername:90', $request->getSchemeAndHttpHost());
  516. $server['PHP_AUTH_USER'] = 'fabien';
  517. $request->initialize(array(), array(), array(), array(), array(), $server);
  518. $this->assertEquals('http://servername:90', $request->getSchemeAndHttpHost());
  519. $server['PHP_AUTH_USER'] = '0';
  520. $request->initialize(array(), array(), array(), array(), array(), $server);
  521. $this->assertEquals('http://servername:90', $request->getSchemeAndHttpHost());
  522. $server['PHP_AUTH_PW'] = '0';
  523. $request->initialize(array(), array(), array(), array(), array(), $server);
  524. $this->assertEquals('http://servername:90', $request->getSchemeAndHttpHost());
  525. }
  526. /**
  527. * @dataProvider getQueryStringNormalizationData
  528. */
  529. public function testGetQueryString($query, $expectedQuery, $msg)
  530. {
  531. $request = new Request();
  532. $request->server->set('QUERY_STRING', $query);
  533. $this->assertSame($expectedQuery, $request->getQueryString(), $msg);
  534. }
  535. public function getQueryStringNormalizationData()
  536. {
  537. return array(
  538. array('foo', 'foo', 'works with valueless parameters'),
  539. array('foo=', 'foo=', 'includes a dangling equal sign'),
  540. array('bar=&foo=bar', 'bar=&foo=bar', '->works with empty parameters'),
  541. array('foo=bar&bar=', 'bar=&foo=bar', 'sorts keys alphabetically'),
  542. // GET parameters, that are submitted from a HTML form, encode spaces as "+" by default (as defined in enctype application/x-www-form-urlencoded).
  543. // PHP also converts "+" to spaces when filling the global _GET or when using the function parse_str.
  544. array('him=John%20Doe&her=Jane+Doe', 'her=Jane%20Doe&him=John%20Doe', 'normalizes spaces in both encodings "%20" and "+"'),
  545. array('foo[]=1&foo[]=2', 'foo%5B%5D=1&foo%5B%5D=2', 'allows array notation'),
  546. array('foo=1&foo=2', 'foo=1&foo=2', 'allows repeated parameters'),
  547. array('pa%3Dram=foo%26bar%3Dbaz&test=test', 'pa%3Dram=foo%26bar%3Dbaz&test=test', 'works with encoded delimiters'),
  548. array('0', '0', 'allows "0"'),
  549. array('Jane Doe&John%20Doe', 'Jane%20Doe&John%20Doe', 'normalizes encoding in keys'),
  550. array('her=Jane Doe&him=John%20Doe', 'her=Jane%20Doe&him=John%20Doe', 'normalizes encoding in values'),
  551. array('foo=bar&&&test&&', 'foo=bar&test', 'removes unneeded delimiters'),
  552. array('formula=e=m*c^2', 'formula=e%3Dm%2Ac%5E2', 'correctly treats only the first "=" as delimiter and the next as value'),
  553. // Ignore pairs with empty key, even if there was a value, e.g. "=value", as such nameless values cannot be retrieved anyway.
  554. // PHP also does not include them when building _GET.
  555. array('foo=bar&=a=b&=x=y', 'foo=bar', 'removes params with empty key'),
  556. );
  557. }
  558. public function testGetQueryStringReturnsNull()
  559. {
  560. $request = new Request();
  561. $this->assertNull($request->getQueryString(), '->getQueryString() returns null for non-existent query string');
  562. $request->server->set('QUERY_STRING', '');
  563. $this->assertNull($request->getQueryString(), '->getQueryString() returns null for empty query string');
  564. }
  565. public function testGetHost()
  566. {
  567. $request = new Request();
  568. $request->initialize(array('foo' => 'bar'));
  569. $this->assertEquals('', $request->getHost(), '->getHost() return empty string if not initialized');
  570. $request->initialize(array(), array(), array(), array(), array(), array('HTTP_HOST' => 'www.example.com'));
  571. $this->assertEquals('www.example.com', $request->getHost(), '->getHost() from Host Header');
  572. // Host header with port number
  573. $request->initialize(array(), array(), array(), array(), array(), array('HTTP_HOST' => 'www.example.com:8080'));
  574. $this->assertEquals('www.example.com', $request->getHost(), '->getHost() from Host Header with port number');
  575. // Server values
  576. $request->initialize(array(), array(), array(), array(), array(), array('SERVER_NAME' => 'www.example.com'));
  577. $this->assertEquals('www.example.com', $request->getHost(), '->getHost() from server name');
  578. $request->initialize(array(), array(), array(), array(), array(), array('SERVER_NAME' => 'www.example.com', 'HTTP_HOST' => 'www.host.com'));
  579. $this->assertEquals('www.host.com', $request->getHost(), '->getHost() value from Host header has priority over SERVER_NAME ');
  580. }
  581. public function testGetPort()
  582. {
  583. $request = Request::create('http://example.com', 'GET', array(), array(), array(), array(
  584. 'HTTP_X_FORWARDED_PROTO' => 'https',
  585. 'HTTP_X_FORWARDED_PORT' => '443',
  586. ));
  587. $port = $request->getPort();
  588. $this->assertEquals(80, $port, 'Without trusted proxies FORWARDED_PROTO and FORWARDED_PORT are ignored.');
  589. Request::setTrustedProxies(array('1.1.1.1'));
  590. $request = Request::create('http://example.com', 'GET', array(), array(), array(), array(
  591. 'HTTP_X_FORWARDED_PROTO' => 'https',
  592. 'HTTP_X_FORWARDED_PORT' => '8443',
  593. ));
  594. $this->assertEquals(80, $request->getPort(), 'With PROTO and PORT on untrusted connection server value takes precedence.');
  595. $request->server->set('REMOTE_ADDR', '1.1.1.1');
  596. $this->assertEquals(8443, $request->getPort(), 'With PROTO and PORT set PORT takes precedence.');
  597. $request = Request::create('http://example.com', 'GET', array(), array(), array(), array(
  598. 'HTTP_X_FORWARDED_PROTO' => 'https',
  599. ));
  600. $this->assertEquals(80, $request->getPort(), 'With only PROTO set getPort() ignores trusted headers on untrusted connection.');
  601. $request->server->set('REMOTE_ADDR', '1.1.1.1');
  602. $this->assertEquals(443, $request->getPort(), 'With only PROTO set getPort() defaults to 443.');
  603. $request = Request::create('http://example.com', 'GET', array(), array(), array(), array(
  604. 'HTTP_X_FORWARDED_PROTO' => 'http',
  605. ));
  606. $this->assertEquals(80, $request->getPort(), 'If X_FORWARDED_PROTO is set to HTTP getPort() ignores trusted headers on untrusted connection.');
  607. $request->server->set('REMOTE_ADDR', '1.1.1.1');
  608. $this->assertEquals(80, $request->getPort(), 'If X_FORWARDED_PROTO is set to HTTP getPort() returns port of the original request.');
  609. $request = Request::create('http://example.com', 'GET', array(), array(), array(), array(
  610. 'HTTP_X_FORWARDED_PROTO' => 'On',
  611. ));
  612. $this->assertEquals(80, $request->getPort(), 'With only PROTO set and value is On, getPort() ignores trusted headers on untrusted connection.');
  613. $request->server->set('REMOTE_ADDR', '1.1.1.1');
  614. $this->assertEquals(443, $request->getPort(), 'With only PROTO set and value is On, getPort() defaults to 443.');
  615. $request = Request::create('http://example.com', 'GET', array(), array(), array(), array(
  616. 'HTTP_X_FORWARDED_PROTO' => '1',
  617. ));
  618. $this->assertEquals(80, $request->getPort(), 'With only PROTO set and value is 1, getPort() ignores trusted headers on untrusted connection.');
  619. $request->server->set('REMOTE_ADDR', '1.1.1.1');
  620. $this->assertEquals(443, $request->getPort(), 'With only PROTO set and value is 1, getPort() defaults to 443.');
  621. $request = Request::create('http://example.com', 'GET', array(), array(), array(), array(
  622. 'HTTP_X_FORWARDED_PROTO' => 'something-else',
  623. ));
  624. $port = $request->getPort();
  625. $this->assertEquals(80, $port, 'With only PROTO set and value is not recognized, getPort() defaults to 80.');
  626. Request::setTrustedProxies(array());
  627. }
  628. /**
  629. * @expectedException \RuntimeException
  630. */
  631. public function testGetHostWithFakeHttpHostValue()
  632. {
  633. $request = new Request();
  634. $request->initialize(array(), array(), array(), array(), array(), array('HTTP_HOST' => 'www.host.com?query=string'));
  635. $request->getHost();
  636. }
  637. public function testGetSetMethod()
  638. {
  639. $request = new Request();
  640. $this->assertEquals('GET', $request->getMethod(), '->getMethod() returns GET if no method is defined');
  641. $request->setMethod('get');
  642. $this->assertEquals('GET', $request->getMethod(), '->getMethod() returns an uppercased string');
  643. $request->setMethod('PURGE');
  644. $this->assertEquals('PURGE', $request->getMethod(), '->getMethod() returns the method even if it is not a standard one');
  645. $request->setMethod('POST');
  646. $this->assertEquals('POST', $request->getMethod(), '->getMethod() returns the method POST if no _method is defined');
  647. $request->setMethod('POST');
  648. $request->request->set('_method', 'purge');
  649. $this->assertEquals('POST', $request->getMethod(), '->getMethod() does not return the method from _method if defined and POST but support not enabled');
  650. $request = new Request();
  651. $request->setMethod('POST');
  652. $request->request->set('_method', 'purge');
  653. $this->assertFalse(Request::getHttpMethodParameterOverride(), 'httpMethodParameterOverride should be disabled by default');
  654. Request::enableHttpMethodParameterOverride();
  655. $this->assertTrue(Request::getHttpMethodParameterOverride(), 'httpMethodParameterOverride should be enabled now but it is not');
  656. $this->assertEquals('PURGE', $request->getMethod(), '->getMethod() returns the method from _method if defined and POST');
  657. $this->disableHttpMethodParameterOverride();
  658. $request = new Request();
  659. $request->setMethod('POST');
  660. $request->query->set('_method', 'purge');
  661. $this->assertEquals('POST', $request->getMethod(), '->getMethod() does not return the method from _method if defined and POST but support not enabled');
  662. $request = new Request();
  663. $request->setMethod('POST');
  664. $request->query->set('_method', 'purge');
  665. Request::enableHttpMethodParameterOverride();
  666. $this->assertEquals('PURGE', $request->getMethod(), '->getMethod() returns the method from _method if defined and POST');
  667. $this->disableHttpMethodParameterOverride();
  668. $request = new Request();
  669. $request->setMethod('POST');
  670. $request->headers->set('X-HTTP-METHOD-OVERRIDE', 'delete');
  671. $this->assertEquals('DELETE', $request->getMethod(), '->getMethod() returns the method from X-HTTP-Method-Override even though _method is set if defined and POST');
  672. $request = new Request();
  673. $request->setMethod('POST');
  674. $request->headers->set('X-HTTP-METHOD-OVERRIDE', 'delete');
  675. $this->assertEquals('DELETE', $request->getMethod(), '->getMethod() returns the method from X-HTTP-Method-Override if defined and POST');
  676. }
  677. /**
  678. * @dataProvider testGetClientIpsProvider
  679. */
  680. public function testGetClientIp($expected, $remoteAddr, $httpForwardedFor, $trustedProxies)
  681. {
  682. $request = $this->getRequestInstanceForClientIpTests($remoteAddr, $httpForwardedFor, $trustedProxies);
  683. $this->assertEquals($expected[0], $request->getClientIp());
  684. Request::setTrustedProxies(array());
  685. }
  686. /**
  687. * @dataProvider testGetClientIpsProvider
  688. */
  689. public function testGetClientIps($expected, $remoteAddr, $httpForwardedFor, $trustedProxies)
  690. {
  691. $request = $this->getRequestInstanceForClientIpTests($remoteAddr, $httpForwardedFor, $trustedProxies);
  692. $this->assertEquals($expected, $request->getClientIps());
  693. Request::setTrustedProxies(array());
  694. }
  695. /**
  696. * @dataProvider testGetClientIpsForwardedProvider
  697. */
  698. public function testGetClientIpsForwarded($expected, $remoteAddr, $httpForwarded, $trustedProxies)
  699. {
  700. $request = $this->getRequestInstanceForClientIpsForwardedTests($remoteAddr, $httpForwarded, $trustedProxies);
  701. $this->assertEquals($expected, $request->getClientIps());
  702. Request::setTrustedProxies(array());
  703. }
  704. public function testGetClientIpsForwardedProvider()
  705. {
  706. // $expected $remoteAddr $httpForwarded $trustedProxies
  707. return array(
  708. array(array('127.0.0.1'), '127.0.0.1', 'for="_gazonk"', null),
  709. array(array('127.0.0.1'), '127.0.0.1', 'for="_gazonk"', array('127.0.0.1')),
  710. array(array('88.88.88.88'), '127.0.0.1', 'for="88.88.88.88:80"', array('127.0.0.1')),
  711. array(array('192.0.2.60'), '::1', 'for=192.0.2.60;proto=http;by=203.0.113.43', array('::1')),
  712. array(array('2620:0:1cfe:face:b00c::3', '192.0.2.43'), '::1', 'for=192.0.2.43, for=2620:0:1cfe:face:b00c::3', array('::1')),
  713. array(array('2001:db8:cafe::17'), '::1', 'for="[2001:db8:cafe::17]:4711', array('::1')),
  714. );
  715. }
  716. public function testGetClientIpsProvider()
  717. {
  718. // $expected $remoteAddr $httpForwardedFor $trustedProxies
  719. return array(
  720. // simple IPv4
  721. array(array('88.88.88.88'), '88.88.88.88', null, null),
  722. // trust the IPv4 remote addr
  723. array(array('88.88.88.88'), '88.88.88.88', null, array('88.88.88.88')),
  724. // simple IPv6
  725. array(array('::1'), '::1', null, null),
  726. // trust the IPv6 remote addr
  727. array(array('::1'), '::1', null, array('::1')),
  728. // forwarded for with remote IPv4 addr not trusted
  729. array(array('127.0.0.1'), '127.0.0.1', '88.88.88.88', null),
  730. // forwarded for with remote IPv4 addr trusted
  731. array(array('88.88.88.88'), '127.0.0.1', '88.88.88.88', array('127.0.0.1')),
  732. // forwarded for with remote IPv4 and all FF addrs trusted
  733. array(array('88.88.88.88'), '127.0.0.1', '88.88.88.88', array('127.0.0.1', '88.88.88.88')),
  734. // forwarded for with remote IPv4 range trusted
  735. array(array('88.88.88.88'), '123.45.67.89', '88.88.88.88', array('123.45.67.0/24')),
  736. // forwarded for with remote IPv6 addr not trusted
  737. array(array('1620:0:1cfe:face:b00c::3'), '1620:0:1cfe:face:b00c::3', '2620:0:1cfe:face:b00c::3', null),
  738. // forwarded for with remote IPv6 addr trusted
  739. array(array('2620:0:1cfe:face:b00c::3'), '1620:0:1cfe:face:b00c::3', '2620:0:1cfe:face:b00c::3', array('1620:0:1cfe:face:b00c::3')),
  740. // forwarded for with remote IPv6 range trusted
  741. array(array('88.88.88.88'), '2a01:198:603:0:396e:4789:8e99:890f', '88.88.88.88', array('2a01:198:603:0::/65')),
  742. // multiple forwarded for with remote IPv4 addr trusted
  743. array(array('88.88.88.88', '87.65.43.21', '127.0.0.1'), '123.45.67.89', '127.0.0.1, 87.65.43.21, 88.88.88.88', array('123.45.67.89')),
  744. // multiple forwarded for with remote IPv4 addr and some reverse proxies trusted
  745. array(array('87.65.43.21', '127.0.0.1'), '123.45.67.89', '127.0.0.1, 87.65.43.21, 88.88.88.88', array('123.45.67.89', '88.88.88.88')),
  746. // multiple forwarded for with remote IPv4 addr and some reverse proxies trusted but in the middle
  747. array(array('88.88.88.88', '127.0.0.1'), '123.45.67.89', '127.0.0.1, 87.65.43.21, 88.88.88.88', array('123.45.67.89', '87.65.43.21')),
  748. // multiple forwarded for with remote IPv4 addr and all reverse proxies trusted
  749. array(array('127.0.0.1'), '123.45.67.89', '127.0.0.1, 87.65.43.21, 88.88.88.88', array('123.45.67.89', '87.65.43.21', '88.88.88.88', '127.0.0.1')),
  750. // multiple forwarded for with remote IPv6 addr trusted
  751. array(array('2620:0:1cfe:face:b00c::3', '3620:0:1cfe:face:b00c::3'), '1620:0:1cfe:face:b00c::3', '3620:0:1cfe:face:b00c::3,2620:0:1cfe:face:b00c::3', array('1620:0:1cfe:face:b00c::3')),
  752. // multiple forwarded for with remote IPv6 addr and some reverse proxies trusted
  753. array(array('3620:0:1cfe:face:b00c::3'), '1620:0:1cfe:face:b00c::3', '3620:0:1cfe:face:b00c::3,2620:0:1cfe:face:b00c::3', array('1620:0:1cfe:face:b00c::3', '2620:0:1cfe:face:b00c::3')),
  754. // multiple forwarded for with remote IPv4 addr and some reverse proxies trusted but in the middle
  755. array(array('2620:0:1cfe:face:b00c::3', '4620:0:1cfe:face:b00c::3'), '1620:0:1cfe:face:b00c::3', '4620:0:1cfe:face:b00c::3,3620:0:1cfe:face:b00c::3,2620:0:1cfe:face:b00c::3', array('1620:0:1cfe:face:b00c::3', '3620:0:1cfe:face:b00c::3')),
  756. // client IP with port
  757. array(array('88.88.88.88'), '127.0.0.1', '88.88.88.88:12345, 127.0.0.1', array('127.0.0.1')),
  758. // invalid forwarded IP is ignored
  759. array(array('88.88.88.88'), '127.0.0.1', 'unknown,88.88.88.88', array('127.0.0.1')),
  760. array(array('88.88.88.88'), '127.0.0.1', '}__test|O:21:&quot;JDatabaseDriverMysqli&quot;:3:{s:2,88.88.88.88', array('127.0.0.1')),
  761. );
  762. }
  763. /**
  764. * @expectedException \Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException
  765. * @dataProvider testGetClientIpsWithConflictingHeadersProvider
  766. */
  767. public function testGetClientIpsWithConflictingHeaders($httpForwarded, $httpXForwardedFor)
  768. {
  769. $request = new Request();
  770. $server = array(
  771. 'REMOTE_ADDR' => '88.88.88.88',
  772. 'HTTP_FORWARDED' => $httpForwarded,
  773. 'HTTP_X_FORWARDED_FOR' => $httpXForwardedFor,
  774. );
  775. Request::setTrustedProxies(array('88.88.88.88'));
  776. $request->initialize(array(), array(), array(), array(), array(), $server);
  777. $request->getClientIps();
  778. }
  779. public function testGetClientIpsWithConflictingHeadersProvider()
  780. {
  781. // $httpForwarded $httpXForwardedFor
  782. return array(
  783. array('for=87.65.43.21', '192.0.2.60'),
  784. array('for=87.65.43.21, for=192.0.2.60', '192.0.2.60'),
  785. array('for=192.0.2.60', '192.0.2.60,87.65.43.21'),
  786. array('for="::face", for=192.0.2.60', '192.0.2.60,192.0.2.43'),
  787. array('for=87.65.43.21, for=192.0.2.60', '192.0.2.60,87.65.43.21'),
  788. );
  789. }
  790. /**
  791. * @dataProvider testGetClientIpsWithAgreeingHeadersProvider
  792. */
  793. public function testGetClientIpsWithAgreeingHeaders($httpForwarded, $httpXForwardedFor)
  794. {
  795. $request = new Request();
  796. $server = array(
  797. 'REMOTE_ADDR' => '88.88.88.88',
  798. 'HTTP_FORWARDED' => $httpForwarded,
  799. 'HTTP_X_FORWARDED_FOR' => $httpXForwardedFor,
  800. );
  801. Request::setTrustedProxies(array('88.88.88.88'));
  802. $request->initialize(array(), array(), array(), array(), array(), $server);
  803. $request->getClientIps();
  804. Request::setTrustedProxies(array());
  805. }
  806. public function testGetClientIpsWithAgreeingHeadersProvider()
  807. {
  808. // $httpForwarded $httpXForwardedFor
  809. return array(
  810. array('for="192.0.2.60"', '192.0.2.60'),
  811. array('for=192.0.2.60, for=87.65.43.21', '192.0.2.60,87.65.43.21'),
  812. array('for="[::face]", for=192.0.2.60', '::face,192.0.2.60'),
  813. array('for="192.0.2.60:80"', '192.0.2.60'),
  814. array('for=192.0.2.60;proto=http;by=203.0.113.43', '192.0.2.60'),
  815. array('for="[2001:db8:cafe::17]:4711"', '2001:db8:cafe::17'),
  816. );
  817. }
  818. public function testGetContentWorksTwiceInDefaultMode()
  819. {
  820. $req = new Request();
  821. $this->assertEquals('', $req->getContent());
  822. $this->assertEquals('', $req->getContent());
  823. }
  824. public function testGetContentReturnsResource()
  825. {
  826. $req = new Request();
  827. $retval = $req->getContent(true);
  828. $this->assertInternalType('resource', $retval);
  829. $this->assertEquals('', fread($retval, 1));
  830. $this->assertTrue(feof($retval));
  831. }
  832. public function testGetContentReturnsResourceWhenContentSetInConstructor()
  833. {
  834. $req = new Request(array(), array(), array(), array(), array(), array(), 'MyContent');
  835. $resource = $req->getContent(true);
  836. $this->assertTrue(is_resource($resource));
  837. $this->assertEquals('MyContent', stream_get_contents($resource));
  838. }
  839. public function testContentAsResource()
  840. {
  841. $resource = fopen('php://memory', 'r+');
  842. fwrite($resource, 'My other content');
  843. rewind($resource);
  844. $req = new Request(array(), array(), array(), array(), array(), array(), $resource);
  845. $this->assertEquals('My other content', stream_get_contents($req->getContent(true)));
  846. $this->assertEquals('My other content', $req->getContent());
  847. }
  848. /**
  849. * @expectedException \LogicException
  850. * @dataProvider getContentCantBeCalledTwiceWithResourcesProvider
  851. */
  852. public function testGetContentCantBeCalledTwiceWithResources($first, $second)
  853. {
  854. if (PHP_VERSION_ID >= 50600) {
  855. $this->markTestSkipped('PHP >= 5.6 allows to open php://input several times.');
  856. }
  857. $req = new Request();
  858. $req->getContent($first);
  859. $req->getContent($second);
  860. }
  861. public function getContentCantBeCalledTwiceWithResourcesProvider()
  862. {
  863. return array(
  864. 'Resource then fetch' => array(true, false),
  865. 'Resource then resource' => array(true, true),
  866. );
  867. }
  868. /**
  869. * @dataProvider getContentCanBeCalledTwiceWithResourcesProvider
  870. * @requires PHP 5.6
  871. */
  872. public function testGetContentCanBeCalledTwiceWithResources($first, $second)
  873. {
  874. $req = new Request();
  875. $a = $req->getContent($first);
  876. $b = $req->getContent($second);
  877. if ($first) {
  878. $a = stream_get_contents($a);
  879. }
  880. if ($second) {
  881. $b = stream_get_contents($b);
  882. }
  883. $this->assertSame($a, $b);
  884. }
  885. public function getContentCanBeCalledTwiceWithResourcesProvider()
  886. {
  887. return array(
  888. 'Fetch then fetch' => array(false, false),
  889. 'Fetch then resource' => array(false, true),
  890. 'Resource then fetch' => array(true, false),
  891. 'Resource then resource' => array(true, true),
  892. );
  893. }
  894. public function provideOverloadedMethods()
  895. {
  896. return array(
  897. array('PUT'),
  898. array('DELETE'),
  899. array('PATCH'),
  900. array('put'),
  901. array('delete'),
  902. array('patch'),
  903. );
  904. }
  905. /**
  906. * @dataProvider provideOverloadedMethods
  907. */
  908. public function testCreateFromGlobals($method)
  909. {
  910. $normalizedMethod = strtoupper($method);
  911. $_GET['foo1'] = 'bar1';
  912. $_POST['foo2'] = 'bar2';
  913. $_COOKIE['foo3'] = 'bar3';
  914. $_FILES['foo4'] = array('bar4');
  915. $_SERVER['foo5'] = 'bar5';
  916. $request = Request::createFromGlobals();
  917. $this->assertEquals('bar1', $request->query->get('foo1'), '::fromGlobals() uses values from $_GET');
  918. $this->assertEquals('bar2', $request->request->get('foo2'), '::fromGlobals() uses values from $_POST');
  919. $this->assertEquals('bar3', $request->cookies->get('foo3'), '::fromGlobals() uses values from $_COOKIE');
  920. $this->assertEquals(array('bar4'), $request->files->get('foo4'), '::fromGlobals() uses values from $_FILES');
  921. $this->assertEquals('bar5', $request->server->get('foo5'), '::fromGlobals() uses values from $_SERVER');
  922. unset($_GET['foo1'], $_POST['foo2'], $_COOKIE['foo3'], $_FILES['foo4'], $_SERVER['foo5']);
  923. $_SERVER['REQUEST_METHOD'] = $method;
  924. $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
  925. $request = RequestContentProxy::createFromGlobals();
  926. $this->assertEquals($normalizedMethod, $request->getMethod());
  927. $this->assertEquals('mycontent', $request->request->get('content'));
  928. unset($_SERVER['REQUEST_METHOD'], $_SERVER['CONTENT_TYPE']);
  929. Request::createFromGlobals();
  930. Request::enableHttpMethodParameterOverride();
  931. $_POST['_method'] = $method;
  932. $_POST['foo6'] = 'bar6';
  933. $_SERVER['REQUEST_METHOD'] = 'PoSt';
  934. $request = Request::createFromGlobals();
  935. $this->assertEquals($normalizedMethod, $request->getMethod());
  936. $this->assertEquals('POST', $request->getRealMethod());
  937. $this->assertEquals('bar6', $request->request->get('foo6'));
  938. unset($_POST['_method'], $_POST['foo6'], $_SERVER['REQUEST_METHOD']);
  939. $this->disableHttpMethodParameterOverride();
  940. }
  941. public function testOverrideGlobals()
  942. {
  943. $request = new Request();
  944. $request->initialize(array('foo' => 'bar'));
  945. // as the Request::overrideGlobals really work, it erase $_SERVER, so we must backup it
  946. $server = $_SERVER;
  947. $request->overrideGlobals();
  948. $this->assertEquals(array('foo' => 'bar'), $_GET);
  949. $request->initialize(array(), array('foo' => 'bar'));
  950. $request->overrideGlobals();
  951. $this->assertEquals(array('foo' => 'bar'), $_POST);
  952. $this->assertArrayNotHasKey('HTTP_X_FORWARDED_PROTO', $_SERVER);
  953. $request->headers->set('X_FORWARDED_PROTO', 'https');
  954. Request::setTrustedProxies(array('1.1.1.1'));
  955. $this->assertFalse($request->isSecure());
  956. $request->server->set('REMOTE_ADDR', '1.1.1.1');
  957. $this->assertTrue($request->isSecure());
  958. Request::setTrustedProxies(array());
  959. $request->overrideGlobals();
  960. $this->assertArrayHasKey('HTTP_X_FORWARDED_PROTO', $_SERVER);
  961. $request->headers->set('CONTENT_TYPE', 'multipart/form-data');
  962. $request->headers->set('CONTENT_LENGTH', 12345);
  963. $request->overrideGlobals();
  964. $this->assertArrayHasKey('CONTENT_TYPE', $_SERVER);
  965. $this->assertArrayHasKey('CONTENT_LENGTH', $_SERVER);
  966. $request->initialize(array('foo' => 'bar', 'baz' => 'foo'));
  967. $request->query->remove('baz');
  968. $request->overrideGlobals();
  969. $this->assertEquals(array('foo' => 'bar'), $_GET);
  970. $this->assertEquals('foo=bar', $_SERVER['QUERY_STRING']);
  971. $this->assertEquals('foo=bar', $request->server->get('QUERY_STRING'));
  972. // restore initial $_SERVER array
  973. $_SERVER = $server;
  974. }
  975. public function testGetScriptName()
  976. {
  977. $request = new Request();
  978. $this->assertEquals('', $request->getScriptName());
  979. $server = array();
  980. $server['SCRIPT_NAME'] = '/index.php';
  981. $request->initialize(array(), array(), array(), array(), array(), $server);
  982. $this->assertEquals('/index.php', $request->getScriptName());
  983. $server = array();
  984. $server['ORIG_SCRIPT_NAME'] = '/frontend.php';
  985. $request->initialize(array(), array(), array(), array(), array(), $server);
  986. $this->assertEquals('/frontend.php', $request->getScriptName());
  987. $server = array();
  988. $server['SCRIPT_NAME'] = '/index.php';
  989. $server['ORIG_SCRIPT_NAME'] = '/frontend.php';
  990. $request->initialize(array(), array(), array(), array(), array(), $server);
  991. $this->assertEquals('/index.php', $request->getScriptName());
  992. }
  993. public function testGetBasePath()
  994. {
  995. $request = new Request();
  996. $this->assertEquals('', $request->getBasePath());
  997. $server = array();
  998. $server['SCRIPT_FILENAME'] = '/some/where/index.php';
  999. $request->initialize(array(), array(), array(), array(), array(), $server);
  1000. $this->assertEquals('', $request->getBasePath());
  1001. $server = array();
  1002. $server['SCRIPT_FILENAME'] = '/some/where/index.php';
  1003. $server['SCRIPT_NAME'] = '/index.php';
  1004. $request->initialize(array(), array(), array(), array(), array(), $server);
  1005. $this->assertEquals('', $request->getBasePath());
  1006. $server = array();
  1007. $server['SCRIPT_FILENAME'] = '/some/where/index.php';
  1008. $server['PHP_SELF'] = '/index.php';
  1009. $request->initialize(array(), array(), array(), array(), array(), $server);
  1010. $this->assertEquals('', $request->getBasePath());
  1011. $server = array();
  1012. $server['SCRIPT_FILENAME'] = '/some/where/index.php';
  1013. $server['ORIG_SCRIPT_NAME'] = '/index.php';
  1014. $request->initialize(array(), array(), array(), array(), array(), $server);
  1015. $this->assertEquals('', $request->getBasePath());
  1016. }
  1017. public function testGetPathInfo()
  1018. {
  1019. $request = new Request();
  1020. $this->assertEquals('/', $request->getPathInfo());
  1021. $server = array();
  1022. $server['REQUEST_URI'] = '/path/info';
  1023. $request->initialize(array(), array(), array(), array(), array(), $server);
  1024. $this->assertEquals('/path/info', $request->getPathInfo());
  1025. $server = array();
  1026. $server['REQUEST_URI'] = '/path%20test/info';
  1027. $request->initialize(array(), array(), array(), array(), array(), $server);
  1028. $this->assertEquals('/path%20test/info', $request->getPathInfo());
  1029. }
  1030. public function testGetParameterPrecedence()
  1031. {
  1032. $request = new Request();
  1033. $request->attributes->set('foo', 'attr');
  1034. $request->query->set('foo', 'query');
  1035. $request->request->set('foo', 'body');
  1036. $this->assertSame('attr', $request->get('foo'));
  1037. $request->attributes->remove('foo');
  1038. $this->assertSame('query', $request->get('foo'));
  1039. $request->query->remove('foo');
  1040. $this->assertSame('body', $request->get('foo'));
  1041. $request->request->remove('foo');
  1042. $this->assertNull($request->get('foo'));
  1043. }
  1044. public function testGetPreferredLanguage()
  1045. {
  1046. $request = new Request();
  1047. $this->assertNull($request->getPreferredLanguage());
  1048. $this->assertNull($request->getPreferredLanguage(array()));
  1049. $this->assertEquals('fr', $request->getPreferredLanguage(array('fr')));
  1050. $this->assertEquals('fr', $request->getPreferredLanguage(array('fr', 'en')));
  1051. $this->assertEquals('en', $request->getPreferredLanguage(array('en', 'fr')));
  1052. $this->assertEquals('fr-ch', $request->getPreferredLanguage(array('fr-ch', 'fr-fr')));
  1053. $request = new Request();
  1054. $request->headers->set('Accept-language', 'zh, en-us; q=0.8, en; q=0.6');
  1055. $this->assertEquals('en', $request->getPreferredLanguage(array('en', 'en-us')));
  1056. $request = new Request();
  1057. $request->headers->set('Accept-language', 'zh, en-us; q=0.8, en; q=0.6');
  1058. $this->assertEquals('en', $request->getPreferredLanguage(array('fr', 'en')));
  1059. $request = new Request();
  1060. $request->headers->set('Accept-language', 'zh, en-us; q=0.8');
  1061. $this->assertEquals('en', $request->getPreferredLanguage(array('fr', 'en')));
  1062. $request = new Request();
  1063. $request->headers->set('Accept-language', 'zh, en-us; q=0.8, fr-fr; q=0.6, fr; q=0.5');
  1064. $this->assertEquals('en', $request->getPreferredLanguage(array('fr', 'en')));
  1065. }
  1066. public function testIsXmlHttpRequest()
  1067. {
  1068. $request = new Request();
  1069. $this->assertFalse($request->isXmlHttpRequest());
  1070. $request->headers->set('X-Requested-With', 'XMLHttpRequest');
  1071. $this->assertTrue($request->isXmlHttpRequest());
  1072. $request->headers->remove('X-Requested-With');
  1073. $this->assertFalse($request->isXmlHttpRequest());
  1074. }
  1075. /**
  1076. * @requires extension intl
  1077. */
  1078. public function testIntlLocale()
  1079. {
  1080. $request = new Request();
  1081. $request->setDefaultLocale('fr');
  1082. $this->assertEquals('fr', $request->getLocale());
  1083. $this->assertEquals('fr', \Locale::getDefault());
  1084. $request->setLocale('en');
  1085. $this->assertEquals('en', $request->getLocale());
  1086. $this->assertEquals('en', \Locale::getDefault());
  1087. $request->setDefaultLocale('de');
  1088. $this->assertEquals('en', $request->getLocale());
  1089. $this->assertEquals('en', \Locale::getDefault());
  1090. }
  1091. public function testGetCharsets()
  1092. {
  1093. $request = new Request();
  1094. $this->assertEquals(array(), $request->getCharsets());
  1095. $request->headers->set('Accept-Charset', 'ISO-8859-1, US-ASCII, UTF-8; q=0.8, ISO-10646-UCS-2; q=0.6');
  1096. $this->assertEquals(array(), $request->getCharsets()); // testing caching
  1097. $request = new Request();
  1098. $request->headers->set('Accept-Charset', 'ISO-8859-1, US-ASCII, UTF-8; q=0.8, ISO-10646-UCS-2; q=0.6');
  1099. $this->assertEquals(array('ISO-8859-1', 'US-ASCII', 'UTF-8', 'ISO-10646-UCS-2'), $request->getCharsets());
  1100. $request = new Request();
  1101. $request->headers->set('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7');
  1102. $this->assertEquals(array('ISO-8859-1', 'utf-8', '*'), $request->getCharsets());
  1103. }
  1104. public function testGetEncodings()
  1105. {
  1106. $request = new Request();
  1107. $this->assertEquals(array(), $request->getEncodings());
  1108. $request->headers->set('Accept-Encoding', 'gzip,deflate,sdch');
  1109. $this->assertEquals(array(), $request->getEncodings()); // testing caching
  1110. $request = new Request();
  1111. $request->headers->set('Accept-Encoding', 'gzip,deflate,sdch');
  1112. $this->assertEquals(array('gzip', 'deflate', 'sdch'), $request->getEncodings());
  1113. $request = new Request();
  1114. $request->headers->set('Accept-Encoding', 'gzip;q=0.4,deflate;q=0.9,compress;q=0.7');
  1115. $this->assertEquals(array('deflate', 'compress', 'gzip'), $request->getEncodings());
  1116. }
  1117. public function testGetAcceptableContentTypes()
  1118. {
  1119. $request = new Request();
  1120. $this->assertEquals(array(), $request->getAcceptableContentTypes());
  1121. $request->headers->set('Accept', 'application/vnd.wap.wmlscriptc, text/vnd.wap.wml, application/vnd.wap.xhtml+xml, application/xhtml+xml, text/html, multipart/mixed, */*');
  1122. $this->assertEquals(array(), $request->getAcceptableContentTypes()); // testing caching
  1123. $request = new Request();
  1124. $request->headers->set('Accept', 'application/vnd.wap.wmlscriptc, text/vnd.wap.wml, application/vnd.wap.xhtml+xml, application/xhtml+xml, text/html, multipart/mixed, */*');
  1125. $this->assertEquals(array('application/vnd.wap.wmlscriptc', 'text/vnd.wap.wml', 'application/vnd.wap.xhtml+xml', 'application/xhtml+xml', 'text/html', 'multipart/mixed', '*/*'), $request->getAcceptableContentTypes());
  1126. }
  1127. public function testGetLanguages()
  1128. {
  1129. $request = new Request();
  1130. $this->assertEquals(array(), $request->getLanguages());
  1131. $request = new Request();
  1132. $request->headers->set('Accept-language', 'zh, en-us; q=0.8, en; q=0.6');
  1133. $this->assertEquals(array('zh', 'en_US', 'en'), $request->getLanguages());
  1134. $this->assertEquals(array('zh', 'en_US', 'en'), $request->getLanguages());
  1135. $request = new Request();
  1136. $request->headers->set('Accept-language', 'zh, en-us; q=0.6, en; q=0.8');
  1137. $this->assertEquals(array('zh', 'en', 'en_US'), $request->getLanguages()); // Test out of order qvalues
  1138. $request = new Request();
  1139. $request->headers->set('Accept-language', 'zh, en, en-us');
  1140. $this->assertEquals(array('zh', 'en', 'en_US'), $request->getLanguages()); // Test equal weighting without qvalues
  1141. $request = new Request();
  1142. $request->headers->set('Accept-language', 'zh; q=0.6, en, en-us; q=0.6');
  1143. $this->assertEquals(array('en', 'zh', 'en_US'), $request->getLanguages()); // Test equal weighting with qvalues
  1144. $request = new Request();
  1145. $request->headers->set('Accept-language', 'zh, i-cherokee; q=0.6');
  1146. $this->assertEquals(array('zh', 'cherokee'), $request->getLanguages());
  1147. }
  1148. public function testGetRequestFormat()
  1149. {
  1150. $request = new Request();
  1151. $this->assertEquals('html', $request->getRequestFormat());
  1152. // Ensure that setting different default values over time is possible,
  1153. // aka. setRequestFormat determines the state.
  1154. $this->assertEquals('json', $request->getRequestFormat('json'));
  1155. $this->assertEquals('html', $request->getRequestFormat('html'));
  1156. $request = new Request();
  1157. $this->assertNull($request->getRequestFormat(null));
  1158. $request = new Request();
  1159. $this->assertNull($request->setRequestFormat('foo'));
  1160. $this->assertEquals('foo', $request->getRequestFormat(null));
  1161. $request = new Request(array('_format' => 'foo'));
  1162. $this->assertEquals('html', $request->getRequestFormat());
  1163. }
  1164. public function testHasSession()
  1165. {
  1166. $request = new Request();
  1167. $this->assertFalse($request->hasSession());
  1168. $request->setSession(new Session(new MockArraySessionStorage()));
  1169. $this->assertTrue($request->hasSession());
  1170. }
  1171. public function testGetSession()
  1172. {
  1173. $request = new Request();
  1174. $request->setSession(new Session(new MockArraySessionStorage()));
  1175. $this->assertTrue($request->hasSession());
  1176. $session = $request->getSession();
  1177. $this->assertObjectHasAttribute('storage', $session);
  1178. $this->assertObjectHasAttribute('flashName', $session);
  1179. $this->assertObjectHasAttribute('attributeName', $session);
  1180. }
  1181. public function testHasPreviousSession()
  1182. {
  1183. $request = new Request();
  1184. $this->assertFalse($request->hasPreviousSession());
  1185. $request->cookies->set('MOCKSESSID', 'foo');
  1186. $this->assertFalse($request->hasPreviousSession());
  1187. $request->setSession(new Session(new MockArraySessionStorage()));
  1188. $this->assertTrue($request->hasPreviousSession());
  1189. }
  1190. public function testToString()
  1191. {
  1192. $request = new Request();
  1193. $request->headers->set('Accept-language', 'zh, en-us; q=0.8, en; q=0.6');
  1194. $this->assertContains('Accept-Language: zh, en-us; q=0.8, en; q=0.6', $request->__toString());
  1195. }
  1196. public function testIsMethod()
  1197. {
  1198. $request = new Request();
  1199. $request->setMethod('POST');
  1200. $this->assertTrue($request->isMethod('POST'));
  1201. $this->assertTrue($request->isMethod('post'));
  1202. $this->assertFalse($request->isMethod('GET'));
  1203. $this->assertFalse($request->isMethod('get'));
  1204. $request->setMethod('GET');
  1205. $this->assertTrue($request->isMethod('GET'));
  1206. $this->assertTrue($request->isMethod('get'));
  1207. $this->assertFalse($request->isMethod('POST'));
  1208. $this->assertFalse($request->isMethod('post'));
  1209. }
  1210. /**
  1211. * @dataProvider getBaseUrlData
  1212. */
  1213. public function testGetBaseUrl($uri, $server, $expectedBaseUrl, $expectedPathInfo)
  1214. {
  1215. $request = Request::create($uri, 'GET', array(), array(), array(), $server);
  1216. $this->assertSame($expectedBaseUrl, $request->getBaseUrl(), 'baseUrl');
  1217. $this->assertSame($expectedPathInfo, $request->getPathInfo(), 'pathInfo');
  1218. }
  1219. public function getBaseUrlData()
  1220. {
  1221. return array(
  1222. array(
  1223. '/fruit/strawberry/1234index.php/blah',
  1224. array(
  1225. 'SCRIPT_FILENAME' => 'E:/Sites/cc-new/public_html/fruit/index.php',
  1226. 'SCRIPT_NAME' => '/fruit/index.php',
  1227. 'PHP_SELF' => '/fruit/index.php',
  1228. ),
  1229. '/fruit',
  1230. '/strawberry/1234index.php/blah',
  1231. ),
  1232. array(
  1233. '/fruit/strawberry/1234index.php/blah',
  1234. array(
  1235. 'SCRIPT_FILENAME' => 'E:/Sites/cc-new/public_html/index.php',
  1236. 'SCRIPT_NAME' => '/index.php',
  1237. 'PHP_SELF' => '/index.php',
  1238. ),
  1239. '',
  1240. '/fruit/strawberry/1234index.php/blah',
  1241. ),
  1242. array(
  1243. '/foo%20bar/',
  1244. array(
  1245. 'SCRIPT_FILENAME' => '/home/John Doe/public_html/foo bar/app.php',
  1246. 'SCRIPT_NAME' => '/foo bar/app.php',
  1247. 'PHP_SELF' => '/foo bar/app.php',
  1248. ),
  1249. '/foo%20bar',
  1250. '/',
  1251. ),
  1252. array(
  1253. '/foo%20bar/home',
  1254. array(
  1255. 'SCRIPT_FILENAME' => '/home/John Doe/public_html/foo bar/app.php',
  1256. 'SCRIPT_NAME' => '/foo bar/app.php',
  1257. 'PHP_SELF' => '/foo bar/app.php',
  1258. ),
  1259. '/foo%20bar',
  1260. '/home',
  1261. ),
  1262. array(
  1263. '/foo%20bar/app.php/home',
  1264. array(
  1265. 'SCRIPT_FILENAME' => '/home/John Doe/public_html/foo bar/app.php',
  1266. 'SCRIPT_NAME' => '/foo bar/app.php',
  1267. 'PHP_SELF' => '/foo bar/app.php',
  1268. ),
  1269. '/foo%20bar/app.php',
  1270. '/home',
  1271. ),
  1272. array(
  1273. '/foo%20bar/app.php/home%3Dbaz',
  1274. array(
  1275. 'SCRIPT_FILENAME' => '/home/John Doe/public_html/foo bar/app.php',
  1276. 'SCRIPT_NAME' => '/foo bar/app.php',
  1277. 'PHP_SELF' => '/foo bar/app.php',
  1278. ),
  1279. '/foo%20bar/app.php',
  1280. '/home%3Dbaz',
  1281. ),
  1282. array(
  1283. '/foo/bar+baz',
  1284. array(
  1285. 'SCRIPT_FILENAME' => '/home/John Doe/public_html/foo/app.php',
  1286. 'SCRIPT_NAME' => '/foo/app.php',
  1287. 'PHP_SELF' => '/foo/app.php',
  1288. ),
  1289. '/foo',
  1290. '/bar+baz',
  1291. ),
  1292. );
  1293. }
  1294. /**
  1295. * @dataProvider urlencodedStringPrefixData
  1296. */
  1297. public function testUrlencodedStringPrefix($string, $prefix, $expect)
  1298. {
  1299. $request = new Request();
  1300. $me = new \ReflectionMethod($request, 'getUrlencodedPrefix');
  1301. $me->setAccessible(true);
  1302. $this->assertSame($expect, $me->invoke($request, $string, $prefix));
  1303. }
  1304. public function urlencodedStringPrefixData()
  1305. {
  1306. return array(
  1307. array('foo', 'foo', 'foo'),
  1308. array('fo%6f', 'foo', 'fo%6f'),
  1309. array('foo/bar', 'foo', 'foo'),
  1310. array('fo%6f/bar', 'foo', 'fo%6f'),
  1311. array('f%6f%6f/bar', 'foo', 'f%6f%6f'),
  1312. array('%66%6F%6F/bar', 'foo', '%66%6F%6F'),
  1313. array('fo+o/bar', 'fo+o', 'fo+o'),
  1314. array('fo%2Bo/bar', 'fo+o', 'fo%2Bo'),
  1315. );
  1316. }
  1317. private function disableHttpMethodParameterOverride()
  1318. {
  1319. $class = new \ReflectionClass('Symfony\\Component\\HttpFoundation\\Request');
  1320. $property = $class->getProperty('httpMethodParameterOverride');
  1321. $property->setAccessible(true);
  1322. $property->setValue(false);
  1323. }
  1324. private function getRequestInstanceForClientIpTests($remoteAddr, $httpForwardedFor, $trustedProxies)
  1325. {
  1326. $request = new Request();
  1327. $server = array('REMOTE_ADDR' => $remoteAddr);
  1328. if (null !== $httpForwardedFor) {
  1329. $server['HTTP_X_FORWARDED_FOR'] = $httpForwardedFor;
  1330. }
  1331. if ($trustedProxies) {
  1332. Request::setTrustedProxies($trustedProxies);
  1333. }
  1334. $request->initialize(array(), array(), array(), array(), array(), $server);
  1335. return $request;
  1336. }
  1337. private function getRequestInstanceForClientIpsForwardedTests($remoteAddr, $httpForwarded, $trustedProxies)
  1338. {
  1339. $request = new Request();
  1340. $server = array('REMOTE_ADDR' => $remoteAddr);
  1341. if (null !== $httpForwarded) {
  1342. $server['HTTP_FORWARDED'] = $httpForwarded;
  1343. }
  1344. if ($trustedProxies) {
  1345. Request::setTrustedProxies($trustedProxies);
  1346. }
  1347. $request->initialize(array(), array(), array(), array(), array(), $server);
  1348. return $request;
  1349. }
  1350. public function testTrustedProxies()
  1351. {
  1352. $request = Request::create('http://example.com/');
  1353. $request->server->set('REMOTE_ADDR', '3.3.3.3');
  1354. $request->headers->set('X_FORWARDED_FOR', '1.1.1.1, 2.2.2.2');
  1355. $request->headers->set('X_FORWARDED_HOST', 'foo.example.com, real.example.com:8080');
  1356. $request->headers->set('X_FORWARDED_PROTO', 'https');
  1357. $request->headers->set('X_FORWARDED_PORT', 443);
  1358. $request->headers->set('X_MY_FOR', '3.3.3.3, 4.4.4.4');
  1359. $request->headers->set('X_MY_HOST', 'my.example.com');
  1360. $request->headers->set('X_MY_PROTO', 'http');
  1361. $request->headers->set('X_MY_PORT', 81);
  1362. // no trusted proxies
  1363. $this->assertEquals('3.3.3.3', $request->getClientIp());
  1364. $this->assertEquals('example.com', $request->getHost());
  1365. $this->assertEquals(80, $request->getPort());
  1366. $this->assertFalse($request->isSecure());
  1367. // disabling proxy trusting
  1368. Request::setTrustedProxies(array());
  1369. $this->assertEquals('3.3.3.3', $request->getClientIp());
  1370. $this->assertEquals('example.com', $request->getHost());
  1371. $this->assertEquals(80, $request->getPort());
  1372. $this->assertFalse($request->isSecure());
  1373. // request is forwarded by a non-trusted proxy
  1374. Request::setTrustedProxies(array('2.2.2.2'));
  1375. $this->assertEquals('3.3.3.3', $request->getClientIp());
  1376. $this->assertEquals('example.com', $request->getHost());
  1377. $this->assertEquals(80, $request->getPort());
  1378. $this->assertFalse($request->isSecure());
  1379. // trusted proxy via setTrustedProxies()
  1380. Request::setTrustedProxies(array('3.3.3.3', '2.2.2.2'));
  1381. $this->assertEquals('1.1.1.1', $request->getClientIp());
  1382. $this->assertEquals('real.example.com', $request->getHost());
  1383. $this->assertEquals(443, $request->getPort());
  1384. $this->assertTrue($request->isSecure());
  1385. // trusted proxy via setTrustedProxies()
  1386. Request::setTrustedProxies(array('3.3.3.4', '2.2.2.2'));
  1387. $this->assertEquals('3.3.3.3', $request->getClientIp());
  1388. $this->assertEquals('example.com', $request->getHost());
  1389. $this->assertEquals(80, $request->getPort());
  1390. $this->assertFalse($request->isSecure());
  1391. // check various X_FORWARDED_PROTO header values
  1392. Request::setTrustedProxies(array('3.3.3.3', '2.2.2.2'));
  1393. $request->headers->set('X_FORWARDED_PROTO', 'ssl');
  1394. $this->assertTrue($request->isSecure());
  1395. $request->headers->set('X_FORWARDED_PROTO', 'https, http');
  1396. $this->assertTrue($request->isSecure());
  1397. // custom header names
  1398. Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, 'X_MY_FOR');
  1399. Request::setTrustedHeaderName(Request::HEADER_CLIENT_HOST, 'X_MY_HOST');
  1400. Request::setTrustedHeaderName(Request::HEADER_CLIENT_PORT, 'X_MY_PORT');
  1401. Request::setTrustedHeaderName(Request::HEADER_CLIENT_PROTO, 'X_MY_PROTO');
  1402. $this->assertEquals('4.4.4.4', $request->getClientIp());
  1403. $this->assertEquals('my.example.com', $request->getHost());
  1404. $this->assertEquals(81, $request->getPort());
  1405. $this->assertFalse($request->isSecure());
  1406. // disabling via empty header names
  1407. Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, null);
  1408. Request::setTrustedHeaderName(Request::HEADER_CLIENT_HOST, null);
  1409. Request::setTrustedHeaderName(Request::HEADER_CLIENT_PORT, null);
  1410. Request::setTrustedHeaderName(Request::HEADER_CLIENT_PROTO, null);
  1411. $this->assertEquals('3.3.3.3', $request->getClientIp());
  1412. $this->assertEquals('example.com', $request->getHost());
  1413. $this->assertEquals(80, $request->getPort());
  1414. $this->assertFalse($request->isSecure());
  1415. // reset
  1416. Request::setTrustedProxies(array());
  1417. Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, 'X_FORWARDED_FOR');
  1418. Request::setTrustedHeaderName(Request::HEADER_CLIENT_HOST, 'X_FORWARDED_HOST');
  1419. Request::setTrustedHeaderName(Request::HEADER_CLIENT_PORT, 'X_FORWARDED_PORT');
  1420. Request::setTrustedHeaderName(Request::HEADER_CLIENT_PROTO, 'X_FORWARDED_PROTO');
  1421. }
  1422. /**
  1423. * @expectedException \InvalidArgumentException
  1424. */
  1425. public function testSetTrustedProxiesInvalidHeaderName()
  1426. {
  1427. Request::create('http://example.com/');
  1428. Request::setTrustedHeaderName('bogus name', 'X_MY_FOR');
  1429. }
  1430. /**
  1431. * @expectedException \InvalidArgumentException
  1432. */
  1433. public function testGetTrustedProxiesInvalidHeaderName()
  1434. {
  1435. Request::create('http://example.com/');
  1436. Request::getTrustedHeaderName('bogus name');
  1437. }
  1438. /**
  1439. * @dataProvider iisRequestUriProvider
  1440. */
  1441. public function testIISRequestUri($headers, $server, $expectedRequestUri)
  1442. {
  1443. $request = new Request();
  1444. $request->headers->replace($headers);
  1445. $request->server->replace($server);
  1446. $this->assertEquals($expectedRequestUri, $request->getRequestUri(), '->getRequestUri() is correct');
  1447. $subRequestUri = '/bar/foo';
  1448. $subRequest = Request::create($subRequestUri, 'get', array(), array(), array(), $request->server->all());
  1449. $this->assertEquals($subRequestUri, $subRequest->getRequestUri(), '->getRequestUri() is correct in sub request');
  1450. }
  1451. public function iisRequestUriProvider()
  1452. {
  1453. return array(
  1454. array(
  1455. array(
  1456. 'X_ORIGINAL_URL' => '/foo/bar',
  1457. ),
  1458. array(),
  1459. '/foo/bar',
  1460. ),
  1461. array(
  1462. array(
  1463. 'X_REWRITE_URL' => '/foo/bar',
  1464. ),
  1465. array(),
  1466. '/foo/bar',
  1467. ),
  1468. array(
  1469. array(),
  1470. array(
  1471. 'IIS_WasUrlRewritten' => '1',
  1472. 'UNENCODED_URL' => '/foo/bar',
  1473. ),
  1474. '/foo/bar',
  1475. ),
  1476. array(
  1477. array(
  1478. 'X_ORIGINAL_URL' => '/foo/bar',
  1479. ),
  1480. array(
  1481. 'HTTP_X_ORIGINAL_URL' => '/foo/bar',
  1482. ),
  1483. '/foo/bar',
  1484. ),
  1485. array(
  1486. array(
  1487. 'X_ORIGINAL_URL' => '/foo/bar',
  1488. ),
  1489. array(
  1490. 'IIS_WasUrlRewritten' => '1',
  1491. 'UNENCODED_URL' => '/foo/bar',
  1492. ),
  1493. '/foo/bar',
  1494. ),
  1495. array(
  1496. array(
  1497. 'X_ORIGINAL_URL' => '/foo/bar',
  1498. ),
  1499. array(
  1500. 'HTTP_X_ORIGINAL_URL' => '/foo/bar',
  1501. 'IIS_WasUrlRewritten' => '1',
  1502. 'UNENCODED_URL' => '/foo/bar',
  1503. ),
  1504. '/foo/bar',
  1505. ),
  1506. array(
  1507. array(),
  1508. array(
  1509. 'ORIG_PATH_INFO' => '/foo/bar',
  1510. ),
  1511. '/foo/bar',
  1512. ),
  1513. array(
  1514. array(),
  1515. array(
  1516. 'ORIG_PATH_INFO' => '/foo/bar',
  1517. 'QUERY_STRING' => 'foo=bar',
  1518. ),
  1519. '/foo/bar?foo=bar',
  1520. ),
  1521. );
  1522. }
  1523. public function testTrustedHosts()
  1524. {
  1525. // create a request
  1526. $request = Request::create('/');
  1527. // no trusted host set -> no host check
  1528. $request->headers->set('host', 'evil.com');
  1529. $this->assertEquals('evil.com', $request->getHost());
  1530. // add a trusted domain and all its subdomains
  1531. Request::setTrustedHosts(array('^([a-z]{9}\.)?trusted\.com$'));
  1532. // untrusted host
  1533. $request->headers->set('host', 'evil.com');
  1534. try {
  1535. $request->getHost();
  1536. $this->fail('Request::getHost() should throw an exception when host is not trusted.');
  1537. } catch (\UnexpectedValueException $e) {
  1538. $this->assertEquals('Untrusted Host "evil.com"', $e->getMessage());
  1539. }
  1540. // trusted hosts
  1541. $request->headers->set('host', 'trusted.com');
  1542. $this->assertEquals('trusted.com', $request->getHost());
  1543. $this->assertEquals(80, $request->getPort());
  1544. $request->server->set('HTTPS', true);
  1545. $request->headers->set('host', 'trusted.com');
  1546. $this->assertEquals('trusted.com', $request->getHost());
  1547. $this->assertEquals(443, $request->getPort());
  1548. $request->server->set('HTTPS', false);
  1549. $request->headers->set('host', 'trusted.com:8000');
  1550. $this->assertEquals('trusted.com', $request->getHost());
  1551. $this->assertEquals(8000, $request->getPort());
  1552. $request->headers->set('host', 'subdomain.trusted.com');
  1553. $this->assertEquals('subdomain.trusted.com', $request->getHost());
  1554. // reset request for following tests
  1555. Request::setTrustedHosts(array());
  1556. }
  1557. public function testFactory()
  1558. {
  1559. Request::setFactory(function (array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null) {
  1560. return new NewRequest();
  1561. });
  1562. $this->assertEquals('foo', Request::create('/')->getFoo());
  1563. Request::setFactory(null);
  1564. }
  1565. /**
  1566. * @dataProvider getLongHostNames
  1567. */
  1568. public function testVeryLongHosts($host)
  1569. {
  1570. $start = microtime(true);
  1571. $request = Request::create('/');
  1572. $request->headers->set('host', $host);
  1573. $this->assertEquals($host, $request->getHost());
  1574. $this->assertLessThan(5, microtime(true) - $start);
  1575. }
  1576. /**
  1577. * @dataProvider getHostValidities
  1578. */
  1579. public function testHostValidity($host, $isValid, $expectedHost = null, $expectedPort = null)
  1580. {
  1581. $request = Request::create('/');
  1582. $request->headers->set('host', $host);
  1583. if ($isValid) {
  1584. $this->assertSame($expectedHost ?: $host, $request->getHost());
  1585. if ($expectedPort) {
  1586. $this->assertSame($expectedPort, $request->getPort());
  1587. }
  1588. } else {
  1589. if (method_exists($this, 'expectException')) {
  1590. $this->expectException('UnexpectedValueException');
  1591. $this->expectExceptionMessage('Invalid Host');
  1592. } else {
  1593. $this->setExpectedException('UnexpectedValueException', 'Invalid Host');
  1594. }
  1595. $request->getHost();
  1596. }
  1597. }
  1598. public function getHostValidities()
  1599. {
  1600. return array(
  1601. array('.a', false),
  1602. array('a..', false),
  1603. array('a.', true),
  1604. array("\xE9", false),
  1605. array('[::1]', true),
  1606. array('[::1]:80', true, '[::1]', 80),
  1607. array(str_repeat('.', 101), false),
  1608. );
  1609. }
  1610. public function getLongHostNames()
  1611. {
  1612. return array(
  1613. array('a'.str_repeat('.a', 40000)),
  1614. array(str_repeat(':', 101)),
  1615. );
  1616. }
  1617. /**
  1618. * @dataProvider methodIdempotentProvider
  1619. */
  1620. public function testMethodIdempotent($method, $idempotent)
  1621. {
  1622. $request = new Request();
  1623. $request->setMethod($method);
  1624. $this->assertEquals($idempotent, $request->isMethodIdempotent());
  1625. }
  1626. public function methodIdempotentProvider()
  1627. {
  1628. return array(
  1629. array('HEAD', true),
  1630. array('GET', true),
  1631. array('POST', false),
  1632. array('PUT', true),
  1633. array('PATCH', false),
  1634. array('DELETE', true),
  1635. array('PURGE', true),
  1636. array('OPTIONS', true),
  1637. array('TRACE', true),
  1638. array('CONNECT', false),
  1639. );
  1640. }
  1641. /**
  1642. * @dataProvider methodSafeProvider
  1643. */
  1644. public function testMethodSafe($method, $safe)
  1645. {
  1646. $request = new Request();
  1647. $request->setMethod($method);
  1648. $this->assertEquals($safe, $request->isMethodSafe(false));
  1649. }
  1650. public function methodSafeProvider()
  1651. {
  1652. return array(
  1653. array('HEAD', true),
  1654. array('GET', true),
  1655. array('POST', false),
  1656. array('PUT', false),
  1657. array('PATCH', false),
  1658. array('DELETE', false),
  1659. array('PURGE', false),
  1660. array('OPTIONS', true),
  1661. array('TRACE', true),
  1662. array('CONNECT', false),
  1663. );
  1664. }
  1665. /**
  1666. * @group legacy
  1667. * @expectedDeprecation Checking only for cacheable HTTP methods with Symfony\Component\HttpFoundation\Request::isMethodSafe() is deprecated since version 3.2 and will throw an exception in 4.0. Disable checking only for cacheable methods by calling the method with `false` as first argument or use the Request::isMethodCacheable() instead.
  1668. */
  1669. public function testMethodSafeChecksCacheable()
  1670. {
  1671. $request = new Request();
  1672. $request->setMethod('OPTIONS');
  1673. $this->assertFalse($request->isMethodSafe());
  1674. }
  1675. /**
  1676. * @dataProvider methodCacheableProvider
  1677. */
  1678. public function testMethodCacheable($method, $chacheable)
  1679. {
  1680. $request = new Request();
  1681. $request->setMethod($method);
  1682. $this->assertEquals($chacheable, $request->isMethodCacheable());
  1683. }
  1684. public function methodCacheableProvider()
  1685. {
  1686. return array(
  1687. array('HEAD', true),
  1688. array('GET', true),
  1689. array('POST', false),
  1690. array('PUT', false),
  1691. array('PATCH', false),
  1692. array('DELETE', false),
  1693. array('PURGE', false),
  1694. array('OPTIONS', false),
  1695. array('TRACE', false),
  1696. array('CONNECT', false),
  1697. );
  1698. }
  1699. }
  1700. class RequestContentProxy extends Request
  1701. {
  1702. public function getContent($asResource = false)
  1703. {
  1704. return http_build_query(array('_method' => 'PUT', 'content' => 'mycontent'));
  1705. }
  1706. }
  1707. class NewRequest extends Request
  1708. {
  1709. public function getFoo()
  1710. {
  1711. return 'foo';
  1712. }
  1713. }