RequestTest.php 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322
  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%5B0%5D=1&foo%5B1%5D=2', 'allows array notation'],
  643. ['foo=1&foo=2', 'foo=2', 'merges 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_Bar=&Foo_Baz=', '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. // Don't reorder nested query string keys
  654. ['foo[]=Z&foo[]=A', 'foo%5B0%5D=Z&foo%5B1%5D=A', 'keeps order of values'],
  655. ['foo[Z]=B&foo[A]=B', 'foo%5BZ%5D=B&foo%5BA%5D=B', 'keeps order of keys'],
  656. ['utf8=✓', 'utf8=%E2%9C%93', 'encodes UTF-8'],
  657. ];
  658. }
  659. public function testGetQueryStringReturnsNull()
  660. {
  661. $request = new Request();
  662. $this->assertNull($request->getQueryString(), '->getQueryString() returns null for non-existent query string');
  663. $request->server->set('QUERY_STRING', '');
  664. $this->assertNull($request->getQueryString(), '->getQueryString() returns null for empty query string');
  665. }
  666. public function testGetHost()
  667. {
  668. $request = new Request();
  669. $request->initialize(['foo' => 'bar']);
  670. $this->assertEquals('', $request->getHost(), '->getHost() return empty string if not initialized');
  671. $request->initialize([], [], [], [], [], ['HTTP_HOST' => 'www.example.com']);
  672. $this->assertEquals('www.example.com', $request->getHost(), '->getHost() from Host Header');
  673. // Host header with port number
  674. $request->initialize([], [], [], [], [], ['HTTP_HOST' => 'www.example.com:8080']);
  675. $this->assertEquals('www.example.com', $request->getHost(), '->getHost() from Host Header with port number');
  676. // Server values
  677. $request->initialize([], [], [], [], [], ['SERVER_NAME' => 'www.example.com']);
  678. $this->assertEquals('www.example.com', $request->getHost(), '->getHost() from server name');
  679. $request->initialize([], [], [], [], [], ['SERVER_NAME' => 'www.example.com', 'HTTP_HOST' => 'www.host.com']);
  680. $this->assertEquals('www.host.com', $request->getHost(), '->getHost() value from Host header has priority over SERVER_NAME ');
  681. }
  682. public function testGetPort()
  683. {
  684. $request = Request::create('http://example.com', 'GET', [], [], [], [
  685. 'HTTP_X_FORWARDED_PROTO' => 'https',
  686. 'HTTP_X_FORWARDED_PORT' => '443',
  687. ]);
  688. $port = $request->getPort();
  689. $this->assertEquals(80, $port, 'Without trusted proxies FORWARDED_PROTO and FORWARDED_PORT are ignored.');
  690. Request::setTrustedProxies(['1.1.1.1'], Request::HEADER_X_FORWARDED_ALL);
  691. $request = Request::create('http://example.com', 'GET', [], [], [], [
  692. 'HTTP_X_FORWARDED_PROTO' => 'https',
  693. 'HTTP_X_FORWARDED_PORT' => '8443',
  694. ]);
  695. $this->assertEquals(80, $request->getPort(), 'With PROTO and PORT on untrusted connection server value takes precedence.');
  696. $request->server->set('REMOTE_ADDR', '1.1.1.1');
  697. $this->assertEquals(8443, $request->getPort(), 'With PROTO and PORT set PORT takes precedence.');
  698. $request = Request::create('http://example.com', 'GET', [], [], [], [
  699. 'HTTP_X_FORWARDED_PROTO' => 'https',
  700. ]);
  701. $this->assertEquals(80, $request->getPort(), 'With only PROTO set getPort() ignores trusted headers on untrusted connection.');
  702. $request->server->set('REMOTE_ADDR', '1.1.1.1');
  703. $this->assertEquals(443, $request->getPort(), 'With only PROTO set getPort() defaults to 443.');
  704. $request = Request::create('http://example.com', 'GET', [], [], [], [
  705. 'HTTP_X_FORWARDED_PROTO' => 'http',
  706. ]);
  707. $this->assertEquals(80, $request->getPort(), 'If X_FORWARDED_PROTO is set to HTTP getPort() ignores trusted headers on untrusted connection.');
  708. $request->server->set('REMOTE_ADDR', '1.1.1.1');
  709. $this->assertEquals(80, $request->getPort(), 'If X_FORWARDED_PROTO is set to HTTP getPort() returns port of the original request.');
  710. $request = Request::create('http://example.com', 'GET', [], [], [], [
  711. 'HTTP_X_FORWARDED_PROTO' => 'On',
  712. ]);
  713. $this->assertEquals(80, $request->getPort(), 'With only PROTO set and value is On, getPort() ignores trusted headers on untrusted connection.');
  714. $request->server->set('REMOTE_ADDR', '1.1.1.1');
  715. $this->assertEquals(443, $request->getPort(), 'With only PROTO set and value is On, getPort() defaults to 443.');
  716. $request = Request::create('http://example.com', 'GET', [], [], [], [
  717. 'HTTP_X_FORWARDED_PROTO' => '1',
  718. ]);
  719. $this->assertEquals(80, $request->getPort(), 'With only PROTO set and value is 1, getPort() ignores trusted headers on untrusted connection.');
  720. $request->server->set('REMOTE_ADDR', '1.1.1.1');
  721. $this->assertEquals(443, $request->getPort(), 'With only PROTO set and value is 1, getPort() defaults to 443.');
  722. $request = Request::create('http://example.com', 'GET', [], [], [], [
  723. 'HTTP_X_FORWARDED_PROTO' => 'something-else',
  724. ]);
  725. $port = $request->getPort();
  726. $this->assertEquals(80, $port, 'With only PROTO set and value is not recognized, getPort() defaults to 80.');
  727. }
  728. /**
  729. * @expectedException \RuntimeException
  730. */
  731. public function testGetHostWithFakeHttpHostValue()
  732. {
  733. $request = new Request();
  734. $request->initialize([], [], [], [], [], ['HTTP_HOST' => 'www.host.com?query=string']);
  735. $request->getHost();
  736. }
  737. public function testGetSetMethod()
  738. {
  739. $request = new Request();
  740. $this->assertEquals('GET', $request->getMethod(), '->getMethod() returns GET if no method is defined');
  741. $request->setMethod('get');
  742. $this->assertEquals('GET', $request->getMethod(), '->getMethod() returns an uppercased string');
  743. $request->setMethod('PURGE');
  744. $this->assertEquals('PURGE', $request->getMethod(), '->getMethod() returns the method even if it is not a standard one');
  745. $request->setMethod('POST');
  746. $this->assertEquals('POST', $request->getMethod(), '->getMethod() returns the method POST if no _method is defined');
  747. $request->setMethod('POST');
  748. $request->request->set('_method', 'purge');
  749. $this->assertEquals('POST', $request->getMethod(), '->getMethod() does not return the method from _method if defined and POST but support not enabled');
  750. $request = new Request();
  751. $request->setMethod('POST');
  752. $request->request->set('_method', 'purge');
  753. $this->assertFalse(Request::getHttpMethodParameterOverride(), 'httpMethodParameterOverride should be disabled by default');
  754. Request::enableHttpMethodParameterOverride();
  755. $this->assertTrue(Request::getHttpMethodParameterOverride(), 'httpMethodParameterOverride should be enabled now but it is not');
  756. $this->assertEquals('PURGE', $request->getMethod(), '->getMethod() returns the method from _method if defined and POST');
  757. $this->disableHttpMethodParameterOverride();
  758. $request = new Request();
  759. $request->setMethod('POST');
  760. $request->query->set('_method', 'purge');
  761. $this->assertEquals('POST', $request->getMethod(), '->getMethod() does not return the method from _method if defined and POST but support not enabled');
  762. $request = new Request();
  763. $request->setMethod('POST');
  764. $request->query->set('_method', 'purge');
  765. Request::enableHttpMethodParameterOverride();
  766. $this->assertEquals('PURGE', $request->getMethod(), '->getMethod() returns the method from _method if defined and POST');
  767. $this->disableHttpMethodParameterOverride();
  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 even though _method is set if defined and POST');
  772. $request = new Request();
  773. $request->setMethod('POST');
  774. $request->headers->set('X-HTTP-METHOD-OVERRIDE', 'delete');
  775. $this->assertEquals('DELETE', $request->getMethod(), '->getMethod() returns the method from X-HTTP-Method-Override if defined and POST');
  776. $request = new Request();
  777. $request->setMethod('POST');
  778. $request->query->set('_method', ['delete', 'patch']);
  779. $this->assertSame('POST', $request->getMethod(), '->getMethod() returns the request method if invalid type is defined in query');
  780. }
  781. /**
  782. * @dataProvider getClientIpsProvider
  783. */
  784. public function testGetClientIp($expected, $remoteAddr, $httpForwardedFor, $trustedProxies)
  785. {
  786. $request = $this->getRequestInstanceForClientIpTests($remoteAddr, $httpForwardedFor, $trustedProxies);
  787. $this->assertEquals($expected[0], $request->getClientIp());
  788. }
  789. /**
  790. * @dataProvider getClientIpsProvider
  791. */
  792. public function testGetClientIps($expected, $remoteAddr, $httpForwardedFor, $trustedProxies)
  793. {
  794. $request = $this->getRequestInstanceForClientIpTests($remoteAddr, $httpForwardedFor, $trustedProxies);
  795. $this->assertEquals($expected, $request->getClientIps());
  796. }
  797. /**
  798. * @dataProvider getClientIpsForwardedProvider
  799. */
  800. public function testGetClientIpsForwarded($expected, $remoteAddr, $httpForwarded, $trustedProxies)
  801. {
  802. $request = $this->getRequestInstanceForClientIpsForwardedTests($remoteAddr, $httpForwarded, $trustedProxies);
  803. $this->assertEquals($expected, $request->getClientIps());
  804. }
  805. public function getClientIpsForwardedProvider()
  806. {
  807. // $expected $remoteAddr $httpForwarded $trustedProxies
  808. return [
  809. [['127.0.0.1'], '127.0.0.1', 'for="_gazonk"', null],
  810. [['127.0.0.1'], '127.0.0.1', 'for="_gazonk"', ['127.0.0.1']],
  811. [['88.88.88.88'], '127.0.0.1', 'for="88.88.88.88:80"', ['127.0.0.1']],
  812. [['192.0.2.60'], '::1', 'for=192.0.2.60;proto=http;by=203.0.113.43', ['::1']],
  813. [['2620:0:1cfe:face:b00c::3', '192.0.2.43'], '::1', 'for=192.0.2.43, for="[2620:0:1cfe:face:b00c::3]"', ['::1']],
  814. [['2001:db8:cafe::17'], '::1', 'for="[2001:db8:cafe::17]:4711', ['::1']],
  815. ];
  816. }
  817. public function getClientIpsProvider()
  818. {
  819. // $expected $remoteAddr $httpForwardedFor $trustedProxies
  820. return [
  821. // simple IPv4
  822. [['88.88.88.88'], '88.88.88.88', null, null],
  823. // trust the IPv4 remote addr
  824. [['88.88.88.88'], '88.88.88.88', null, ['88.88.88.88']],
  825. // simple IPv6
  826. [['::1'], '::1', null, null],
  827. // trust the IPv6 remote addr
  828. [['::1'], '::1', null, ['::1']],
  829. // forwarded for with remote IPv4 addr not trusted
  830. [['127.0.0.1'], '127.0.0.1', '88.88.88.88', null],
  831. // forwarded for with remote IPv4 addr trusted + comma
  832. [['88.88.88.88'], '127.0.0.1', '88.88.88.88,', ['127.0.0.1']],
  833. // forwarded for with remote IPv4 and all FF addrs trusted
  834. [['88.88.88.88'], '127.0.0.1', '88.88.88.88', ['127.0.0.1', '88.88.88.88']],
  835. // forwarded for with remote IPv4 range trusted
  836. [['88.88.88.88'], '123.45.67.89', '88.88.88.88', ['123.45.67.0/24']],
  837. // forwarded for with remote IPv6 addr not trusted
  838. [['1620:0:1cfe:face:b00c::3'], '1620:0:1cfe:face:b00c::3', '2620:0:1cfe:face:b00c::3', null],
  839. // forwarded for with remote IPv6 addr trusted
  840. [['2620:0:1cfe:face:b00c::3'], '1620:0:1cfe:face:b00c::3', '2620:0:1cfe:face:b00c::3', ['1620:0:1cfe:face:b00c::3']],
  841. // forwarded for with remote IPv6 range trusted
  842. [['88.88.88.88'], '2a01:198:603:0:396e:4789:8e99:890f', '88.88.88.88', ['2a01:198:603:0::/65']],
  843. // multiple forwarded for with remote IPv4 addr trusted
  844. [['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']],
  845. // multiple forwarded for with remote IPv4 addr and some reverse proxies trusted
  846. [['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']],
  847. // multiple forwarded for with remote IPv4 addr and some reverse proxies trusted but in the middle
  848. [['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']],
  849. // multiple forwarded for with remote IPv4 addr and all reverse proxies trusted
  850. [['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']],
  851. // multiple forwarded for with remote IPv6 addr trusted
  852. [['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']],
  853. // multiple forwarded for with remote IPv6 addr and some reverse proxies trusted
  854. [['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']],
  855. // multiple forwarded for with remote IPv4 addr and some reverse proxies trusted but in the middle
  856. [['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']],
  857. // client IP with port
  858. [['88.88.88.88'], '127.0.0.1', '88.88.88.88:12345, 127.0.0.1', ['127.0.0.1']],
  859. // invalid forwarded IP is ignored
  860. [['88.88.88.88'], '127.0.0.1', 'unknown,88.88.88.88', ['127.0.0.1']],
  861. [['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']],
  862. ];
  863. }
  864. /**
  865. * @expectedException \Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException
  866. * @dataProvider getClientIpsWithConflictingHeadersProvider
  867. */
  868. public function testGetClientIpsWithConflictingHeaders($httpForwarded, $httpXForwardedFor)
  869. {
  870. $request = new Request();
  871. $server = [
  872. 'REMOTE_ADDR' => '88.88.88.88',
  873. 'HTTP_FORWARDED' => $httpForwarded,
  874. 'HTTP_X_FORWARDED_FOR' => $httpXForwardedFor,
  875. ];
  876. Request::setTrustedProxies(['88.88.88.88'], Request::HEADER_X_FORWARDED_ALL | Request::HEADER_FORWARDED);
  877. $request->initialize([], [], [], [], [], $server);
  878. $request->getClientIps();
  879. }
  880. /**
  881. * @dataProvider getClientIpsWithConflictingHeadersProvider
  882. */
  883. public function testGetClientIpsOnlyXHttpForwardedForTrusted($httpForwarded, $httpXForwardedFor)
  884. {
  885. $request = new Request();
  886. $server = [
  887. 'REMOTE_ADDR' => '88.88.88.88',
  888. 'HTTP_FORWARDED' => $httpForwarded,
  889. 'HTTP_X_FORWARDED_FOR' => $httpXForwardedFor,
  890. ];
  891. Request::setTrustedProxies(['88.88.88.88'], Request::HEADER_X_FORWARDED_FOR);
  892. $request->initialize([], [], [], [], [], $server);
  893. $this->assertSame(array_reverse(explode(',', $httpXForwardedFor)), $request->getClientIps());
  894. }
  895. public function getClientIpsWithConflictingHeadersProvider()
  896. {
  897. // $httpForwarded $httpXForwardedFor
  898. return [
  899. ['for=87.65.43.21', '192.0.2.60'],
  900. ['for=87.65.43.21, for=192.0.2.60', '192.0.2.60'],
  901. ['for=192.0.2.60', '192.0.2.60,87.65.43.21'],
  902. ['for="::face", for=192.0.2.60', '192.0.2.60,192.0.2.43'],
  903. ['for=87.65.43.21, for=192.0.2.60', '192.0.2.60,87.65.43.21'],
  904. ];
  905. }
  906. /**
  907. * @dataProvider getClientIpsWithAgreeingHeadersProvider
  908. */
  909. public function testGetClientIpsWithAgreeingHeaders($httpForwarded, $httpXForwardedFor, $expectedIps)
  910. {
  911. $request = new Request();
  912. $server = [
  913. 'REMOTE_ADDR' => '88.88.88.88',
  914. 'HTTP_FORWARDED' => $httpForwarded,
  915. 'HTTP_X_FORWARDED_FOR' => $httpXForwardedFor,
  916. ];
  917. Request::setTrustedProxies(['88.88.88.88'], -1);
  918. $request->initialize([], [], [], [], [], $server);
  919. $clientIps = $request->getClientIps();
  920. $this->assertSame($expectedIps, $clientIps);
  921. }
  922. public function getClientIpsWithAgreeingHeadersProvider()
  923. {
  924. // $httpForwarded $httpXForwardedFor
  925. return [
  926. ['for="192.0.2.60"', '192.0.2.60', ['192.0.2.60']],
  927. ['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']],
  928. ['for="[::face]", for=192.0.2.60', '::face,192.0.2.60', ['192.0.2.60', '::face']],
  929. ['for="192.0.2.60:80"', '192.0.2.60', ['192.0.2.60']],
  930. ['for=192.0.2.60;proto=http;by=203.0.113.43', '192.0.2.60', ['192.0.2.60']],
  931. ['for="[2001:db8:cafe::17]:4711"', '2001:db8:cafe::17', ['2001:db8:cafe::17']],
  932. ];
  933. }
  934. public function testGetContentWorksTwiceInDefaultMode()
  935. {
  936. $req = new Request();
  937. $this->assertEquals('', $req->getContent());
  938. $this->assertEquals('', $req->getContent());
  939. }
  940. public function testGetContentReturnsResource()
  941. {
  942. $req = new Request();
  943. $retval = $req->getContent(true);
  944. $this->assertInternalType('resource', $retval);
  945. $this->assertEquals('', fread($retval, 1));
  946. $this->assertTrue(feof($retval));
  947. }
  948. public function testGetContentReturnsResourceWhenContentSetInConstructor()
  949. {
  950. $req = new Request([], [], [], [], [], [], 'MyContent');
  951. $resource = $req->getContent(true);
  952. $this->assertInternalType('resource', $resource);
  953. $this->assertEquals('MyContent', stream_get_contents($resource));
  954. }
  955. public function testContentAsResource()
  956. {
  957. $resource = fopen('php://memory', 'r+');
  958. fwrite($resource, 'My other content');
  959. rewind($resource);
  960. $req = new Request([], [], [], [], [], [], $resource);
  961. $this->assertEquals('My other content', stream_get_contents($req->getContent(true)));
  962. $this->assertEquals('My other content', $req->getContent());
  963. }
  964. public function getContentCantBeCalledTwiceWithResourcesProvider()
  965. {
  966. return [
  967. 'Resource then fetch' => [true, false],
  968. 'Resource then resource' => [true, true],
  969. ];
  970. }
  971. /**
  972. * @dataProvider getContentCanBeCalledTwiceWithResourcesProvider
  973. */
  974. public function testGetContentCanBeCalledTwiceWithResources($first, $second)
  975. {
  976. $req = new Request();
  977. $a = $req->getContent($first);
  978. $b = $req->getContent($second);
  979. if ($first) {
  980. $a = stream_get_contents($a);
  981. }
  982. if ($second) {
  983. $b = stream_get_contents($b);
  984. }
  985. $this->assertSame($a, $b);
  986. }
  987. public function getContentCanBeCalledTwiceWithResourcesProvider()
  988. {
  989. return [
  990. 'Fetch then fetch' => [false, false],
  991. 'Fetch then resource' => [false, true],
  992. 'Resource then fetch' => [true, false],
  993. 'Resource then resource' => [true, true],
  994. ];
  995. }
  996. public function provideOverloadedMethods()
  997. {
  998. return [
  999. ['PUT'],
  1000. ['DELETE'],
  1001. ['PATCH'],
  1002. ['put'],
  1003. ['delete'],
  1004. ['patch'],
  1005. ];
  1006. }
  1007. /**
  1008. * @dataProvider provideOverloadedMethods
  1009. */
  1010. public function testCreateFromGlobals($method)
  1011. {
  1012. $normalizedMethod = strtoupper($method);
  1013. $_GET['foo1'] = 'bar1';
  1014. $_POST['foo2'] = 'bar2';
  1015. $_COOKIE['foo3'] = 'bar3';
  1016. $_FILES['foo4'] = ['bar4'];
  1017. $_SERVER['foo5'] = 'bar5';
  1018. $request = Request::createFromGlobals();
  1019. $this->assertEquals('bar1', $request->query->get('foo1'), '::fromGlobals() uses values from $_GET');
  1020. $this->assertEquals('bar2', $request->request->get('foo2'), '::fromGlobals() uses values from $_POST');
  1021. $this->assertEquals('bar3', $request->cookies->get('foo3'), '::fromGlobals() uses values from $_COOKIE');
  1022. $this->assertEquals(['bar4'], $request->files->get('foo4'), '::fromGlobals() uses values from $_FILES');
  1023. $this->assertEquals('bar5', $request->server->get('foo5'), '::fromGlobals() uses values from $_SERVER');
  1024. unset($_GET['foo1'], $_POST['foo2'], $_COOKIE['foo3'], $_FILES['foo4'], $_SERVER['foo5']);
  1025. $_SERVER['REQUEST_METHOD'] = $method;
  1026. $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
  1027. $request = RequestContentProxy::createFromGlobals();
  1028. $this->assertEquals($normalizedMethod, $request->getMethod());
  1029. $this->assertEquals('mycontent', $request->request->get('content'));
  1030. unset($_SERVER['REQUEST_METHOD'], $_SERVER['CONTENT_TYPE']);
  1031. Request::createFromGlobals();
  1032. Request::enableHttpMethodParameterOverride();
  1033. $_POST['_method'] = $method;
  1034. $_POST['foo6'] = 'bar6';
  1035. $_SERVER['REQUEST_METHOD'] = 'PoSt';
  1036. $request = Request::createFromGlobals();
  1037. $this->assertEquals($normalizedMethod, $request->getMethod());
  1038. $this->assertEquals('POST', $request->getRealMethod());
  1039. $this->assertEquals('bar6', $request->request->get('foo6'));
  1040. unset($_POST['_method'], $_POST['foo6'], $_SERVER['REQUEST_METHOD']);
  1041. $this->disableHttpMethodParameterOverride();
  1042. }
  1043. public function testOverrideGlobals()
  1044. {
  1045. $request = new Request();
  1046. $request->initialize(['foo' => 'bar']);
  1047. // as the Request::overrideGlobals really work, it erase $_SERVER, so we must backup it
  1048. $server = $_SERVER;
  1049. $request->overrideGlobals();
  1050. $this->assertEquals(['foo' => 'bar'], $_GET);
  1051. $request->initialize([], ['foo' => 'bar']);
  1052. $request->overrideGlobals();
  1053. $this->assertEquals(['foo' => 'bar'], $_POST);
  1054. $this->assertArrayNotHasKey('HTTP_X_FORWARDED_PROTO', $_SERVER);
  1055. $request->headers->set('X_FORWARDED_PROTO', 'https');
  1056. Request::setTrustedProxies(['1.1.1.1'], Request::HEADER_X_FORWARDED_ALL);
  1057. $this->assertFalse($request->isSecure());
  1058. $request->server->set('REMOTE_ADDR', '1.1.1.1');
  1059. $this->assertTrue($request->isSecure());
  1060. $request->overrideGlobals();
  1061. $this->assertArrayHasKey('HTTP_X_FORWARDED_PROTO', $_SERVER);
  1062. $request->headers->set('CONTENT_TYPE', 'multipart/form-data');
  1063. $request->headers->set('CONTENT_LENGTH', 12345);
  1064. $request->overrideGlobals();
  1065. $this->assertArrayHasKey('CONTENT_TYPE', $_SERVER);
  1066. $this->assertArrayHasKey('CONTENT_LENGTH', $_SERVER);
  1067. $request->initialize(['foo' => 'bar', 'baz' => 'foo']);
  1068. $request->query->remove('baz');
  1069. $request->overrideGlobals();
  1070. $this->assertEquals(['foo' => 'bar'], $_GET);
  1071. $this->assertEquals('foo=bar', $_SERVER['QUERY_STRING']);
  1072. $this->assertEquals('foo=bar', $request->server->get('QUERY_STRING'));
  1073. // restore initial $_SERVER array
  1074. $_SERVER = $server;
  1075. }
  1076. public function testGetScriptName()
  1077. {
  1078. $request = new Request();
  1079. $this->assertEquals('', $request->getScriptName());
  1080. $server = [];
  1081. $server['SCRIPT_NAME'] = '/index.php';
  1082. $request->initialize([], [], [], [], [], $server);
  1083. $this->assertEquals('/index.php', $request->getScriptName());
  1084. $server = [];
  1085. $server['ORIG_SCRIPT_NAME'] = '/frontend.php';
  1086. $request->initialize([], [], [], [], [], $server);
  1087. $this->assertEquals('/frontend.php', $request->getScriptName());
  1088. $server = [];
  1089. $server['SCRIPT_NAME'] = '/index.php';
  1090. $server['ORIG_SCRIPT_NAME'] = '/frontend.php';
  1091. $request->initialize([], [], [], [], [], $server);
  1092. $this->assertEquals('/index.php', $request->getScriptName());
  1093. }
  1094. public function testGetBasePath()
  1095. {
  1096. $request = new Request();
  1097. $this->assertEquals('', $request->getBasePath());
  1098. $server = [];
  1099. $server['SCRIPT_FILENAME'] = '/some/where/index.php';
  1100. $request->initialize([], [], [], [], [], $server);
  1101. $this->assertEquals('', $request->getBasePath());
  1102. $server = [];
  1103. $server['SCRIPT_FILENAME'] = '/some/where/index.php';
  1104. $server['SCRIPT_NAME'] = '/index.php';
  1105. $request->initialize([], [], [], [], [], $server);
  1106. $this->assertEquals('', $request->getBasePath());
  1107. $server = [];
  1108. $server['SCRIPT_FILENAME'] = '/some/where/index.php';
  1109. $server['PHP_SELF'] = '/index.php';
  1110. $request->initialize([], [], [], [], [], $server);
  1111. $this->assertEquals('', $request->getBasePath());
  1112. $server = [];
  1113. $server['SCRIPT_FILENAME'] = '/some/where/index.php';
  1114. $server['ORIG_SCRIPT_NAME'] = '/index.php';
  1115. $request->initialize([], [], [], [], [], $server);
  1116. $this->assertEquals('', $request->getBasePath());
  1117. }
  1118. public function testGetPathInfo()
  1119. {
  1120. $request = new Request();
  1121. $this->assertEquals('/', $request->getPathInfo());
  1122. $server = [];
  1123. $server['REQUEST_URI'] = '/path/info';
  1124. $request->initialize([], [], [], [], [], $server);
  1125. $this->assertEquals('/path/info', $request->getPathInfo());
  1126. $server = [];
  1127. $server['REQUEST_URI'] = '/path%20test/info';
  1128. $request->initialize([], [], [], [], [], $server);
  1129. $this->assertEquals('/path%20test/info', $request->getPathInfo());
  1130. $server = [];
  1131. $server['REQUEST_URI'] = '?a=b';
  1132. $request->initialize([], [], [], [], [], $server);
  1133. $this->assertEquals('/', $request->getPathInfo());
  1134. }
  1135. public function testGetParameterPrecedence()
  1136. {
  1137. $request = new Request();
  1138. $request->attributes->set('foo', 'attr');
  1139. $request->query->set('foo', 'query');
  1140. $request->request->set('foo', 'body');
  1141. $this->assertSame('attr', $request->get('foo'));
  1142. $request->attributes->remove('foo');
  1143. $this->assertSame('query', $request->get('foo'));
  1144. $request->query->remove('foo');
  1145. $this->assertSame('body', $request->get('foo'));
  1146. $request->request->remove('foo');
  1147. $this->assertNull($request->get('foo'));
  1148. }
  1149. public function testGetPreferredLanguage()
  1150. {
  1151. $request = new Request();
  1152. $this->assertNull($request->getPreferredLanguage());
  1153. $this->assertNull($request->getPreferredLanguage([]));
  1154. $this->assertEquals('fr', $request->getPreferredLanguage(['fr']));
  1155. $this->assertEquals('fr', $request->getPreferredLanguage(['fr', 'en']));
  1156. $this->assertEquals('en', $request->getPreferredLanguage(['en', 'fr']));
  1157. $this->assertEquals('fr-ch', $request->getPreferredLanguage(['fr-ch', 'fr-fr']));
  1158. $request = new Request();
  1159. $request->headers->set('Accept-language', 'zh, en-us; q=0.8, en; q=0.6');
  1160. $this->assertEquals('en', $request->getPreferredLanguage(['en', 'en-us']));
  1161. $request = new Request();
  1162. $request->headers->set('Accept-language', 'zh, en-us; q=0.8, en; q=0.6');
  1163. $this->assertEquals('en', $request->getPreferredLanguage(['fr', 'en']));
  1164. $request = new Request();
  1165. $request->headers->set('Accept-language', 'zh, en-us; q=0.8');
  1166. $this->assertEquals('en', $request->getPreferredLanguage(['fr', 'en']));
  1167. $request = new Request();
  1168. $request->headers->set('Accept-language', 'zh, en-us; q=0.8, fr-fr; q=0.6, fr; q=0.5');
  1169. $this->assertEquals('en', $request->getPreferredLanguage(['fr', 'en']));
  1170. }
  1171. public function testIsXmlHttpRequest()
  1172. {
  1173. $request = new Request();
  1174. $this->assertFalse($request->isXmlHttpRequest());
  1175. $request->headers->set('X-Requested-With', 'XMLHttpRequest');
  1176. $this->assertTrue($request->isXmlHttpRequest());
  1177. $request->headers->remove('X-Requested-With');
  1178. $this->assertFalse($request->isXmlHttpRequest());
  1179. }
  1180. /**
  1181. * @requires extension intl
  1182. */
  1183. public function testIntlLocale()
  1184. {
  1185. $request = new Request();
  1186. $request->setDefaultLocale('fr');
  1187. $this->assertEquals('fr', $request->getLocale());
  1188. $this->assertEquals('fr', \Locale::getDefault());
  1189. $request->setLocale('en');
  1190. $this->assertEquals('en', $request->getLocale());
  1191. $this->assertEquals('en', \Locale::getDefault());
  1192. $request->setDefaultLocale('de');
  1193. $this->assertEquals('en', $request->getLocale());
  1194. $this->assertEquals('en', \Locale::getDefault());
  1195. }
  1196. public function testGetCharsets()
  1197. {
  1198. $request = new Request();
  1199. $this->assertEquals([], $request->getCharsets());
  1200. $request->headers->set('Accept-Charset', 'ISO-8859-1, US-ASCII, UTF-8; q=0.8, ISO-10646-UCS-2; q=0.6');
  1201. $this->assertEquals([], $request->getCharsets()); // testing caching
  1202. $request = new Request();
  1203. $request->headers->set('Accept-Charset', 'ISO-8859-1, US-ASCII, UTF-8; q=0.8, ISO-10646-UCS-2; q=0.6');
  1204. $this->assertEquals(['ISO-8859-1', 'US-ASCII', 'UTF-8', 'ISO-10646-UCS-2'], $request->getCharsets());
  1205. $request = new Request();
  1206. $request->headers->set('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7');
  1207. $this->assertEquals(['ISO-8859-1', 'utf-8', '*'], $request->getCharsets());
  1208. }
  1209. public function testGetEncodings()
  1210. {
  1211. $request = new Request();
  1212. $this->assertEquals([], $request->getEncodings());
  1213. $request->headers->set('Accept-Encoding', 'gzip,deflate,sdch');
  1214. $this->assertEquals([], $request->getEncodings()); // testing caching
  1215. $request = new Request();
  1216. $request->headers->set('Accept-Encoding', 'gzip,deflate,sdch');
  1217. $this->assertEquals(['gzip', 'deflate', 'sdch'], $request->getEncodings());
  1218. $request = new Request();
  1219. $request->headers->set('Accept-Encoding', 'gzip;q=0.4,deflate;q=0.9,compress;q=0.7');
  1220. $this->assertEquals(['deflate', 'compress', 'gzip'], $request->getEncodings());
  1221. }
  1222. public function testGetAcceptableContentTypes()
  1223. {
  1224. $request = new Request();
  1225. $this->assertEquals([], $request->getAcceptableContentTypes());
  1226. $request->headers->set('Accept', 'application/vnd.wap.wmlscriptc, text/vnd.wap.wml, application/vnd.wap.xhtml+xml, application/xhtml+xml, text/html, multipart/mixed, */*');
  1227. $this->assertEquals([], $request->getAcceptableContentTypes()); // testing caching
  1228. $request = new Request();
  1229. $request->headers->set('Accept', 'application/vnd.wap.wmlscriptc, text/vnd.wap.wml, application/vnd.wap.xhtml+xml, application/xhtml+xml, text/html, multipart/mixed, */*');
  1230. $this->assertEquals(['application/vnd.wap.wmlscriptc', 'text/vnd.wap.wml', 'application/vnd.wap.xhtml+xml', 'application/xhtml+xml', 'text/html', 'multipart/mixed', '*/*'], $request->getAcceptableContentTypes());
  1231. }
  1232. public function testGetLanguages()
  1233. {
  1234. $request = new Request();
  1235. $this->assertEquals([], $request->getLanguages());
  1236. $request = new Request();
  1237. $request->headers->set('Accept-language', 'zh, en-us; q=0.8, en; q=0.6');
  1238. $this->assertEquals(['zh', 'en_US', 'en'], $request->getLanguages());
  1239. $this->assertEquals(['zh', 'en_US', 'en'], $request->getLanguages());
  1240. $request = new Request();
  1241. $request->headers->set('Accept-language', 'zh, en-us; q=0.6, en; q=0.8');
  1242. $this->assertEquals(['zh', 'en', 'en_US'], $request->getLanguages()); // Test out of order qvalues
  1243. $request = new Request();
  1244. $request->headers->set('Accept-language', 'zh, en, en-us');
  1245. $this->assertEquals(['zh', 'en', 'en_US'], $request->getLanguages()); // Test equal weighting without qvalues
  1246. $request = new Request();
  1247. $request->headers->set('Accept-language', 'zh; q=0.6, en, en-us; q=0.6');
  1248. $this->assertEquals(['en', 'zh', 'en_US'], $request->getLanguages()); // Test equal weighting with qvalues
  1249. $request = new Request();
  1250. $request->headers->set('Accept-language', 'zh, i-cherokee; q=0.6');
  1251. $this->assertEquals(['zh', 'cherokee'], $request->getLanguages());
  1252. }
  1253. public function testGetRequestFormat()
  1254. {
  1255. $request = new Request();
  1256. $this->assertEquals('html', $request->getRequestFormat());
  1257. // Ensure that setting different default values over time is possible,
  1258. // aka. setRequestFormat determines the state.
  1259. $this->assertEquals('json', $request->getRequestFormat('json'));
  1260. $this->assertEquals('html', $request->getRequestFormat('html'));
  1261. $request = new Request();
  1262. $this->assertNull($request->getRequestFormat(null));
  1263. $request = new Request();
  1264. $this->assertNull($request->setRequestFormat('foo'));
  1265. $this->assertEquals('foo', $request->getRequestFormat(null));
  1266. $request = new Request(['_format' => 'foo']);
  1267. $this->assertEquals('html', $request->getRequestFormat());
  1268. }
  1269. public function testHasSession()
  1270. {
  1271. $request = new Request();
  1272. $this->assertFalse($request->hasSession());
  1273. $request->setSession(new Session(new MockArraySessionStorage()));
  1274. $this->assertTrue($request->hasSession());
  1275. }
  1276. public function testGetSession()
  1277. {
  1278. $request = new Request();
  1279. $request->setSession(new Session(new MockArraySessionStorage()));
  1280. $this->assertTrue($request->hasSession());
  1281. $session = $request->getSession();
  1282. $this->assertObjectHasAttribute('storage', $session);
  1283. $this->assertObjectHasAttribute('flashName', $session);
  1284. $this->assertObjectHasAttribute('attributeName', $session);
  1285. }
  1286. /**
  1287. * @group legacy
  1288. * @expectedDeprecation Calling "Symfony\Component\HttpFoundation\Request::getSession()" when no session has been set is deprecated since Symfony 4.1 and will throw an exception in 5.0. Use "hasSession()" instead.
  1289. */
  1290. public function testGetSessionNullable()
  1291. {
  1292. (new Request())->getSession();
  1293. }
  1294. public function testHasPreviousSession()
  1295. {
  1296. $request = new Request();
  1297. $this->assertFalse($request->hasPreviousSession());
  1298. $request->cookies->set('MOCKSESSID', 'foo');
  1299. $this->assertFalse($request->hasPreviousSession());
  1300. $request->setSession(new Session(new MockArraySessionStorage()));
  1301. $this->assertTrue($request->hasPreviousSession());
  1302. }
  1303. public function testToString()
  1304. {
  1305. $request = new Request();
  1306. $request->headers->set('Accept-language', 'zh, en-us; q=0.8, en; q=0.6');
  1307. $request->cookies->set('Foo', 'Bar');
  1308. $asString = (string) $request;
  1309. $this->assertContains('Accept-Language: zh, en-us; q=0.8, en; q=0.6', $asString);
  1310. $this->assertContains('Cookie: Foo=Bar', $asString);
  1311. $request->cookies->set('Another', 'Cookie');
  1312. $asString = (string) $request;
  1313. $this->assertContains('Cookie: Foo=Bar; Another=Cookie', $asString);
  1314. }
  1315. public function testIsMethod()
  1316. {
  1317. $request = new Request();
  1318. $request->setMethod('POST');
  1319. $this->assertTrue($request->isMethod('POST'));
  1320. $this->assertTrue($request->isMethod('post'));
  1321. $this->assertFalse($request->isMethod('GET'));
  1322. $this->assertFalse($request->isMethod('get'));
  1323. $request->setMethod('GET');
  1324. $this->assertTrue($request->isMethod('GET'));
  1325. $this->assertTrue($request->isMethod('get'));
  1326. $this->assertFalse($request->isMethod('POST'));
  1327. $this->assertFalse($request->isMethod('post'));
  1328. }
  1329. /**
  1330. * @dataProvider getBaseUrlData
  1331. */
  1332. public function testGetBaseUrl($uri, $server, $expectedBaseUrl, $expectedPathInfo)
  1333. {
  1334. $request = Request::create($uri, 'GET', [], [], [], $server);
  1335. $this->assertSame($expectedBaseUrl, $request->getBaseUrl(), 'baseUrl');
  1336. $this->assertSame($expectedPathInfo, $request->getPathInfo(), 'pathInfo');
  1337. }
  1338. public function getBaseUrlData()
  1339. {
  1340. return [
  1341. [
  1342. '/fruit/strawberry/1234index.php/blah',
  1343. [
  1344. 'SCRIPT_FILENAME' => 'E:/Sites/cc-new/public_html/fruit/index.php',
  1345. 'SCRIPT_NAME' => '/fruit/index.php',
  1346. 'PHP_SELF' => '/fruit/index.php',
  1347. ],
  1348. '/fruit',
  1349. '/strawberry/1234index.php/blah',
  1350. ],
  1351. [
  1352. '/fruit/strawberry/1234index.php/blah',
  1353. [
  1354. 'SCRIPT_FILENAME' => 'E:/Sites/cc-new/public_html/index.php',
  1355. 'SCRIPT_NAME' => '/index.php',
  1356. 'PHP_SELF' => '/index.php',
  1357. ],
  1358. '',
  1359. '/fruit/strawberry/1234index.php/blah',
  1360. ],
  1361. [
  1362. '/foo%20bar/',
  1363. [
  1364. 'SCRIPT_FILENAME' => '/home/John Doe/public_html/foo bar/app.php',
  1365. 'SCRIPT_NAME' => '/foo bar/app.php',
  1366. 'PHP_SELF' => '/foo bar/app.php',
  1367. ],
  1368. '/foo%20bar',
  1369. '/',
  1370. ],
  1371. [
  1372. '/foo%20bar/home',
  1373. [
  1374. 'SCRIPT_FILENAME' => '/home/John Doe/public_html/foo bar/app.php',
  1375. 'SCRIPT_NAME' => '/foo bar/app.php',
  1376. 'PHP_SELF' => '/foo bar/app.php',
  1377. ],
  1378. '/foo%20bar',
  1379. '/home',
  1380. ],
  1381. [
  1382. '/foo%20bar/app.php/home',
  1383. [
  1384. 'SCRIPT_FILENAME' => '/home/John Doe/public_html/foo bar/app.php',
  1385. 'SCRIPT_NAME' => '/foo bar/app.php',
  1386. 'PHP_SELF' => '/foo bar/app.php',
  1387. ],
  1388. '/foo%20bar/app.php',
  1389. '/home',
  1390. ],
  1391. [
  1392. '/foo%20bar/app.php/home%3Dbaz',
  1393. [
  1394. 'SCRIPT_FILENAME' => '/home/John Doe/public_html/foo bar/app.php',
  1395. 'SCRIPT_NAME' => '/foo bar/app.php',
  1396. 'PHP_SELF' => '/foo bar/app.php',
  1397. ],
  1398. '/foo%20bar/app.php',
  1399. '/home%3Dbaz',
  1400. ],
  1401. [
  1402. '/foo/bar+baz',
  1403. [
  1404. 'SCRIPT_FILENAME' => '/home/John Doe/public_html/foo/app.php',
  1405. 'SCRIPT_NAME' => '/foo/app.php',
  1406. 'PHP_SELF' => '/foo/app.php',
  1407. ],
  1408. '/foo',
  1409. '/bar+baz',
  1410. ],
  1411. ];
  1412. }
  1413. /**
  1414. * @dataProvider urlencodedStringPrefixData
  1415. */
  1416. public function testUrlencodedStringPrefix($string, $prefix, $expect)
  1417. {
  1418. $request = new Request();
  1419. $me = new \ReflectionMethod($request, 'getUrlencodedPrefix');
  1420. $me->setAccessible(true);
  1421. $this->assertSame($expect, $me->invoke($request, $string, $prefix));
  1422. }
  1423. public function urlencodedStringPrefixData()
  1424. {
  1425. return [
  1426. ['foo', 'foo', 'foo'],
  1427. ['fo%6f', 'foo', 'fo%6f'],
  1428. ['foo/bar', 'foo', 'foo'],
  1429. ['fo%6f/bar', 'foo', 'fo%6f'],
  1430. ['f%6f%6f/bar', 'foo', 'f%6f%6f'],
  1431. ['%66%6F%6F/bar', 'foo', '%66%6F%6F'],
  1432. ['fo+o/bar', 'fo+o', 'fo+o'],
  1433. ['fo%2Bo/bar', 'fo+o', 'fo%2Bo'],
  1434. ];
  1435. }
  1436. private function disableHttpMethodParameterOverride()
  1437. {
  1438. $class = new \ReflectionClass('Symfony\\Component\\HttpFoundation\\Request');
  1439. $property = $class->getProperty('httpMethodParameterOverride');
  1440. $property->setAccessible(true);
  1441. $property->setValue(false);
  1442. }
  1443. private function getRequestInstanceForClientIpTests($remoteAddr, $httpForwardedFor, $trustedProxies)
  1444. {
  1445. $request = new Request();
  1446. $server = ['REMOTE_ADDR' => $remoteAddr];
  1447. if (null !== $httpForwardedFor) {
  1448. $server['HTTP_X_FORWARDED_FOR'] = $httpForwardedFor;
  1449. }
  1450. if ($trustedProxies) {
  1451. Request::setTrustedProxies($trustedProxies, Request::HEADER_X_FORWARDED_ALL);
  1452. }
  1453. $request->initialize([], [], [], [], [], $server);
  1454. return $request;
  1455. }
  1456. private function getRequestInstanceForClientIpsForwardedTests($remoteAddr, $httpForwarded, $trustedProxies)
  1457. {
  1458. $request = new Request();
  1459. $server = ['REMOTE_ADDR' => $remoteAddr];
  1460. if (null !== $httpForwarded) {
  1461. $server['HTTP_FORWARDED'] = $httpForwarded;
  1462. }
  1463. if ($trustedProxies) {
  1464. Request::setTrustedProxies($trustedProxies, Request::HEADER_FORWARDED);
  1465. }
  1466. $request->initialize([], [], [], [], [], $server);
  1467. return $request;
  1468. }
  1469. public function testTrustedProxiesXForwardedFor()
  1470. {
  1471. $request = Request::create('http://example.com/');
  1472. $request->server->set('REMOTE_ADDR', '3.3.3.3');
  1473. $request->headers->set('X_FORWARDED_FOR', '1.1.1.1, 2.2.2.2');
  1474. $request->headers->set('X_FORWARDED_HOST', 'foo.example.com:1234, real.example.com:8080');
  1475. $request->headers->set('X_FORWARDED_PROTO', 'https');
  1476. $request->headers->set('X_FORWARDED_PORT', 443);
  1477. // no trusted proxies
  1478. $this->assertEquals('3.3.3.3', $request->getClientIp());
  1479. $this->assertEquals('example.com', $request->getHost());
  1480. $this->assertEquals(80, $request->getPort());
  1481. $this->assertFalse($request->isSecure());
  1482. // disabling proxy trusting
  1483. Request::setTrustedProxies([], Request::HEADER_X_FORWARDED_ALL);
  1484. $this->assertEquals('3.3.3.3', $request->getClientIp());
  1485. $this->assertEquals('example.com', $request->getHost());
  1486. $this->assertEquals(80, $request->getPort());
  1487. $this->assertFalse($request->isSecure());
  1488. // request is forwarded by a non-trusted proxy
  1489. Request::setTrustedProxies(['2.2.2.2'], Request::HEADER_X_FORWARDED_ALL);
  1490. $this->assertEquals('3.3.3.3', $request->getClientIp());
  1491. $this->assertEquals('example.com', $request->getHost());
  1492. $this->assertEquals(80, $request->getPort());
  1493. $this->assertFalse($request->isSecure());
  1494. // trusted proxy via setTrustedProxies()
  1495. Request::setTrustedProxies(['3.3.3.3', '2.2.2.2'], Request::HEADER_X_FORWARDED_ALL);
  1496. $this->assertEquals('1.1.1.1', $request->getClientIp());
  1497. $this->assertEquals('foo.example.com', $request->getHost());
  1498. $this->assertEquals(443, $request->getPort());
  1499. $this->assertTrue($request->isSecure());
  1500. // trusted proxy via setTrustedProxies()
  1501. Request::setTrustedProxies(['3.3.3.4', '2.2.2.2'], Request::HEADER_X_FORWARDED_ALL);
  1502. $this->assertEquals('3.3.3.3', $request->getClientIp());
  1503. $this->assertEquals('example.com', $request->getHost());
  1504. $this->assertEquals(80, $request->getPort());
  1505. $this->assertFalse($request->isSecure());
  1506. // check various X_FORWARDED_PROTO header values
  1507. Request::setTrustedProxies(['3.3.3.3', '2.2.2.2'], Request::HEADER_X_FORWARDED_ALL);
  1508. $request->headers->set('X_FORWARDED_PROTO', 'ssl');
  1509. $this->assertTrue($request->isSecure());
  1510. $request->headers->set('X_FORWARDED_PROTO', 'https, http');
  1511. $this->assertTrue($request->isSecure());
  1512. }
  1513. public function testTrustedProxiesForwarded()
  1514. {
  1515. $request = Request::create('http://example.com/');
  1516. $request->server->set('REMOTE_ADDR', '3.3.3.3');
  1517. $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');
  1518. // no trusted proxies
  1519. $this->assertEquals('3.3.3.3', $request->getClientIp());
  1520. $this->assertEquals('example.com', $request->getHost());
  1521. $this->assertEquals(80, $request->getPort());
  1522. $this->assertFalse($request->isSecure());
  1523. // disabling proxy trusting
  1524. Request::setTrustedProxies([], Request::HEADER_FORWARDED);
  1525. $this->assertEquals('3.3.3.3', $request->getClientIp());
  1526. $this->assertEquals('example.com', $request->getHost());
  1527. $this->assertEquals(80, $request->getPort());
  1528. $this->assertFalse($request->isSecure());
  1529. // request is forwarded by a non-trusted proxy
  1530. Request::setTrustedProxies(['2.2.2.2'], Request::HEADER_FORWARDED);
  1531. $this->assertEquals('3.3.3.3', $request->getClientIp());
  1532. $this->assertEquals('example.com', $request->getHost());
  1533. $this->assertEquals(80, $request->getPort());
  1534. $this->assertFalse($request->isSecure());
  1535. // trusted proxy via setTrustedProxies()
  1536. Request::setTrustedProxies(['3.3.3.3', '2.2.2.2'], Request::HEADER_FORWARDED);
  1537. $this->assertEquals('1.1.1.1', $request->getClientIp());
  1538. $this->assertEquals('foo.example.com', $request->getHost());
  1539. $this->assertEquals(8080, $request->getPort());
  1540. $this->assertTrue($request->isSecure());
  1541. // trusted proxy via setTrustedProxies()
  1542. Request::setTrustedProxies(['3.3.3.4', '2.2.2.2'], Request::HEADER_FORWARDED);
  1543. $this->assertEquals('3.3.3.3', $request->getClientIp());
  1544. $this->assertEquals('example.com', $request->getHost());
  1545. $this->assertEquals(80, $request->getPort());
  1546. $this->assertFalse($request->isSecure());
  1547. // check various X_FORWARDED_PROTO header values
  1548. Request::setTrustedProxies(['3.3.3.3', '2.2.2.2'], Request::HEADER_FORWARDED);
  1549. $request->headers->set('FORWARDED', 'proto=ssl');
  1550. $this->assertTrue($request->isSecure());
  1551. $request->headers->set('FORWARDED', 'proto=https, proto=http');
  1552. $this->assertTrue($request->isSecure());
  1553. }
  1554. /**
  1555. * @dataProvider iisRequestUriProvider
  1556. */
  1557. public function testIISRequestUri($headers, $server, $expectedRequestUri)
  1558. {
  1559. $request = new Request();
  1560. $request->headers->replace($headers);
  1561. $request->server->replace($server);
  1562. $this->assertEquals($expectedRequestUri, $request->getRequestUri(), '->getRequestUri() is correct');
  1563. $subRequestUri = '/bar/foo';
  1564. $subRequest = Request::create($subRequestUri, 'get', [], [], [], $request->server->all());
  1565. $this->assertEquals($subRequestUri, $subRequest->getRequestUri(), '->getRequestUri() is correct in sub request');
  1566. }
  1567. public function iisRequestUriProvider()
  1568. {
  1569. return [
  1570. [
  1571. [],
  1572. [
  1573. 'IIS_WasUrlRewritten' => '1',
  1574. 'UNENCODED_URL' => '/foo/bar',
  1575. ],
  1576. '/foo/bar',
  1577. ],
  1578. [
  1579. [],
  1580. [
  1581. 'ORIG_PATH_INFO' => '/foo/bar',
  1582. ],
  1583. '/foo/bar',
  1584. ],
  1585. [
  1586. [],
  1587. [
  1588. 'ORIG_PATH_INFO' => '/foo/bar',
  1589. 'QUERY_STRING' => 'foo=bar',
  1590. ],
  1591. '/foo/bar?foo=bar',
  1592. ],
  1593. ];
  1594. }
  1595. public function testTrustedHosts()
  1596. {
  1597. // create a request
  1598. $request = Request::create('/');
  1599. // no trusted host set -> no host check
  1600. $request->headers->set('host', 'evil.com');
  1601. $this->assertEquals('evil.com', $request->getHost());
  1602. // add a trusted domain and all its subdomains
  1603. Request::setTrustedHosts(['^([a-z]{9}\.)?trusted\.com$']);
  1604. // untrusted host
  1605. $request->headers->set('host', 'evil.com');
  1606. try {
  1607. $request->getHost();
  1608. $this->fail('Request::getHost() should throw an exception when host is not trusted.');
  1609. } catch (SuspiciousOperationException $e) {
  1610. $this->assertEquals('Untrusted Host "evil.com".', $e->getMessage());
  1611. }
  1612. // trusted hosts
  1613. $request->headers->set('host', 'trusted.com');
  1614. $this->assertEquals('trusted.com', $request->getHost());
  1615. $this->assertEquals(80, $request->getPort());
  1616. $request->server->set('HTTPS', true);
  1617. $request->headers->set('host', 'trusted.com');
  1618. $this->assertEquals('trusted.com', $request->getHost());
  1619. $this->assertEquals(443, $request->getPort());
  1620. $request->server->set('HTTPS', false);
  1621. $request->headers->set('host', 'trusted.com:8000');
  1622. $this->assertEquals('trusted.com', $request->getHost());
  1623. $this->assertEquals(8000, $request->getPort());
  1624. $request->headers->set('host', 'subdomain.trusted.com');
  1625. $this->assertEquals('subdomain.trusted.com', $request->getHost());
  1626. }
  1627. public function testSetTrustedHostsDoesNotBreakOnSpecialCharacters()
  1628. {
  1629. Request::setTrustedHosts(['localhost(\.local){0,1}#,example.com', 'localhost']);
  1630. $request = Request::create('/');
  1631. $request->headers->set('host', 'localhost');
  1632. $this->assertSame('localhost', $request->getHost());
  1633. }
  1634. public function testFactory()
  1635. {
  1636. Request::setFactory(function (array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null) {
  1637. return new NewRequest();
  1638. });
  1639. $this->assertEquals('foo', Request::create('/')->getFoo());
  1640. Request::setFactory(null);
  1641. }
  1642. /**
  1643. * @dataProvider getLongHostNames
  1644. */
  1645. public function testVeryLongHosts($host)
  1646. {
  1647. $start = microtime(true);
  1648. $request = Request::create('/');
  1649. $request->headers->set('host', $host);
  1650. $this->assertEquals($host, $request->getHost());
  1651. $this->assertLessThan(5, microtime(true) - $start);
  1652. }
  1653. /**
  1654. * @dataProvider getHostValidities
  1655. */
  1656. public function testHostValidity($host, $isValid, $expectedHost = null, $expectedPort = null)
  1657. {
  1658. $request = Request::create('/');
  1659. $request->headers->set('host', $host);
  1660. if ($isValid) {
  1661. $this->assertSame($expectedHost ?: $host, $request->getHost());
  1662. if ($expectedPort) {
  1663. $this->assertSame($expectedPort, $request->getPort());
  1664. }
  1665. } else {
  1666. if (method_exists($this, 'expectException')) {
  1667. $this->expectException(SuspiciousOperationException::class);
  1668. $this->expectExceptionMessage('Invalid Host');
  1669. } else {
  1670. $this->setExpectedException(SuspiciousOperationException::class, 'Invalid Host');
  1671. }
  1672. $request->getHost();
  1673. }
  1674. }
  1675. public function getHostValidities()
  1676. {
  1677. return [
  1678. ['.a', false],
  1679. ['a..', false],
  1680. ['a.', true],
  1681. ["\xE9", false],
  1682. ['[::1]', true],
  1683. ['[::1]:80', true, '[::1]', 80],
  1684. [str_repeat('.', 101), false],
  1685. ];
  1686. }
  1687. public function getLongHostNames()
  1688. {
  1689. return [
  1690. ['a'.str_repeat('.a', 40000)],
  1691. [str_repeat(':', 101)],
  1692. ];
  1693. }
  1694. /**
  1695. * @dataProvider methodIdempotentProvider
  1696. */
  1697. public function testMethodIdempotent($method, $idempotent)
  1698. {
  1699. $request = new Request();
  1700. $request->setMethod($method);
  1701. $this->assertEquals($idempotent, $request->isMethodIdempotent());
  1702. }
  1703. public function methodIdempotentProvider()
  1704. {
  1705. return [
  1706. ['HEAD', true],
  1707. ['GET', true],
  1708. ['POST', false],
  1709. ['PUT', true],
  1710. ['PATCH', false],
  1711. ['DELETE', true],
  1712. ['PURGE', true],
  1713. ['OPTIONS', true],
  1714. ['TRACE', true],
  1715. ['CONNECT', false],
  1716. ];
  1717. }
  1718. /**
  1719. * @dataProvider methodSafeProvider
  1720. */
  1721. public function testMethodSafe($method, $safe)
  1722. {
  1723. $request = new Request();
  1724. $request->setMethod($method);
  1725. $this->assertEquals($safe, $request->isMethodSafe(false));
  1726. }
  1727. public function methodSafeProvider()
  1728. {
  1729. return [
  1730. ['HEAD', true],
  1731. ['GET', true],
  1732. ['POST', false],
  1733. ['PUT', false],
  1734. ['PATCH', false],
  1735. ['DELETE', false],
  1736. ['PURGE', false],
  1737. ['OPTIONS', true],
  1738. ['TRACE', true],
  1739. ['CONNECT', false],
  1740. ];
  1741. }
  1742. /**
  1743. * @expectedException \BadMethodCallException
  1744. */
  1745. public function testMethodSafeChecksCacheable()
  1746. {
  1747. $request = new Request();
  1748. $request->setMethod('OPTIONS');
  1749. $request->isMethodSafe();
  1750. }
  1751. /**
  1752. * @dataProvider methodCacheableProvider
  1753. */
  1754. public function testMethodCacheable($method, $cacheable)
  1755. {
  1756. $request = new Request();
  1757. $request->setMethod($method);
  1758. $this->assertEquals($cacheable, $request->isMethodCacheable());
  1759. }
  1760. public function methodCacheableProvider()
  1761. {
  1762. return [
  1763. ['HEAD', true],
  1764. ['GET', true],
  1765. ['POST', false],
  1766. ['PUT', false],
  1767. ['PATCH', false],
  1768. ['DELETE', false],
  1769. ['PURGE', false],
  1770. ['OPTIONS', false],
  1771. ['TRACE', false],
  1772. ['CONNECT', false],
  1773. ];
  1774. }
  1775. /**
  1776. * @dataProvider protocolVersionProvider
  1777. */
  1778. public function testProtocolVersion($serverProtocol, $trustedProxy, $via, $expected)
  1779. {
  1780. if ($trustedProxy) {
  1781. Request::setTrustedProxies(['1.1.1.1'], -1);
  1782. }
  1783. $request = new Request();
  1784. $request->server->set('SERVER_PROTOCOL', $serverProtocol);
  1785. $request->server->set('REMOTE_ADDR', '1.1.1.1');
  1786. $request->headers->set('Via', $via);
  1787. $this->assertSame($expected, $request->getProtocolVersion());
  1788. }
  1789. public function protocolVersionProvider()
  1790. {
  1791. return [
  1792. 'untrusted without via' => ['HTTP/2.0', false, '', 'HTTP/2.0'],
  1793. 'untrusted with via' => ['HTTP/2.0', false, '1.0 fred, 1.1 nowhere.com (Apache/1.1)', 'HTTP/2.0'],
  1794. 'trusted without via' => ['HTTP/2.0', true, '', 'HTTP/2.0'],
  1795. 'trusted with via' => ['HTTP/2.0', true, '1.0 fred, 1.1 nowhere.com (Apache/1.1)', 'HTTP/1.0'],
  1796. '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'],
  1797. 'trusted with broken via' => ['HTTP/2.0', true, 'HTTP/1^0 foo', 'HTTP/2.0'],
  1798. 'trusted with partially-broken via' => ['HTTP/2.0', true, '1.0 fred, foo', 'HTTP/1.0'],
  1799. ];
  1800. }
  1801. public function nonstandardRequestsData()
  1802. {
  1803. return [
  1804. ['', '', '/', 'http://host:8080/', ''],
  1805. ['/', '', '/', 'http://host:8080/', ''],
  1806. ['hello/app.php/x', '', '/x', 'http://host:8080/hello/app.php/x', '/hello', '/hello/app.php'],
  1807. ['/hello/app.php/x', '', '/x', 'http://host:8080/hello/app.php/x', '/hello', '/hello/app.php'],
  1808. ['', 'a=b', '/', 'http://host:8080/?a=b'],
  1809. ['?a=b', 'a=b', '/', 'http://host:8080/?a=b'],
  1810. ['/?a=b', 'a=b', '/', 'http://host:8080/?a=b'],
  1811. ['x', 'a=b', '/x', 'http://host:8080/x?a=b'],
  1812. ['x?a=b', 'a=b', '/x', 'http://host:8080/x?a=b'],
  1813. ['/x?a=b', 'a=b', '/x', 'http://host:8080/x?a=b'],
  1814. ['hello/x', '', '/x', 'http://host:8080/hello/x', '/hello'],
  1815. ['/hello/x', '', '/x', 'http://host:8080/hello/x', '/hello'],
  1816. ['hello/app.php/x', 'a=b', '/x', 'http://host:8080/hello/app.php/x?a=b', '/hello', '/hello/app.php'],
  1817. ['hello/app.php/x?a=b', 'a=b', '/x', 'http://host:8080/hello/app.php/x?a=b', '/hello', '/hello/app.php'],
  1818. ['/hello/app.php/x?a=b', 'a=b', '/x', 'http://host:8080/hello/app.php/x?a=b', '/hello', '/hello/app.php'],
  1819. ];
  1820. }
  1821. /**
  1822. * @dataProvider nonstandardRequestsData
  1823. */
  1824. public function testNonstandardRequests($requestUri, $queryString, $expectedPathInfo, $expectedUri, $expectedBasePath = '', $expectedBaseUrl = null)
  1825. {
  1826. if (null === $expectedBaseUrl) {
  1827. $expectedBaseUrl = $expectedBasePath;
  1828. }
  1829. $server = [
  1830. 'HTTP_HOST' => 'host:8080',
  1831. 'SERVER_PORT' => '8080',
  1832. 'QUERY_STRING' => $queryString,
  1833. 'PHP_SELF' => '/hello/app.php',
  1834. 'SCRIPT_FILENAME' => '/some/path/app.php',
  1835. 'REQUEST_URI' => $requestUri,
  1836. ];
  1837. $request = new Request([], [], [], [], [], $server);
  1838. $this->assertEquals($expectedPathInfo, $request->getPathInfo());
  1839. $this->assertEquals($expectedUri, $request->getUri());
  1840. $this->assertEquals($queryString, $request->getQueryString());
  1841. $this->assertEquals(8080, $request->getPort());
  1842. $this->assertEquals('host:8080', $request->getHttpHost());
  1843. $this->assertEquals($expectedBaseUrl, $request->getBaseUrl());
  1844. $this->assertEquals($expectedBasePath, $request->getBasePath());
  1845. }
  1846. public function testTrustedHost()
  1847. {
  1848. Request::setTrustedProxies(['1.1.1.1'], -1);
  1849. $request = Request::create('/');
  1850. $request->server->set('REMOTE_ADDR', '1.1.1.1');
  1851. $request->headers->set('Forwarded', 'host=localhost:8080');
  1852. $request->headers->set('X-Forwarded-Host', 'localhost:8080');
  1853. $this->assertSame('localhost:8080', $request->getHttpHost());
  1854. $this->assertSame(8080, $request->getPort());
  1855. $request = Request::create('/');
  1856. $request->server->set('REMOTE_ADDR', '1.1.1.1');
  1857. $request->headers->set('Forwarded', 'host="[::1]:443"');
  1858. $request->headers->set('X-Forwarded-Host', '[::1]:443');
  1859. $request->headers->set('X-Forwarded-Port', 443);
  1860. $this->assertSame('[::1]:443', $request->getHttpHost());
  1861. $this->assertSame(443, $request->getPort());
  1862. }
  1863. public function testTrustedPort()
  1864. {
  1865. Request::setTrustedProxies(['1.1.1.1'], -1);
  1866. $request = Request::create('/');
  1867. $request->server->set('REMOTE_ADDR', '1.1.1.1');
  1868. $request->headers->set('Forwarded', 'host=localhost:8080');
  1869. $request->headers->set('X-Forwarded-Port', 8080);
  1870. $this->assertSame(8080, $request->getPort());
  1871. $request = Request::create('/');
  1872. $request->server->set('REMOTE_ADDR', '1.1.1.1');
  1873. $request->headers->set('Forwarded', 'host=localhost');
  1874. $request->headers->set('X-Forwarded-Port', 80);
  1875. $this->assertSame(80, $request->getPort());
  1876. $request = Request::create('/');
  1877. $request->server->set('REMOTE_ADDR', '1.1.1.1');
  1878. $request->headers->set('Forwarded', 'host="[::1]"');
  1879. $request->headers->set('X-Forwarded-Proto', 'https');
  1880. $request->headers->set('X-Forwarded-Port', 443);
  1881. $this->assertSame(443, $request->getPort());
  1882. }
  1883. }
  1884. class RequestContentProxy extends Request
  1885. {
  1886. public function getContent($asResource = false)
  1887. {
  1888. return http_build_query(['_method' => 'PUT', 'content' => 'mycontent'], '', '&');
  1889. }
  1890. }
  1891. class NewRequest extends Request
  1892. {
  1893. public function getFoo()
  1894. {
  1895. return 'foo';
  1896. }
  1897. }