RequestTest.php 100 KB

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