ServerRequestTest.php 115 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 2.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Http;
  16. use Cake\Core\Configure;
  17. use Cake\Http\Cookie\Cookie;
  18. use Cake\Http\Cookie\CookieCollection;
  19. use Cake\Http\ServerRequest;
  20. use Cake\Http\ServerRequestFactory;
  21. use Cake\Network\Exception\MethodNotAllowedException;
  22. use Cake\Network\Session;
  23. use Cake\TestSuite\TestCase;
  24. use Zend\Diactoros\UploadedFile;
  25. use Zend\Diactoros\Uri;
  26. /**
  27. * ServerRequest Test
  28. */
  29. class ServerRequestTest extends TestCase
  30. {
  31. /**
  32. * SERVER variable backup.
  33. *
  34. * @var array
  35. */
  36. protected $server = [];
  37. /**
  38. * Setup callback
  39. *
  40. * @return void
  41. */
  42. public function setUp()
  43. {
  44. parent::setUp();
  45. $this->server = $_SERVER;
  46. Configure::write('App.baseUrl', false);
  47. }
  48. public function tearDown()
  49. {
  50. parent::tearDown();
  51. $_SERVER = $this->server;
  52. }
  53. /**
  54. * Test custom detector with extra arguments.
  55. *
  56. * @return void
  57. */
  58. public function testCustomArgsDetector()
  59. {
  60. $request = new ServerRequest();
  61. $request->addDetector('controller', function ($request, $name) {
  62. return $request->param('controller') === $name;
  63. });
  64. $request->params = ['controller' => 'cake'];
  65. $this->assertTrue($request->is('controller', 'cake'));
  66. $this->assertFalse($request->is('controller', 'nonExistingController'));
  67. $this->assertTrue($request->isController('cake'));
  68. $this->assertFalse($request->isController('nonExistingController'));
  69. }
  70. /**
  71. * Test the header detector.
  72. *
  73. * @return void
  74. */
  75. public function testHeaderDetector()
  76. {
  77. $request = new ServerRequest();
  78. $request->addDetector('host', ['header' => ['host' => 'cakephp.org']]);
  79. $request->env('HTTP_HOST', 'cakephp.org');
  80. $this->assertTrue($request->is('host'));
  81. $request->env('HTTP_HOST', 'php.net');
  82. $this->assertFalse($request->is('host'));
  83. }
  84. /**
  85. * Test the accept header detector.
  86. *
  87. * @return void
  88. */
  89. public function testExtensionDetector()
  90. {
  91. $request = new ServerRequest();
  92. $request->params['_ext'] = 'json';
  93. $this->assertTrue($request->is('json'));
  94. $request = new ServerRequest();
  95. $request->params['_ext'] = 'xml';
  96. $this->assertFalse($request->is('json'));
  97. }
  98. /**
  99. * Test the accept header detector.
  100. *
  101. * @return void
  102. */
  103. public function testAcceptHeaderDetector()
  104. {
  105. $request = new ServerRequest();
  106. $request->env('HTTP_ACCEPT', 'application/json, text/plain, */*');
  107. $this->assertTrue($request->is('json'));
  108. $request = new ServerRequest();
  109. $request->env('HTTP_ACCEPT', 'text/plain, */*');
  110. $this->assertFalse($request->is('json'));
  111. }
  112. /**
  113. * Test that the autoparse = false constructor works.
  114. *
  115. * @return void
  116. */
  117. public function testNoAutoParseConstruction()
  118. {
  119. $_GET = [
  120. 'one' => 'param'
  121. ];
  122. $request = new ServerRequest();
  123. $this->assertFalse(isset($request->query['one']));
  124. }
  125. /**
  126. * Test construction
  127. *
  128. * @return void
  129. */
  130. public function testConstructionQueryData()
  131. {
  132. $data = [
  133. 'query' => [
  134. 'one' => 'param',
  135. 'two' => 'banana'
  136. ],
  137. 'url' => 'some/path'
  138. ];
  139. $request = new ServerRequest($data);
  140. $this->assertEquals($request->query, $data['query']);
  141. $this->assertEquals('some/path', $request->url);
  142. }
  143. /**
  144. * Test that querystring args provided in the URL string are parsed.
  145. *
  146. * @return void
  147. */
  148. public function testQueryStringParsingFromInputUrl()
  149. {
  150. $_GET = [];
  151. $request = new ServerRequest(['url' => 'some/path?one=something&two=else']);
  152. $expected = ['one' => 'something', 'two' => 'else'];
  153. $this->assertEquals($expected, $request->query);
  154. $this->assertEquals('some/path', $request->url);
  155. $this->assertEquals('one=something&two=else', $request->getUri()->getQuery());
  156. }
  157. /**
  158. * Test that named arguments + querystrings are handled correctly.
  159. *
  160. * @return void
  161. */
  162. public function testQueryStringAndNamedParams()
  163. {
  164. $_SERVER['REQUEST_URI'] = '/tasks/index?ts=123456';
  165. $request = ServerRequestFactory::fromGlobals();
  166. $this->assertEquals('tasks/index', $request->url);
  167. $_SERVER['REQUEST_URI'] = '/tasks/index/?ts=123456';
  168. $request = ServerRequestFactory::fromGlobals();
  169. $this->assertEquals('tasks/index/', $request->url);
  170. $_SERVER['REQUEST_URI'] = '/some/path?url=http://cakephp.org';
  171. $request = ServerRequestFactory::fromGlobals();
  172. $this->assertEquals('some/path', $request->url);
  173. $_SERVER['REQUEST_URI'] = Configure::read('App.fullBaseUrl') . '/other/path?url=http://cakephp.org';
  174. $request = ServerRequestFactory::fromGlobals();
  175. $this->assertEquals('other/path', $request->url);
  176. }
  177. /**
  178. * Test that URL in path is handled correctly.
  179. */
  180. public function testUrlInPath()
  181. {
  182. $_SERVER['REQUEST_URI'] = '/jump/http://cakephp.org';
  183. $request = ServerRequestFactory::fromGlobals();
  184. $this->assertEquals('jump/http://cakephp.org', $request->url);
  185. $_SERVER['REQUEST_URI'] = Configure::read('App.fullBaseUrl') . '/jump/http://cakephp.org';
  186. $request = ServerRequestFactory::fromGlobals();
  187. $this->assertEquals('jump/http://cakephp.org', $request->url);
  188. }
  189. /**
  190. * Test addParams() method
  191. *
  192. * @return void
  193. */
  194. public function testAddParams()
  195. {
  196. $request = new ServerRequest();
  197. $request->params = ['controller' => 'posts', 'action' => 'view'];
  198. $result = $request->addParams(['plugin' => null, 'action' => 'index']);
  199. $this->assertSame($result, $request, 'Method did not return itself. %s');
  200. $this->assertEquals('posts', $request->controller);
  201. $this->assertEquals('index', $request->action);
  202. $this->assertEquals(null, $request->plugin);
  203. }
  204. /**
  205. * Test splicing in paths.
  206. *
  207. * @return void
  208. */
  209. public function testAddPaths()
  210. {
  211. $request = new ServerRequest();
  212. $request->webroot = '/some/path/going/here/';
  213. $result = $request->addPaths([
  214. 'random' => '/something', 'webroot' => '/', 'here' => '/', 'base' => '/base_dir'
  215. ]);
  216. $this->assertSame($result, $request, 'Method did not return itself. %s');
  217. $this->assertEquals('/', $request->webroot);
  218. $this->assertEquals('/base_dir', $request->base);
  219. $this->assertEquals('/', $request->here);
  220. $this->assertFalse(isset($request->random));
  221. }
  222. /**
  223. * Test parsing POST data into the object.
  224. *
  225. * @return void
  226. */
  227. public function testPostParsing()
  228. {
  229. $post = [
  230. 'Article' => ['title']
  231. ];
  232. $request = new ServerRequest(compact('post'));
  233. $this->assertEquals($post, $request->data);
  234. $post = ['one' => 1, 'two' => 'three'];
  235. $request = new ServerRequest(compact('post'));
  236. $this->assertEquals($post, $request->data);
  237. $post = [
  238. 'Article' => ['title' => 'Testing'],
  239. 'action' => 'update'
  240. ];
  241. $request = new ServerRequest(compact('post'));
  242. $this->assertEquals($post, $request->data);
  243. }
  244. /**
  245. * Test parsing PUT data into the object.
  246. *
  247. * @return void
  248. */
  249. public function testPutParsing()
  250. {
  251. $data = [
  252. 'Article' => ['title']
  253. ];
  254. $request = new ServerRequest([
  255. 'input' => 'Article[]=title',
  256. 'environment' => [
  257. 'REQUEST_METHOD' => 'PUT',
  258. 'CONTENT_TYPE' => 'application/x-www-form-urlencoded; charset=UTF-8'
  259. ]
  260. ]);
  261. $this->assertEquals($data, $request->data);
  262. $data = ['one' => 1, 'two' => 'three'];
  263. $request = new ServerRequest([
  264. 'input' => 'one=1&two=three',
  265. 'environment' => [
  266. 'REQUEST_METHOD' => 'PUT',
  267. 'CONTENT_TYPE' => 'application/x-www-form-urlencoded; charset=UTF-8'
  268. ]
  269. ]);
  270. $this->assertEquals($data, $request->data);
  271. $request = new ServerRequest([
  272. 'input' => 'Article[title]=Testing&action=update',
  273. 'environment' => [
  274. 'REQUEST_METHOD' => 'DELETE',
  275. 'CONTENT_TYPE' => 'application/x-www-form-urlencoded; charset=UTF-8'
  276. ]
  277. ]);
  278. $expected = [
  279. 'Article' => ['title' => 'Testing'],
  280. 'action' => 'update'
  281. ];
  282. $this->assertEquals($expected, $request->data);
  283. $data = [
  284. 'Article' => ['title'],
  285. 'Tag' => ['Tag' => [1, 2]]
  286. ];
  287. $request = new ServerRequest([
  288. 'input' => 'Article[]=title&Tag[Tag][]=1&Tag[Tag][]=2',
  289. 'environment' => [
  290. 'REQUEST_METHOD' => 'PATCH',
  291. 'CONTENT_TYPE' => 'application/x-www-form-urlencoded; charset=UTF-8'
  292. ]
  293. ]);
  294. $this->assertEquals($data, $request->data);
  295. }
  296. /**
  297. * Test parsing json PUT data into the object.
  298. *
  299. * @return void
  300. */
  301. public function testPutParsingJSON()
  302. {
  303. $data = '{"Article":["title"]}';
  304. $request = new ServerRequest([
  305. 'input' => $data,
  306. 'environment' => [
  307. 'REQUEST_METHOD' => 'PUT',
  308. 'CONTENT_TYPE' => 'application/json'
  309. ]
  310. ]);
  311. $this->assertEquals([], $request->data);
  312. $result = $request->input('json_decode', true);
  313. $this->assertEquals(['title'], $result['Article']);
  314. }
  315. /**
  316. * Test processing files with `file` field names.
  317. *
  318. * @return void
  319. */
  320. public function testFilesNested()
  321. {
  322. $files = [
  323. 'image_main' => [
  324. 'name' => ['file' => 'born on.txt'],
  325. 'type' => ['file' => 'text/plain'],
  326. 'tmp_name' => ['file' => __FILE__],
  327. 'error' => ['file' => 0],
  328. 'size' => ['file' => 17178]
  329. ],
  330. 0 => [
  331. 'name' => ['image' => 'scratch.text'],
  332. 'type' => ['image' => 'text/plain'],
  333. 'tmp_name' => ['image' => __FILE__],
  334. 'error' => ['image' => 0],
  335. 'size' => ['image' => 1490]
  336. ],
  337. 'pictures' => [
  338. 'name' => [
  339. 0 => ['file' => 'a-file.png'],
  340. 1 => ['file' => 'a-moose.png']
  341. ],
  342. 'type' => [
  343. 0 => ['file' => 'image/png'],
  344. 1 => ['file' => 'image/jpg']
  345. ],
  346. 'tmp_name' => [
  347. 0 => ['file' => __FILE__],
  348. 1 => ['file' => __FILE__]
  349. ],
  350. 'error' => [
  351. 0 => ['file' => 0],
  352. 1 => ['file' => 0]
  353. ],
  354. 'size' => [
  355. 0 => ['file' => 17188],
  356. 1 => ['file' => 2010]
  357. ],
  358. ]
  359. ];
  360. $post = [
  361. 'pictures' => [
  362. 0 => ['name' => 'A cat'],
  363. 1 => ['name' => 'A moose']
  364. ],
  365. 0 => [
  366. 'name' => 'A dog'
  367. ]
  368. ];
  369. $request = new ServerRequest(compact('files', 'post'));
  370. $expected = [
  371. 'image_main' => [
  372. 'file' => [
  373. 'name' => 'born on.txt',
  374. 'type' => 'text/plain',
  375. 'tmp_name' => __FILE__,
  376. 'error' => 0,
  377. 'size' => 17178,
  378. ]
  379. ],
  380. 'pictures' => [
  381. 0 => [
  382. 'name' => 'A cat',
  383. 'file' => [
  384. 'name' => 'a-file.png',
  385. 'type' => 'image/png',
  386. 'tmp_name' => __FILE__,
  387. 'error' => '0',
  388. 'size' => 17188,
  389. ]
  390. ],
  391. 1 => [
  392. 'name' => 'A moose',
  393. 'file' => [
  394. 'name' => 'a-moose.png',
  395. 'type' => 'image/jpg',
  396. 'tmp_name' => __FILE__,
  397. 'error' => '0',
  398. 'size' => 2010,
  399. ]
  400. ]
  401. ],
  402. 0 => [
  403. 'name' => 'A dog',
  404. 'image' => [
  405. 'name' => 'scratch.text',
  406. 'type' => 'text/plain',
  407. 'tmp_name' => __FILE__,
  408. 'error' => 0,
  409. 'size' => 1490
  410. ]
  411. ]
  412. ];
  413. $this->assertEquals($expected, $request->data);
  414. $uploads = $request->getUploadedFiles();
  415. $this->assertCount(3, $uploads);
  416. $this->assertArrayHasKey(0, $uploads);
  417. $this->assertEquals('scratch.text', $uploads[0]['image']->getClientFilename());
  418. $this->assertArrayHasKey('pictures', $uploads);
  419. $this->assertEquals('a-file.png', $uploads['pictures'][0]['file']->getClientFilename());
  420. $this->assertEquals('a-moose.png', $uploads['pictures'][1]['file']->getClientFilename());
  421. $this->assertArrayHasKey('image_main', $uploads);
  422. $this->assertEquals('born on.txt', $uploads['image_main']['file']->getClientFilename());
  423. }
  424. /**
  425. * Test processing a file input with no .'s in it.
  426. *
  427. * @return void
  428. */
  429. public function testFilesFlat()
  430. {
  431. $files = [
  432. 'birth_cert' => [
  433. 'name' => 'born on.txt',
  434. 'type' => 'application/octet-stream',
  435. 'tmp_name' => __FILE__,
  436. 'error' => 0,
  437. 'size' => 123,
  438. ]
  439. ];
  440. $request = new ServerRequest(compact('files'));
  441. $expected = [
  442. 'birth_cert' => [
  443. 'name' => 'born on.txt',
  444. 'type' => 'application/octet-stream',
  445. 'tmp_name' => __FILE__,
  446. 'error' => 0,
  447. 'size' => 123
  448. ]
  449. ];
  450. $this->assertEquals($expected, $request->data);
  451. $uploads = $request->getUploadedFiles();
  452. $this->assertCount(1, $uploads);
  453. $this->assertArrayHasKey('birth_cert', $uploads);
  454. $this->assertEquals('born on.txt', $uploads['birth_cert']->getClientFilename());
  455. $this->assertEquals(0, $uploads['birth_cert']->getError());
  456. $this->assertEquals('application/octet-stream', $uploads['birth_cert']->getClientMediaType());
  457. $this->assertEquals(123, $uploads['birth_cert']->getSize());
  458. }
  459. /**
  460. * Test that files in the 0th index work.
  461. *
  462. * @return void
  463. */
  464. public function testFilesZeroithIndex()
  465. {
  466. $files = [
  467. 0 => [
  468. 'name' => 'cake_sqlserver_patch.patch',
  469. 'type' => 'text/plain',
  470. 'tmp_name' => __FILE__,
  471. 'error' => 0,
  472. 'size' => 6271,
  473. ],
  474. ];
  475. $request = new ServerRequest([
  476. 'files' => $files
  477. ]);
  478. $this->assertEquals($files, $request->data);
  479. $uploads = $request->getUploadedFiles();
  480. $this->assertCount(1, $uploads);
  481. $this->assertEquals($files[0]['name'], $uploads[0]->getClientFilename());
  482. }
  483. /**
  484. * Test that the constructor uses uploaded file objects
  485. * if they are present. This could happen in test scenarios.
  486. *
  487. * @return void
  488. */
  489. public function testFilesObject()
  490. {
  491. $file = new UploadedFile(
  492. __FILE__,
  493. 123,
  494. UPLOAD_ERR_OK,
  495. 'test.php',
  496. 'text/plain'
  497. );
  498. $request = new ServerRequest(['files' => ['avatar' => $file]]);
  499. $this->assertSame(['avatar' => $file], $request->getUploadedFiles());
  500. }
  501. /**
  502. * Test replacing files.
  503. *
  504. * @return void
  505. */
  506. public function testWithUploadedFiles()
  507. {
  508. $file = new UploadedFile(
  509. __FILE__,
  510. 123,
  511. UPLOAD_ERR_OK,
  512. 'test.php',
  513. 'text/plain'
  514. );
  515. $request = new ServerRequest();
  516. $new = $request->withUploadedFiles(['picture' => $file]);
  517. $this->assertSame([], $request->getUploadedFiles());
  518. $this->assertNotSame($new, $request);
  519. $this->assertSame(['picture' => $file], $new->getUploadedFiles());
  520. }
  521. /**
  522. * Test getting a single file
  523. *
  524. * @return void
  525. */
  526. public function testGetUploadedFile()
  527. {
  528. $file = new UploadedFile(
  529. __FILE__,
  530. 123,
  531. UPLOAD_ERR_OK,
  532. 'test.php',
  533. 'text/plain'
  534. );
  535. $request = new ServerRequest();
  536. $new = $request->withUploadedFiles(['picture' => $file]);
  537. $this->assertNull($new->getUploadedFile(''));
  538. $this->assertSame($file, $new->getUploadedFile('picture'));
  539. $new = $request->withUploadedFiles([
  540. 'pictures' => [
  541. [
  542. 'image' => $file
  543. ]
  544. ]
  545. ]);
  546. $this->assertNull($new->getUploadedFile('pictures'));
  547. $this->assertNull($new->getUploadedFile('pictures.0'));
  548. $this->assertNull($new->getUploadedFile('pictures.1'));
  549. $this->assertSame($file, $new->getUploadedFile('pictures.0.image'));
  550. }
  551. /**
  552. * Test replacing files with an invalid file
  553. *
  554. * @expectedException InvalidArgumentException
  555. * @expectedExceptionMessage Invalid file at 'avatar'
  556. * @return void
  557. */
  558. public function testWithUploadedFilesInvalidFile()
  559. {
  560. $request = new ServerRequest();
  561. $request->withUploadedFiles(['avatar' => 'not a file']);
  562. }
  563. /**
  564. * Test replacing files with an invalid file
  565. *
  566. * @expectedException InvalidArgumentException
  567. * @expectedExceptionMessage Invalid file at 'user.avatar'
  568. * @return void
  569. */
  570. public function testWithUploadedFilesInvalidFileNested()
  571. {
  572. $request = new ServerRequest();
  573. $request->withUploadedFiles(['user' => ['avatar' => 'not a file']]);
  574. }
  575. /**
  576. * Test method overrides coming in from POST data.
  577. *
  578. * @return void
  579. */
  580. public function testMethodOverrides()
  581. {
  582. $post = ['_method' => 'POST'];
  583. $request = new ServerRequest(compact('post'));
  584. $this->assertEquals('POST', $request->env('REQUEST_METHOD'));
  585. $post = ['_method' => 'DELETE'];
  586. $request = new ServerRequest(compact('post'));
  587. $this->assertEquals('DELETE', $request->env('REQUEST_METHOD'));
  588. $request = new ServerRequest(['environment' => ['HTTP_X_HTTP_METHOD_OVERRIDE' => 'PUT']]);
  589. $this->assertEquals('PUT', $request->env('REQUEST_METHOD'));
  590. $request = new ServerRequest([
  591. 'environment' => ['REQUEST_METHOD' => 'POST'],
  592. 'post' => ['_method' => 'PUT']
  593. ]);
  594. $this->assertEquals('PUT', $request->env('REQUEST_METHOD'));
  595. $this->assertEquals('POST', $request->env('ORIGINAL_REQUEST_METHOD'));
  596. }
  597. /**
  598. * Tests the env() method returning a default value in case the requested environment variable is not set.
  599. */
  600. public function testDefaultEnvValue()
  601. {
  602. $_ENV['DOES_NOT_EXIST'] = null;
  603. $request = new ServerRequest();
  604. $this->assertNull($request->env('DOES_NOT_EXIST'));
  605. $this->assertEquals('default', $request->env('DOES_NOT_EXIST', null, 'default'));
  606. $_ENV['DOES_EXIST'] = 'some value';
  607. $request = new ServerRequest();
  608. $this->assertEquals('some value', $request->env('DOES_EXIST'));
  609. $this->assertEquals('some value', $request->env('DOES_EXIST', null, 'default'));
  610. $_ENV['EMPTY_VALUE'] = '';
  611. $request = new ServerRequest();
  612. $this->assertEquals('', $request->env('EMPTY_VALUE'));
  613. $this->assertEquals('', $request->env('EMPTY_VALUE', null, 'default'));
  614. $_ENV['ZERO'] = '0';
  615. $request = new ServerRequest();
  616. $this->assertEquals('0', $request->env('ZERO'));
  617. $this->assertEquals('0', $request->env('ZERO', null, 'default'));
  618. }
  619. /**
  620. * Test the clientIp method.
  621. *
  622. * @return void
  623. */
  624. public function testClientIp()
  625. {
  626. $request = new ServerRequest(['environment' => [
  627. 'HTTP_X_FORWARDED_FOR' => '192.168.1.5, 10.0.1.1, proxy.com',
  628. 'HTTP_CLIENT_IP' => '192.168.1.2',
  629. 'REMOTE_ADDR' => '192.168.1.3'
  630. ]]);
  631. $request->trustProxy = true;
  632. $this->assertEquals('192.168.1.5', $request->clientIp());
  633. $request->env('HTTP_X_FORWARDED_FOR', '');
  634. $this->assertEquals('192.168.1.2', $request->clientIp());
  635. $request->trustProxy = false;
  636. $this->assertEquals('192.168.1.3', $request->clientIp());
  637. $request->env('HTTP_X_FORWARDED_FOR', '');
  638. $this->assertEquals('192.168.1.3', $request->clientIp());
  639. $request->env('HTTP_CLIENT_IP', '');
  640. $this->assertEquals('192.168.1.3', $request->clientIp());
  641. }
  642. /**
  643. * Test the referrer function.
  644. *
  645. * @return void
  646. */
  647. public function testReferer()
  648. {
  649. $request = new ServerRequest();
  650. $request->webroot = '/';
  651. $request->env('HTTP_REFERER', 'http://cakephp.org');
  652. $result = $request->referer();
  653. $this->assertSame('http://cakephp.org', $result);
  654. $request->env('HTTP_REFERER', '');
  655. $result = $request->referer();
  656. $this->assertSame('/', $result);
  657. $request->env('HTTP_REFERER', Configure::read('App.fullBaseUrl') . '/some/path');
  658. $result = $request->referer(true);
  659. $this->assertSame('/some/path', $result);
  660. $request->env('HTTP_REFERER', Configure::read('App.fullBaseUrl') . '/0');
  661. $result = $request->referer(true);
  662. $this->assertSame('/0', $result);
  663. $request->env('HTTP_REFERER', Configure::read('App.fullBaseUrl') . '/');
  664. $result = $request->referer(true);
  665. $this->assertSame('/', $result);
  666. $request->env('HTTP_REFERER', Configure::read('App.fullBaseUrl') . '/some/path');
  667. $result = $request->referer(false);
  668. $this->assertSame(Configure::read('App.fullBaseUrl') . '/some/path', $result);
  669. }
  670. /**
  671. * Test referer() with a base path that duplicates the
  672. * first segment.
  673. *
  674. * @return void
  675. */
  676. public function testRefererBasePath()
  677. {
  678. $request = new ServerRequest('some/path');
  679. $request->url = 'users/login';
  680. $request->webroot = '/waves/';
  681. $request->base = '/waves';
  682. $request->here = '/waves/users/login';
  683. $request->env('HTTP_REFERER', Configure::read('App.fullBaseUrl') . '/waves/waves/add');
  684. $result = $request->referer(true);
  685. $this->assertSame('/waves/add', $result);
  686. }
  687. /**
  688. * test the simple uses of is()
  689. *
  690. * @return void
  691. */
  692. public function testIsHttpMethods()
  693. {
  694. $request = new ServerRequest();
  695. $this->assertFalse($request->is('undefined-behavior'));
  696. $request->env('REQUEST_METHOD', 'GET');
  697. $this->assertTrue($request->is('get'));
  698. $request->env('REQUEST_METHOD', 'POST');
  699. $this->assertTrue($request->is('POST'));
  700. $request->env('REQUEST_METHOD', 'PUT');
  701. $this->assertTrue($request->is('put'));
  702. $this->assertFalse($request->is('get'));
  703. $request->env('REQUEST_METHOD', 'DELETE');
  704. $this->assertTrue($request->is('delete'));
  705. $this->assertTrue($request->isDelete());
  706. $request->env('REQUEST_METHOD', 'delete');
  707. $this->assertFalse($request->is('delete'));
  708. }
  709. /**
  710. * Test is() with json and xml.
  711. *
  712. * @return void
  713. */
  714. public function testIsJsonAndXml()
  715. {
  716. $request = new ServerRequest();
  717. $request->env('HTTP_ACCEPT', 'application/json, text/plain, */*');
  718. $this->assertTrue($request->is('json'));
  719. $request = new ServerRequest();
  720. $request->env('HTTP_ACCEPT', 'application/xml, text/plain, */*');
  721. $this->assertTrue($request->is('xml'));
  722. $request = new ServerRequest();
  723. $request->env('HTTP_ACCEPT', 'text/xml, */*');
  724. $this->assertTrue($request->is('xml'));
  725. }
  726. /**
  727. * Test is() with multiple types.
  728. *
  729. * @return void
  730. */
  731. public function testIsMultiple()
  732. {
  733. $request = new ServerRequest();
  734. $request->env('REQUEST_METHOD', 'GET');
  735. $this->assertTrue($request->is(['get', 'post']));
  736. $request->env('REQUEST_METHOD', 'POST');
  737. $this->assertTrue($request->is(['get', 'post']));
  738. $request->env('REQUEST_METHOD', 'PUT');
  739. $this->assertFalse($request->is(['get', 'post']));
  740. }
  741. /**
  742. * Test isAll()
  743. *
  744. * @return void
  745. */
  746. public function testIsAll()
  747. {
  748. $request = new ServerRequest();
  749. $request->env('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest');
  750. $request->env('REQUEST_METHOD', 'GET');
  751. $this->assertTrue($request->isAll(['ajax', 'get']));
  752. $this->assertFalse($request->isAll(['post', 'get']));
  753. $this->assertFalse($request->isAll(['ajax', 'post']));
  754. }
  755. /**
  756. * Test the method() method.
  757. *
  758. * @return void
  759. * @deprecated
  760. */
  761. public function testMethod()
  762. {
  763. $request = new ServerRequest(['environment' => ['REQUEST_METHOD' => 'delete']]);
  764. $this->assertEquals('delete', $request->method());
  765. }
  766. /**
  767. * Test getMethod()
  768. *
  769. * @return void
  770. */
  771. public function testGetMethod()
  772. {
  773. $request = new ServerRequest([
  774. 'environment' => ['REQUEST_METHOD' => 'delete']
  775. ]);
  776. $this->assertEquals('delete', $request->getMethod());
  777. }
  778. /**
  779. * Test withMethod()
  780. *
  781. * @return void
  782. */
  783. public function testWithMethod()
  784. {
  785. $request = new ServerRequest([
  786. 'environment' => ['REQUEST_METHOD' => 'delete']
  787. ]);
  788. $new = $request->withMethod('put');
  789. $this->assertNotSame($new, $request);
  790. $this->assertEquals('delete', $request->getMethod());
  791. $this->assertEquals('put', $new->getMethod());
  792. }
  793. /**
  794. * Test withMethod() and invalid data
  795. *
  796. * @expectedException InvalidArgumentException
  797. * @expectedExceptionMessage Unsupported HTTP method "no good" provided
  798. * @return void
  799. */
  800. public function testWithMethodInvalid()
  801. {
  802. $request = new ServerRequest([
  803. 'environment' => ['REQUEST_METHOD' => 'delete']
  804. ]);
  805. $request->withMethod('no good');
  806. }
  807. /**
  808. * Test getProtocolVersion()
  809. *
  810. * @return void
  811. */
  812. public function testGetProtocolVersion()
  813. {
  814. $request = new ServerRequest();
  815. $this->assertEquals('1.1', $request->getProtocolVersion());
  816. // SERVER var.
  817. $request = new ServerRequest([
  818. 'environment' => ['SERVER_PROTOCOL' => 'HTTP/1.0']
  819. ]);
  820. $this->assertEquals('1.0', $request->getProtocolVersion());
  821. }
  822. /**
  823. * Test withProtocolVersion()
  824. *
  825. * @return void
  826. */
  827. public function testWithProtocolVersion()
  828. {
  829. $request = new ServerRequest();
  830. $new = $request->withProtocolVersion('1.0');
  831. $this->assertNotSame($new, $request);
  832. $this->assertEquals('1.1', $request->getProtocolVersion());
  833. $this->assertEquals('1.0', $new->getProtocolVersion());
  834. }
  835. /**
  836. * Test withProtocolVersion() and invalid data
  837. *
  838. * @expectedException InvalidArgumentException
  839. * @expectedExceptionMessage Unsupported protocol version 'no good' provided
  840. * @return void
  841. */
  842. public function testWithProtocolVersionInvalid()
  843. {
  844. $request = new ServerRequest();
  845. $request->withProtocolVersion('no good');
  846. }
  847. /**
  848. * Test host retrieval.
  849. *
  850. * @return void
  851. */
  852. public function testHost()
  853. {
  854. $request = new ServerRequest(['environment' => [
  855. 'HTTP_HOST' => 'localhost',
  856. 'HTTP_X_FORWARDED_HOST' => 'cakephp.org',
  857. ]]);
  858. $this->assertEquals('localhost', $request->host());
  859. $request->trustProxy = true;
  860. $this->assertEquals('cakephp.org', $request->host());
  861. }
  862. /**
  863. * test port retrieval.
  864. *
  865. * @return void
  866. */
  867. public function testPort()
  868. {
  869. $request = new ServerRequest(['environment' => ['SERVER_PORT' => '80']]);
  870. $this->assertEquals('80', $request->port());
  871. $request->env('SERVER_PORT', '443');
  872. $request->env('HTTP_X_FORWARDED_PORT', '80');
  873. $this->assertEquals('443', $request->port());
  874. $request->trustProxy = true;
  875. $this->assertEquals('80', $request->port());
  876. }
  877. /**
  878. * test domain retrieval.
  879. *
  880. * @return void
  881. */
  882. public function testDomain()
  883. {
  884. $request = new ServerRequest(['environment' => ['HTTP_HOST' => 'something.example.com']]);
  885. $this->assertEquals('example.com', $request->domain());
  886. $request->env('HTTP_HOST', 'something.example.co.uk');
  887. $this->assertEquals('example.co.uk', $request->domain(2));
  888. }
  889. /**
  890. * Test scheme() method.
  891. *
  892. * @return void
  893. */
  894. public function testScheme()
  895. {
  896. $request = new ServerRequest(['environment' => ['HTTPS' => 'on']]);
  897. $this->assertEquals('https', $request->scheme());
  898. $request->env('HTTPS', '');
  899. $this->assertEquals('http', $request->scheme());
  900. $request->env('HTTP_X_FORWARDED_PROTO', 'https');
  901. $request->trustProxy = true;
  902. $this->assertEquals('https', $request->scheme());
  903. }
  904. /**
  905. * test getting subdomains for a host.
  906. *
  907. * @return void
  908. */
  909. public function testSubdomain()
  910. {
  911. $request = new ServerRequest(['environment' => ['HTTP_HOST' => 'something.example.com']]);
  912. $this->assertEquals(['something'], $request->subdomains());
  913. $request->env('HTTP_HOST', 'www.something.example.com');
  914. $this->assertEquals(['www', 'something'], $request->subdomains());
  915. $request->env('HTTP_HOST', 'www.something.example.co.uk');
  916. $this->assertEquals(['www', 'something'], $request->subdomains(2));
  917. $request->env('HTTP_HOST', 'example.co.uk');
  918. $this->assertEquals([], $request->subdomains(2));
  919. }
  920. /**
  921. * Test ajax, flash and friends
  922. *
  923. * @return void
  924. */
  925. public function testisAjaxFlashAndFriends()
  926. {
  927. $request = new ServerRequest();
  928. $request->env('HTTP_USER_AGENT', 'Shockwave Flash');
  929. $this->assertTrue($request->is('flash'));
  930. $request->env('HTTP_USER_AGENT', 'Adobe Flash');
  931. $this->assertTrue($request->is('flash'));
  932. $request->env('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest');
  933. $this->assertTrue($request->is('ajax'));
  934. $request->env('HTTP_X_REQUESTED_WITH', 'XMLHTTPREQUEST');
  935. $this->assertFalse($request->is('ajax'));
  936. $this->assertFalse($request->isAjax());
  937. }
  938. /**
  939. * Test __call exceptions
  940. *
  941. * @expectedException \BadMethodCallException
  942. * @return void
  943. */
  944. public function testMagicCallExceptionOnUnknownMethod()
  945. {
  946. $request = new ServerRequest();
  947. $request->IamABanana();
  948. }
  949. /**
  950. * Test is(ssl)
  951. *
  952. * @return void
  953. */
  954. public function testIsSsl()
  955. {
  956. $request = new ServerRequest();
  957. $request->env('HTTPS', 1);
  958. $this->assertTrue($request->is('ssl'));
  959. $request->env('HTTPS', 'on');
  960. $this->assertTrue($request->is('ssl'));
  961. $request->env('HTTPS', '1');
  962. $this->assertTrue($request->is('ssl'));
  963. $request->env('HTTPS', 'I am not empty');
  964. $this->assertFalse($request->is('ssl'));
  965. $request->env('HTTPS', 'off');
  966. $this->assertFalse($request->is('ssl'));
  967. $request->env('HTTPS', false);
  968. $this->assertFalse($request->is('ssl'));
  969. $request->env('HTTPS', '');
  970. $this->assertFalse($request->is('ssl'));
  971. }
  972. /**
  973. * Test getting request params with object properties.
  974. *
  975. * @return void
  976. */
  977. public function testMagicget()
  978. {
  979. $request = new ServerRequest();
  980. $request->params = ['controller' => 'posts', 'action' => 'view', 'plugin' => 'blogs'];
  981. $this->assertEquals('posts', $request->controller);
  982. $this->assertEquals('view', $request->action);
  983. $this->assertEquals('blogs', $request->plugin);
  984. $this->assertNull($request->banana);
  985. }
  986. /**
  987. * Test isset()/empty() with overloaded properties.
  988. *
  989. * @return void
  990. */
  991. public function testMagicisset()
  992. {
  993. $request = new ServerRequest();
  994. $request->params = [
  995. 'controller' => 'posts',
  996. 'action' => 'view',
  997. 'plugin' => 'blogs',
  998. ];
  999. $this->assertTrue(isset($request->controller));
  1000. $this->assertFalse(isset($request->notthere));
  1001. $this->assertFalse(empty($request->controller));
  1002. }
  1003. /**
  1004. * Test the array access implementation
  1005. *
  1006. * @return void
  1007. */
  1008. public function testArrayAccess()
  1009. {
  1010. $request = new ServerRequest();
  1011. $request->params = ['controller' => 'posts', 'action' => 'view', 'plugin' => 'blogs'];
  1012. $this->assertEquals('posts', $request['controller']);
  1013. $request['slug'] = 'speedy-slug';
  1014. $this->assertEquals('speedy-slug', $request->slug);
  1015. $this->assertEquals('speedy-slug', $request['slug']);
  1016. $this->assertTrue(isset($request['action']));
  1017. $this->assertFalse(isset($request['wrong-param']));
  1018. $this->assertTrue(isset($request['plugin']));
  1019. unset($request['plugin']);
  1020. $this->assertFalse(isset($request['plugin']));
  1021. $this->assertNull($request['plugin']);
  1022. $this->assertNull($request->plugin);
  1023. $request = new ServerRequest(['url' => 'some/path?one=something&two=else']);
  1024. $this->assertTrue(isset($request['url']['one']));
  1025. $request->data = ['Post' => ['title' => 'something']];
  1026. $this->assertEquals('something', $request['data']['Post']['title']);
  1027. }
  1028. /**
  1029. * Test adding detectors and having them work.
  1030. *
  1031. * @return void
  1032. */
  1033. public function testAddDetector()
  1034. {
  1035. $request = new ServerRequest();
  1036. ServerRequest::addDetector('closure', function ($request) {
  1037. return true;
  1038. });
  1039. $this->assertTrue($request->is('closure'));
  1040. ServerRequest::addDetector('get', function ($request) {
  1041. return $request->env('REQUEST_METHOD') === 'GET';
  1042. });
  1043. $request->env('REQUEST_METHOD', 'GET');
  1044. $this->assertTrue($request->is('get'));
  1045. ServerRequest::addDetector('compare', ['env' => 'TEST_VAR', 'value' => 'something']);
  1046. $request->env('TEST_VAR', 'something');
  1047. $this->assertTrue($request->is('compare'), 'Value match failed.');
  1048. $request->env('TEST_VAR', 'wrong');
  1049. $this->assertFalse($request->is('compare'), 'Value mis-match failed.');
  1050. ServerRequest::addDetector('compareCamelCase', ['env' => 'TEST_VAR', 'value' => 'foo']);
  1051. $request->env('TEST_VAR', 'foo');
  1052. $this->assertTrue($request->is('compareCamelCase'), 'Value match failed.');
  1053. $this->assertTrue($request->is('comparecamelcase'), 'detectors should be case insensitive');
  1054. $this->assertTrue($request->is('COMPARECAMELCASE'), 'detectors should be case insensitive');
  1055. $request->env('TEST_VAR', 'not foo');
  1056. $this->assertFalse($request->is('compareCamelCase'), 'Value match failed.');
  1057. $this->assertFalse($request->is('comparecamelcase'), 'detectors should be case insensitive');
  1058. $this->assertFalse($request->is('COMPARECAMELCASE'), 'detectors should be case insensitive');
  1059. ServerRequest::addDetector('banana', ['env' => 'TEST_VAR', 'pattern' => '/^ban.*$/']);
  1060. $request->env('TEST_VAR', 'banana');
  1061. $this->assertTrue($request->isBanana());
  1062. $request->env('TEST_VAR', 'wrong value');
  1063. $this->assertFalse($request->isBanana());
  1064. ServerRequest::addDetector('mobile', ['env' => 'HTTP_USER_AGENT', 'options' => ['Imagination']]);
  1065. $request->env('HTTP_USER_AGENT', 'Imagination land');
  1066. $this->assertTrue($request->isMobile());
  1067. ServerRequest::addDetector('index', ['param' => 'action', 'value' => 'index']);
  1068. $request->params['action'] = 'index';
  1069. $request->clearDetectorCache();
  1070. $this->assertTrue($request->isIndex());
  1071. $request->params['action'] = 'add';
  1072. $request->clearDetectorCache();
  1073. $this->assertFalse($request->isIndex());
  1074. ServerRequest::addDetector('callme', [$this, 'detectCallback']);
  1075. $request->return = true;
  1076. $request->clearDetectorCache();
  1077. $this->assertTrue($request->isCallMe());
  1078. ServerRequest::addDetector('extension', ['param' => '_ext', 'options' => ['pdf', 'png', 'txt']]);
  1079. $request->params['_ext'] = 'pdf';
  1080. $request->clearDetectorCache();
  1081. $this->assertTrue($request->is('extension'));
  1082. $request->params['_ext'] = 'exe';
  1083. $request->clearDetectorCache();
  1084. $this->assertFalse($request->isExtension());
  1085. }
  1086. /**
  1087. * Helper function for testing callbacks.
  1088. *
  1089. * @param $request
  1090. * @return bool
  1091. */
  1092. public function detectCallback($request)
  1093. {
  1094. return (bool)$request->return;
  1095. }
  1096. /**
  1097. * Test getting headers
  1098. *
  1099. * @return void
  1100. */
  1101. public function testHeader()
  1102. {
  1103. $request = new ServerRequest(['environment' => [
  1104. 'HTTP_HOST' => 'localhost',
  1105. 'HTTP_USER_AGENT' => 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_4; en-ca) AppleWebKit/534.8+ (KHTML, like Gecko) Version/5.0 Safari/533.16',
  1106. 'CONTENT_TYPE' => 'application/json',
  1107. 'CONTENT_LENGTH' => 1337,
  1108. 'HTTP_CONTENT_MD5' => 'abc123'
  1109. ]]);
  1110. $this->assertEquals($request->env('HTTP_HOST'), $request->header('host'));
  1111. $this->assertEquals($request->env('HTTP_USER_AGENT'), $request->header('User-Agent'));
  1112. $this->assertEquals($request->env('CONTENT_LENGTH'), $request->header('content-length'));
  1113. $this->assertEquals($request->env('CONTENT_TYPE'), $request->header('content-type'));
  1114. $this->assertEquals($request->env('HTTP_CONTENT_MD5'), $request->header('content-md5'));
  1115. }
  1116. /**
  1117. * Test getting headers with psr7 methods
  1118. *
  1119. * @return void
  1120. */
  1121. public function testGetHeaders()
  1122. {
  1123. $request = new ServerRequest(['environment' => [
  1124. 'HTTP_HOST' => 'localhost',
  1125. 'CONTENT_TYPE' => 'application/json',
  1126. 'CONTENT_LENGTH' => 1337,
  1127. 'HTTP_CONTENT_MD5' => 'abc123',
  1128. 'HTTP_DOUBLE' => ['a', 'b']
  1129. ]]);
  1130. $headers = $request->getHeaders();
  1131. $expected = [
  1132. 'Host' => ['localhost'],
  1133. 'Content-Type' => ['application/json'],
  1134. 'Content-Length' => [1337],
  1135. 'Content-Md5' => ['abc123'],
  1136. 'Double' => ['a', 'b'],
  1137. ];
  1138. $this->assertEquals($expected, $headers);
  1139. }
  1140. /**
  1141. * Test hasHeader
  1142. *
  1143. * @return void
  1144. */
  1145. public function testHasHeader()
  1146. {
  1147. $request = new ServerRequest(['environment' => [
  1148. 'HTTP_HOST' => 'localhost',
  1149. 'CONTENT_TYPE' => 'application/json',
  1150. 'CONTENT_LENGTH' => 1337,
  1151. 'HTTP_CONTENT_MD5' => 'abc123',
  1152. 'HTTP_DOUBLE' => ['a', 'b']
  1153. ]]);
  1154. $this->assertTrue($request->hasHeader('Host'));
  1155. $this->assertTrue($request->hasHeader('Content-Type'));
  1156. $this->assertTrue($request->hasHeader('Content-MD5'));
  1157. $this->assertTrue($request->hasHeader('Double'));
  1158. $this->assertFalse($request->hasHeader('Authorization'));
  1159. }
  1160. /**
  1161. * Test getting headers with psr7 methods
  1162. *
  1163. * @return void
  1164. */
  1165. public function testGetHeader()
  1166. {
  1167. $request = new ServerRequest(['environment' => [
  1168. 'HTTP_HOST' => 'localhost',
  1169. 'CONTENT_TYPE' => 'application/json',
  1170. 'CONTENT_LENGTH' => 1337,
  1171. 'HTTP_CONTENT_MD5' => 'abc123',
  1172. 'HTTP_DOUBLE' => ['a', 'b']
  1173. ]]);
  1174. $this->assertEquals([], $request->getHeader('Not-there'));
  1175. $expected = [$request->env('HTTP_HOST')];
  1176. $this->assertEquals($expected, $request->getHeader('Host'));
  1177. $this->assertEquals($expected, $request->getHeader('host'));
  1178. $this->assertEquals($expected, $request->getHeader('HOST'));
  1179. $this->assertEquals(['a', 'b'], $request->getHeader('Double'));
  1180. }
  1181. /**
  1182. * Test getting headers with psr7 methods
  1183. *
  1184. * @return void
  1185. */
  1186. public function testGetHeaderLine()
  1187. {
  1188. $request = new ServerRequest(['environment' => [
  1189. 'HTTP_HOST' => 'localhost',
  1190. 'CONTENT_TYPE' => 'application/json',
  1191. 'CONTENT_LENGTH' => 1337,
  1192. 'HTTP_CONTENT_MD5' => 'abc123',
  1193. 'HTTP_DOUBLE' => ['a', 'b']
  1194. ]]);
  1195. $this->assertEquals('', $request->getHeaderLine('Authorization'));
  1196. $expected = $request->env('CONTENT_LENGTH');
  1197. $this->assertEquals($expected, $request->getHeaderLine('Content-Length'));
  1198. $this->assertEquals($expected, $request->getHeaderLine('content-Length'));
  1199. $this->assertEquals($expected, $request->getHeaderLine('ConTent-LenGth'));
  1200. $this->assertEquals('a, b', $request->getHeaderLine('Double'));
  1201. }
  1202. /**
  1203. * Test setting a header.
  1204. *
  1205. * @return void
  1206. */
  1207. public function testWithHeader()
  1208. {
  1209. $request = new ServerRequest(['environment' => [
  1210. 'HTTP_HOST' => 'localhost',
  1211. 'CONTENT_TYPE' => 'application/json',
  1212. 'CONTENT_LENGTH' => 1337,
  1213. 'HTTP_CONTENT_MD5' => 'abc123',
  1214. 'HTTP_DOUBLE' => ['a', 'b']
  1215. ]]);
  1216. $new = $request->withHeader('Content-Length', 999);
  1217. $this->assertNotSame($new, $request);
  1218. $this->assertEquals(1337, $request->getHeaderLine('Content-length'), 'old request is unchanged');
  1219. $this->assertEquals(999, $new->getHeaderLine('Content-length'), 'new request is correct');
  1220. $this->assertEquals(999, $new->header('Content-Length'));
  1221. $new = $request->withHeader('Double', ['a']);
  1222. $this->assertEquals(['a'], $new->getHeader('Double'), 'List values are overwritten');
  1223. $this->assertEquals(['a'], $new->header('Double'), 'headers written in bc way.');
  1224. }
  1225. /**
  1226. * Test adding a header.
  1227. *
  1228. * @return void
  1229. */
  1230. public function testWithAddedHeader()
  1231. {
  1232. $request = new ServerRequest(['environment' => [
  1233. 'HTTP_HOST' => 'localhost',
  1234. 'CONTENT_TYPE' => 'application/json',
  1235. 'CONTENT_LENGTH' => 1337,
  1236. 'HTTP_CONTENT_MD5' => 'abc123',
  1237. 'HTTP_DOUBLE' => ['a', 'b']
  1238. ]]);
  1239. $new = $request->withAddedHeader('Double', 'c');
  1240. $this->assertNotSame($new, $request);
  1241. $this->assertEquals('a, b', $request->getHeaderLine('Double'), 'old request is unchanged');
  1242. $this->assertEquals('a, b, c', $new->getHeaderLine('Double'), 'new request is correct');
  1243. $this->assertEquals(['a', 'b', 'c'], $new->header('Double'));
  1244. $new = $request->withAddedHeader('Content-Length', 777);
  1245. $this->assertEquals([1337, 777], $new->getHeader('Content-Length'), 'scalar values are appended');
  1246. $new = $request->withAddedHeader('Content-Length', [123, 456]);
  1247. $this->assertEquals([1337, 123, 456], $new->getHeader('Content-Length'), 'List values are merged');
  1248. }
  1249. /**
  1250. * Test removing a header.
  1251. *
  1252. * @return void
  1253. */
  1254. public function testWithoutHeader()
  1255. {
  1256. $request = new ServerRequest(['environment' => [
  1257. 'HTTP_HOST' => 'localhost',
  1258. 'CONTENT_TYPE' => 'application/json',
  1259. 'CONTENT_LENGTH' => 1337,
  1260. 'HTTP_CONTENT_MD5' => 'abc123',
  1261. 'HTTP_DOUBLE' => ['a', 'b']
  1262. ]]);
  1263. $new = $request->withoutHeader('Content-Length', 999);
  1264. $this->assertNotSame($new, $request);
  1265. $this->assertEquals(1337, $request->getHeaderLine('Content-length'), 'old request is unchanged');
  1266. $this->assertEquals('', $new->getHeaderLine('Content-length'), 'new request is correct');
  1267. $this->assertNull($new->header('Content-Length'));
  1268. }
  1269. /**
  1270. * Test accepts() with and without parameters
  1271. *
  1272. * @return void
  1273. */
  1274. public function testAccepts()
  1275. {
  1276. $request = new ServerRequest(['environment' => [
  1277. 'HTTP_ACCEPT' => 'text/xml,application/xml;q=0.9,application/xhtml+xml,text/html,text/plain,image/png'
  1278. ]]);
  1279. $result = $request->accepts();
  1280. $expected = [
  1281. 'text/xml', 'application/xhtml+xml', 'text/html', 'text/plain', 'image/png', 'application/xml'
  1282. ];
  1283. $this->assertEquals($expected, $result, 'Content types differ.');
  1284. $result = $request->accepts('text/html');
  1285. $this->assertTrue($result);
  1286. $result = $request->accepts('image/gif');
  1287. $this->assertFalse($result);
  1288. }
  1289. /**
  1290. * Test that accept header types are trimmed for comparisons.
  1291. *
  1292. * @return void
  1293. */
  1294. public function testAcceptWithWhitespace()
  1295. {
  1296. $request = new ServerRequest(['environment' => [
  1297. 'HTTP_ACCEPT' => 'text/xml , text/html , text/plain,image/png'
  1298. ]]);
  1299. $result = $request->accepts();
  1300. $expected = [
  1301. 'text/xml', 'text/html', 'text/plain', 'image/png'
  1302. ];
  1303. $this->assertEquals($expected, $result, 'Content types differ.');
  1304. $this->assertTrue($request->accepts('text/html'));
  1305. }
  1306. /**
  1307. * Content types from accepts() should respect the client's q preference values.
  1308. *
  1309. * @return void
  1310. */
  1311. public function testAcceptWithQvalueSorting()
  1312. {
  1313. $request = new ServerRequest(['environment' => [
  1314. 'HTTP_ACCEPT' => 'text/html;q=0.8,application/json;q=0.7,application/xml;q=1.0'
  1315. ]]);
  1316. $result = $request->accepts();
  1317. $expected = ['application/xml', 'text/html', 'application/json'];
  1318. $this->assertEquals($expected, $result);
  1319. }
  1320. /**
  1321. * Test the raw parsing of accept headers into the q value formatting.
  1322. *
  1323. * @return void
  1324. */
  1325. public function testParseAcceptWithQValue()
  1326. {
  1327. $request = new ServerRequest(['environment' => [
  1328. 'HTTP_ACCEPT' => 'text/html;q=0.8,application/json;q=0.7,application/xml;q=1.0,image/png'
  1329. ]]);
  1330. $result = $request->parseAccept();
  1331. $expected = [
  1332. '1.0' => ['application/xml', 'image/png'],
  1333. '0.8' => ['text/html'],
  1334. '0.7' => ['application/json'],
  1335. ];
  1336. $this->assertEquals($expected, $result);
  1337. }
  1338. /**
  1339. * Test parsing accept with a confusing accept value.
  1340. *
  1341. * @return void
  1342. */
  1343. public function testParseAcceptNoQValues()
  1344. {
  1345. $request = new ServerRequest(['environment' => [
  1346. 'HTTP_ACCEPT' => 'application/json, text/plain, */*'
  1347. ]]);
  1348. $result = $request->parseAccept();
  1349. $expected = [
  1350. '1.0' => ['application/json', 'text/plain', '*/*'],
  1351. ];
  1352. $this->assertEquals($expected, $result);
  1353. }
  1354. /**
  1355. * Test parsing accept ignores index param
  1356. *
  1357. * @return void
  1358. */
  1359. public function testParseAcceptIgnoreAcceptExtensions()
  1360. {
  1361. $request = new ServerRequest(['environment' => [
  1362. 'url' => '/',
  1363. 'HTTP_ACCEPT' => 'application/json;level=1, text/plain, */*'
  1364. ]], false);
  1365. $result = $request->parseAccept();
  1366. $expected = [
  1367. '1.0' => ['application/json', 'text/plain', '*/*'],
  1368. ];
  1369. $this->assertEquals($expected, $result);
  1370. }
  1371. /**
  1372. * Test that parsing accept headers with invalid syntax works.
  1373. *
  1374. * The header used is missing a q value for application/xml.
  1375. *
  1376. * @return void
  1377. */
  1378. public function testParseAcceptInvalidSyntax()
  1379. {
  1380. $request = new ServerRequest(['environment' => [
  1381. 'url' => '/',
  1382. 'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;image/png,image/jpeg,image/*;q=0.9,*/*;q=0.8'
  1383. ]], false);
  1384. $result = $request->parseAccept();
  1385. $expected = [
  1386. '1.0' => ['text/html', 'application/xhtml+xml', 'application/xml', 'image/jpeg'],
  1387. '0.9' => ['image/*'],
  1388. '0.8' => ['*/*'],
  1389. ];
  1390. $this->assertEquals($expected, $result);
  1391. }
  1392. /**
  1393. * Test baseUrl and webroot with ModRewrite
  1394. *
  1395. * @return void
  1396. */
  1397. public function testBaseUrlAndWebrootWithModRewrite()
  1398. {
  1399. Configure::write('App.baseUrl', false);
  1400. $_SERVER['DOCUMENT_ROOT'] = '/cake/repo/branches';
  1401. $_SERVER['PHP_SELF'] = '/urlencode me/webroot/index.php';
  1402. $_SERVER['PATH_INFO'] = '/posts/view/1';
  1403. $request = ServerRequestFactory::fromGlobals();
  1404. $this->assertEquals('/urlencode%20me', $request->base);
  1405. $this->assertEquals('/urlencode%20me/', $request->webroot);
  1406. $this->assertEquals('posts/view/1', $request->url);
  1407. $_SERVER['DOCUMENT_ROOT'] = '/cake/repo/branches';
  1408. $_SERVER['PHP_SELF'] = '/1.2.x.x/webroot/index.php';
  1409. $_SERVER['PATH_INFO'] = '/posts/view/1';
  1410. $request = ServerRequestFactory::fromGlobals();
  1411. $this->assertEquals('/1.2.x.x', $request->base);
  1412. $this->assertEquals('/1.2.x.x/', $request->webroot);
  1413. $this->assertEquals('posts/view/1', $request->url);
  1414. $_SERVER['DOCUMENT_ROOT'] = '/cake/repo/branches/1.2.x.x/webroot';
  1415. $_SERVER['PHP_SELF'] = '/index.php';
  1416. $_SERVER['PATH_INFO'] = '/posts/add';
  1417. $request = ServerRequestFactory::fromGlobals();
  1418. $this->assertEquals('', $request->base);
  1419. $this->assertEquals('/', $request->webroot);
  1420. $this->assertEquals('posts/add', $request->url);
  1421. $_SERVER['DOCUMENT_ROOT'] = '/cake/repo/branches/1.2.x.x/test/';
  1422. $_SERVER['PHP_SELF'] = '/webroot/index.php';
  1423. $request = ServerRequestFactory::fromGlobals();
  1424. $this->assertEquals('', $request->base);
  1425. $this->assertEquals('/', $request->webroot);
  1426. $_SERVER['DOCUMENT_ROOT'] = '/some/apps/where';
  1427. $_SERVER['PHP_SELF'] = '/webroot/index.php';
  1428. $request = ServerRequestFactory::fromGlobals();
  1429. $this->assertEquals('', $request->base);
  1430. $this->assertEquals('/', $request->webroot);
  1431. Configure::write('App.dir', 'auth');
  1432. $_SERVER['DOCUMENT_ROOT'] = '/cake/repo/branches';
  1433. $_SERVER['PHP_SELF'] = '/demos/webroot/index.php';
  1434. $request = ServerRequestFactory::fromGlobals();
  1435. $this->assertEquals('/demos', $request->base);
  1436. $this->assertEquals('/demos/', $request->webroot);
  1437. Configure::write('App.dir', 'code');
  1438. $_SERVER['DOCUMENT_ROOT'] = '/Library/WebServer/Documents';
  1439. $_SERVER['PHP_SELF'] = '/clients/PewterReport/webroot/index.php';
  1440. $request = ServerRequestFactory::fromGlobals();
  1441. $this->assertEquals('/clients/PewterReport', $request->base);
  1442. $this->assertEquals('/clients/PewterReport/', $request->webroot);
  1443. }
  1444. /**
  1445. * Test baseUrl with ModRewrite alias
  1446. *
  1447. * @return void
  1448. */
  1449. public function testBaseUrlwithModRewriteAlias()
  1450. {
  1451. $_SERVER['DOCUMENT_ROOT'] = '/home/aplusnur/public_html';
  1452. $_SERVER['PHP_SELF'] = '/control/index.php';
  1453. Configure::write('App.base', '/control');
  1454. $request = ServerRequestFactory::fromGlobals();
  1455. $this->assertEquals('/control', $request->base);
  1456. $this->assertEquals('/control/', $request->webroot);
  1457. Configure::write('App.base', false);
  1458. Configure::write('App.dir', 'affiliate');
  1459. Configure::write('App.webroot', 'newaffiliate');
  1460. $_SERVER['DOCUMENT_ROOT'] = '/var/www/abtravaff/html';
  1461. $_SERVER['PHP_SELF'] = '/newaffiliate/index.php';
  1462. $request = ServerRequestFactory::fromGlobals();
  1463. $this->assertEquals('', $request->base);
  1464. $this->assertEquals('/', $request->webroot);
  1465. }
  1466. /**
  1467. * Test base, webroot, URL and here parsing when there is URL rewriting but
  1468. * CakePHP gets called with index.php in URL nonetheless.
  1469. *
  1470. * Tests uri with
  1471. * - index.php/
  1472. * - index.php/
  1473. * - index.php/apples/
  1474. * - index.php/bananas/eat/tasty_banana
  1475. *
  1476. * @return void
  1477. */
  1478. public function testBaseUrlWithModRewriteAndIndexPhp()
  1479. {
  1480. $_SERVER['REQUEST_URI'] = '/cakephp/webroot/index.php';
  1481. $_SERVER['PHP_SELF'] = '/cakephp/webroot/index.php';
  1482. unset($_SERVER['PATH_INFO']);
  1483. $request = ServerRequestFactory::fromGlobals();
  1484. $this->assertEquals('/cakephp', $request->base);
  1485. $this->assertEquals('/cakephp/', $request->webroot);
  1486. $this->assertEquals('', $request->url);
  1487. $this->assertEquals('/cakephp/', $request->here);
  1488. $_SERVER['REQUEST_URI'] = '/cakephp/webroot/index.php/';
  1489. $_SERVER['PHP_SELF'] = '/cakephp/webroot/index.php/';
  1490. $_SERVER['PATH_INFO'] = '/';
  1491. $request = ServerRequestFactory::fromGlobals();
  1492. $this->assertEquals('/cakephp', $request->base);
  1493. $this->assertEquals('/cakephp/', $request->webroot);
  1494. $this->assertEquals('', $request->url);
  1495. $this->assertEquals('/cakephp/', $request->here);
  1496. $_SERVER['REQUEST_URI'] = '/cakephp/webroot/index.php/apples';
  1497. $_SERVER['PHP_SELF'] = '/cakephp/webroot/index.php/apples';
  1498. $_SERVER['PATH_INFO'] = '/apples';
  1499. $request = ServerRequestFactory::fromGlobals();
  1500. $this->assertEquals('/cakephp', $request->base);
  1501. $this->assertEquals('/cakephp/', $request->webroot);
  1502. $this->assertEquals('apples', $request->url);
  1503. $this->assertEquals('/cakephp/apples', $request->here);
  1504. $_SERVER['REQUEST_URI'] = '/cakephp/webroot/index.php/melons/share/';
  1505. $_SERVER['PHP_SELF'] = '/cakephp/webroot/index.php/melons/share/';
  1506. $_SERVER['PATH_INFO'] = '/melons/share/';
  1507. $request = ServerRequestFactory::fromGlobals();
  1508. $this->assertEquals('/cakephp', $request->base);
  1509. $this->assertEquals('/cakephp/', $request->webroot);
  1510. $this->assertEquals('melons/share/', $request->url);
  1511. $this->assertEquals('/cakephp/melons/share/', $request->here);
  1512. $_SERVER['REQUEST_URI'] = '/cakephp/webroot/index.php/bananas/eat/tasty_banana';
  1513. $_SERVER['PHP_SELF'] = '/cakephp/webroot/index.php/bananas/eat/tasty_banana';
  1514. $_SERVER['PATH_INFO'] = '/bananas/eat/tasty_banana';
  1515. $request = ServerRequestFactory::fromGlobals();
  1516. $this->assertEquals('/cakephp', $request->base);
  1517. $this->assertEquals('/cakephp/', $request->webroot);
  1518. $this->assertEquals('bananas/eat/tasty_banana', $request->url);
  1519. $this->assertEquals('/cakephp/bananas/eat/tasty_banana', $request->here);
  1520. }
  1521. /**
  1522. * Test that even if mod_rewrite is on, and the url contains index.php
  1523. * and there are numerous //s that the base/webroot is calculated correctly.
  1524. *
  1525. * @return void
  1526. */
  1527. public function testBaseUrlWithModRewriteAndExtraSlashes()
  1528. {
  1529. $_SERVER['REQUEST_URI'] = '/cakephp/webroot///index.php/bananas/eat';
  1530. $_SERVER['PHP_SELF'] = '/cakephp/webroot///index.php/bananas/eat';
  1531. $_SERVER['PATH_INFO'] = '/bananas/eat';
  1532. $request = ServerRequestFactory::fromGlobals();
  1533. $this->assertEquals('/cakephp', $request->base);
  1534. $this->assertEquals('/cakephp/', $request->webroot);
  1535. $this->assertEquals('bananas/eat', $request->url);
  1536. $this->assertEquals('/cakephp/bananas/eat', $request->here);
  1537. }
  1538. /**
  1539. * Test base, webroot, and URL parsing when there is no URL rewriting
  1540. *
  1541. * @return void
  1542. */
  1543. public function testBaseUrlWithNoModRewrite()
  1544. {
  1545. $_SERVER['DOCUMENT_ROOT'] = '/Users/markstory/Sites';
  1546. $_SERVER['SCRIPT_FILENAME'] = '/Users/markstory/Sites/cake/index.php';
  1547. $_SERVER['PHP_SELF'] = '/cake/index.php/posts/index';
  1548. $_SERVER['REQUEST_URI'] = '/cake/index.php/posts/index';
  1549. Configure::write('App', [
  1550. 'dir' => APP_DIR,
  1551. 'webroot' => 'webroot',
  1552. 'base' => false,
  1553. 'baseUrl' => '/cake/index.php'
  1554. ]);
  1555. $request = ServerRequestFactory::fromGlobals();
  1556. $this->assertEquals('/cake/index.php', $request->base);
  1557. $this->assertEquals('/cake/webroot/', $request->webroot);
  1558. $this->assertEquals('posts/index', $request->url);
  1559. }
  1560. /**
  1561. * Test baseUrl and webroot with baseUrl
  1562. *
  1563. * @return void
  1564. */
  1565. public function testBaseUrlAndWebrootWithBaseUrl()
  1566. {
  1567. Configure::write('App.dir', 'App');
  1568. Configure::write('App.baseUrl', '/App/webroot/index.php');
  1569. $request = ServerRequestFactory::fromGlobals();
  1570. $this->assertEquals('/App/webroot/index.php', $request->base);
  1571. $this->assertEquals('/App/webroot/', $request->webroot);
  1572. Configure::write('App.baseUrl', '/App/webroot/test.php');
  1573. $request = ServerRequestFactory::fromGlobals();
  1574. $this->assertEquals('/App/webroot/test.php', $request->base);
  1575. $this->assertEquals('/App/webroot/', $request->webroot);
  1576. Configure::write('App.baseUrl', '/App/index.php');
  1577. $request = ServerRequestFactory::fromGlobals();
  1578. $this->assertEquals('/App/index.php', $request->base);
  1579. $this->assertEquals('/App/webroot/', $request->webroot);
  1580. Configure::write('App.baseUrl', '/CakeBB/App/webroot/index.php');
  1581. $request = ServerRequestFactory::fromGlobals();
  1582. $this->assertEquals('/CakeBB/App/webroot/index.php', $request->base);
  1583. $this->assertEquals('/CakeBB/App/webroot/', $request->webroot);
  1584. Configure::write('App.baseUrl', '/CakeBB/App/index.php');
  1585. $request = ServerRequestFactory::fromGlobals();
  1586. $this->assertEquals('/CakeBB/App/index.php', $request->base);
  1587. $this->assertEquals('/CakeBB/App/webroot/', $request->webroot);
  1588. Configure::write('App.baseUrl', '/CakeBB/index.php');
  1589. $request = ServerRequestFactory::fromGlobals();
  1590. $this->assertEquals('/CakeBB/index.php', $request->base);
  1591. $this->assertEquals('/CakeBB/webroot/', $request->webroot);
  1592. Configure::write('App.baseUrl', '/dbhauser/index.php');
  1593. $_SERVER['DOCUMENT_ROOT'] = '/kunden/homepages/4/d181710652/htdocs/joomla';
  1594. $_SERVER['SCRIPT_FILENAME'] = '/kunden/homepages/4/d181710652/htdocs/joomla/dbhauser/index.php';
  1595. $request = ServerRequestFactory::fromGlobals();
  1596. $this->assertEquals('/dbhauser/index.php', $request->base);
  1597. $this->assertEquals('/dbhauser/webroot/', $request->webroot);
  1598. }
  1599. /**
  1600. * Test baseUrl with no rewrite and using the top level index.php.
  1601. *
  1602. * @return void
  1603. */
  1604. public function testBaseUrlNoRewriteTopLevelIndex()
  1605. {
  1606. Configure::write('App.baseUrl', '/index.php');
  1607. $_SERVER['DOCUMENT_ROOT'] = '/Users/markstory/Sites/cake_dev';
  1608. $_SERVER['SCRIPT_FILENAME'] = '/Users/markstory/Sites/cake_dev/index.php';
  1609. $request = ServerRequestFactory::fromGlobals();
  1610. $this->assertEquals('/index.php', $request->base);
  1611. $this->assertEquals('/webroot/', $request->webroot);
  1612. }
  1613. /**
  1614. * Check that a sub-directory containing app|webroot doesn't get mishandled when re-writing is off.
  1615. *
  1616. * @return void
  1617. */
  1618. public function testBaseUrlWithAppAndWebrootInDirname()
  1619. {
  1620. Configure::write('App.baseUrl', '/approval/index.php');
  1621. $_SERVER['DOCUMENT_ROOT'] = '/Users/markstory/Sites/';
  1622. $_SERVER['SCRIPT_FILENAME'] = '/Users/markstory/Sites/approval/index.php';
  1623. $request = ServerRequestFactory::fromGlobals();
  1624. $this->assertEquals('/approval/index.php', $request->base);
  1625. $this->assertEquals('/approval/webroot/', $request->webroot);
  1626. Configure::write('App.baseUrl', '/webrootable/index.php');
  1627. $_SERVER['DOCUMENT_ROOT'] = '/Users/markstory/Sites/';
  1628. $_SERVER['SCRIPT_FILENAME'] = '/Users/markstory/Sites/webrootable/index.php';
  1629. $request = ServerRequestFactory::fromGlobals();
  1630. $this->assertEquals('/webrootable/index.php', $request->base);
  1631. $this->assertEquals('/webrootable/webroot/', $request->webroot);
  1632. }
  1633. /**
  1634. * Test baseUrl with no rewrite, and using the app/webroot/index.php file as is normal with virtual hosts.
  1635. *
  1636. * @return void
  1637. */
  1638. public function testBaseUrlNoRewriteWebrootIndex()
  1639. {
  1640. Configure::write('App.baseUrl', '/index.php');
  1641. $_SERVER['DOCUMENT_ROOT'] = '/Users/markstory/Sites/cake_dev/webroot';
  1642. $_SERVER['SCRIPT_FILENAME'] = '/Users/markstory/Sites/cake_dev/webroot/index.php';
  1643. $request = ServerRequestFactory::fromGlobals();
  1644. $this->assertEquals('/index.php', $request->base);
  1645. $this->assertEquals('/', $request->webroot);
  1646. }
  1647. /**
  1648. * Test that a request with a . in the main GET parameter is filtered out.
  1649. * PHP changes GET parameter keys containing dots to _.
  1650. *
  1651. * @return void
  1652. */
  1653. public function testGetParamsWithDot()
  1654. {
  1655. $_GET = [];
  1656. $_GET['/posts/index/add_add'] = '';
  1657. $_SERVER['PHP_SELF'] = '/webroot/index.php';
  1658. $_SERVER['REQUEST_URI'] = '/posts/index/add.add';
  1659. $request = ServerRequestFactory::fromGlobals();
  1660. $this->assertEquals('', $request->base);
  1661. $this->assertEquals([], $request->query);
  1662. $_GET = [];
  1663. $_GET['/cake_dev/posts/index/add_add'] = '';
  1664. $_SERVER['PHP_SELF'] = '/cake_dev/webroot/index.php';
  1665. $_SERVER['REQUEST_URI'] = '/cake_dev/posts/index/add.add';
  1666. $request = ServerRequestFactory::fromGlobals();
  1667. $this->assertEquals('/cake_dev', $request->base);
  1668. $this->assertEquals([], $request->query);
  1669. }
  1670. /**
  1671. * Test that a request with urlencoded bits in the main GET parameter are filtered out.
  1672. *
  1673. * @return void
  1674. */
  1675. public function testGetParamWithUrlencodedElement()
  1676. {
  1677. $_GET = [];
  1678. $_GET['/posts/add/∂∂'] = '';
  1679. $_SERVER['PHP_SELF'] = '/webroot/index.php';
  1680. $_SERVER['REQUEST_URI'] = '/posts/add/%E2%88%82%E2%88%82';
  1681. $request = ServerRequestFactory::fromGlobals();
  1682. $this->assertEquals('', $request->base);
  1683. $this->assertEquals([], $request->query);
  1684. $_GET = [];
  1685. $_GET['/cake_dev/posts/add/∂∂'] = '';
  1686. $_SERVER['PHP_SELF'] = '/cake_dev/webroot/index.php';
  1687. $_SERVER['REQUEST_URI'] = '/cake_dev/posts/add/%E2%88%82%E2%88%82';
  1688. $request = ServerRequestFactory::fromGlobals();
  1689. $this->assertEquals('/cake_dev', $request->base);
  1690. $this->assertEquals([], $request->query);
  1691. }
  1692. /**
  1693. * Generator for environment configurations
  1694. *
  1695. * @return array Environment array
  1696. */
  1697. public static function environmentGenerator()
  1698. {
  1699. return [
  1700. [
  1701. 'IIS - No rewrite base path',
  1702. [
  1703. 'App' => [
  1704. 'base' => false,
  1705. 'baseUrl' => '/index.php',
  1706. 'dir' => 'TestApp',
  1707. 'webroot' => 'webroot'
  1708. ],
  1709. 'SERVER' => [
  1710. 'SCRIPT_NAME' => '/index.php',
  1711. 'PATH_TRANSLATED' => 'C:\\Inetpub\\wwwroot',
  1712. 'QUERY_STRING' => '',
  1713. 'REQUEST_URI' => '/index.php',
  1714. 'URL' => '/index.php',
  1715. 'SCRIPT_FILENAME' => 'C:\\Inetpub\\wwwroot\\index.php',
  1716. 'ORIG_PATH_INFO' => '/index.php',
  1717. 'PATH_INFO' => '',
  1718. 'ORIG_PATH_TRANSLATED' => 'C:\\Inetpub\\wwwroot\\index.php',
  1719. 'DOCUMENT_ROOT' => 'C:\\Inetpub\\wwwroot',
  1720. 'PHP_SELF' => '/index.php',
  1721. ],
  1722. ],
  1723. [
  1724. 'base' => '/index.php',
  1725. 'webroot' => '/webroot/',
  1726. 'url' => ''
  1727. ],
  1728. ],
  1729. [
  1730. 'IIS - No rewrite with path, no PHP_SELF',
  1731. [
  1732. 'App' => [
  1733. 'base' => false,
  1734. 'baseUrl' => '/index.php?',
  1735. 'dir' => 'TestApp',
  1736. 'webroot' => 'webroot'
  1737. ],
  1738. 'SERVER' => [
  1739. 'QUERY_STRING' => '/posts/add',
  1740. 'REQUEST_URI' => '/index.php?/posts/add',
  1741. 'PHP_SELF' => '',
  1742. 'URL' => '/index.php?/posts/add',
  1743. 'DOCUMENT_ROOT' => 'C:\\Inetpub\\wwwroot',
  1744. 'argv' => ['/posts/add'],
  1745. 'argc' => 1
  1746. ],
  1747. ],
  1748. [
  1749. 'url' => 'posts/add',
  1750. 'base' => '/index.php?',
  1751. 'webroot' => '/webroot/'
  1752. ]
  1753. ],
  1754. [
  1755. 'IIS - No rewrite sub dir 2',
  1756. [
  1757. 'App' => [
  1758. 'base' => false,
  1759. 'baseUrl' => '/site/index.php',
  1760. 'dir' => 'TestApp',
  1761. 'webroot' => 'webroot',
  1762. ],
  1763. 'SERVER' => [
  1764. 'SCRIPT_NAME' => '/site/index.php',
  1765. 'PATH_TRANSLATED' => 'C:\\Inetpub\\wwwroot',
  1766. 'QUERY_STRING' => '',
  1767. 'REQUEST_URI' => '/site/index.php',
  1768. 'URL' => '/site/index.php',
  1769. 'SCRIPT_FILENAME' => 'C:\\Inetpub\\wwwroot\\site\\index.php',
  1770. 'DOCUMENT_ROOT' => 'C:\\Inetpub\\wwwroot',
  1771. 'PHP_SELF' => '/site/index.php',
  1772. 'argv' => [],
  1773. 'argc' => 0
  1774. ],
  1775. ],
  1776. [
  1777. 'url' => '',
  1778. 'base' => '/site/index.php',
  1779. 'webroot' => '/site/webroot/'
  1780. ],
  1781. ],
  1782. [
  1783. 'IIS - No rewrite sub dir 2 with path',
  1784. [
  1785. 'App' => [
  1786. 'base' => false,
  1787. 'baseUrl' => '/site/index.php',
  1788. 'dir' => 'TestApp',
  1789. 'webroot' => 'webroot'
  1790. ],
  1791. 'GET' => ['/posts/add' => ''],
  1792. 'SERVER' => [
  1793. 'SCRIPT_NAME' => '/site/index.php',
  1794. 'PATH_TRANSLATED' => 'C:\\Inetpub\\wwwroot',
  1795. 'QUERY_STRING' => '/posts/add',
  1796. 'REQUEST_URI' => '/site/index.php/posts/add',
  1797. 'URL' => '/site/index.php/posts/add',
  1798. 'ORIG_PATH_TRANSLATED' => 'C:\\Inetpub\\wwwroot\\site\\index.php',
  1799. 'DOCUMENT_ROOT' => 'C:\\Inetpub\\wwwroot',
  1800. 'PHP_SELF' => '/site/index.php/posts/add',
  1801. 'argv' => ['/posts/add'],
  1802. 'argc' => 1
  1803. ],
  1804. ],
  1805. [
  1806. 'url' => 'posts/add',
  1807. 'base' => '/site/index.php',
  1808. 'webroot' => '/site/webroot/'
  1809. ]
  1810. ],
  1811. [
  1812. 'Apache - No rewrite, document root set to webroot, requesting path',
  1813. [
  1814. 'App' => [
  1815. 'base' => false,
  1816. 'baseUrl' => '/index.php',
  1817. 'dir' => 'TestApp',
  1818. 'webroot' => 'webroot'
  1819. ],
  1820. 'SERVER' => [
  1821. 'DOCUMENT_ROOT' => '/Library/WebServer/Documents/site/App/webroot',
  1822. 'SCRIPT_FILENAME' => '/Library/WebServer/Documents/site/App/webroot/index.php',
  1823. 'QUERY_STRING' => '',
  1824. 'REQUEST_URI' => '/index.php/posts/index',
  1825. 'SCRIPT_NAME' => '/index.php',
  1826. 'PATH_INFO' => '/posts/index',
  1827. 'PHP_SELF' => '/index.php/posts/index',
  1828. ],
  1829. ],
  1830. [
  1831. 'url' => 'posts/index',
  1832. 'base' => '/index.php',
  1833. 'webroot' => '/'
  1834. ],
  1835. ],
  1836. [
  1837. 'Apache - No rewrite, document root set to webroot, requesting root',
  1838. [
  1839. 'App' => [
  1840. 'base' => false,
  1841. 'baseUrl' => '/index.php',
  1842. 'dir' => 'TestApp',
  1843. 'webroot' => 'webroot'
  1844. ],
  1845. 'SERVER' => [
  1846. 'DOCUMENT_ROOT' => '/Library/WebServer/Documents/site/App/webroot',
  1847. 'SCRIPT_FILENAME' => '/Library/WebServer/Documents/site/App/webroot/index.php',
  1848. 'QUERY_STRING' => '',
  1849. 'REQUEST_URI' => '/index.php',
  1850. 'SCRIPT_NAME' => '/index.php',
  1851. 'PATH_INFO' => '',
  1852. 'PHP_SELF' => '/index.php',
  1853. ],
  1854. ],
  1855. [
  1856. 'url' => '',
  1857. 'base' => '/index.php',
  1858. 'webroot' => '/'
  1859. ],
  1860. ],
  1861. [
  1862. 'Apache - No rewrite, document root set above top level cake dir, requesting path',
  1863. [
  1864. 'App' => [
  1865. 'base' => false,
  1866. 'baseUrl' => '/site/index.php',
  1867. 'dir' => 'TestApp',
  1868. 'webroot' => 'webroot'
  1869. ],
  1870. 'SERVER' => [
  1871. 'SERVER_NAME' => 'localhost',
  1872. 'DOCUMENT_ROOT' => '/Library/WebServer/Documents',
  1873. 'SCRIPT_FILENAME' => '/Library/WebServer/Documents/site/index.php',
  1874. 'REQUEST_URI' => '/site/index.php/posts/index',
  1875. 'SCRIPT_NAME' => '/site/index.php',
  1876. 'PATH_INFO' => '/posts/index',
  1877. 'PHP_SELF' => '/site/index.php/posts/index',
  1878. ],
  1879. ],
  1880. [
  1881. 'url' => 'posts/index',
  1882. 'base' => '/site/index.php',
  1883. 'webroot' => '/site/webroot/',
  1884. ],
  1885. ],
  1886. [
  1887. 'Apache - No rewrite, document root set above top level cake dir, request root, no PATH_INFO',
  1888. [
  1889. 'App' => [
  1890. 'base' => false,
  1891. 'baseUrl' => '/site/index.php',
  1892. 'dir' => 'TestApp',
  1893. 'webroot' => 'webroot'
  1894. ],
  1895. 'SERVER' => [
  1896. 'SERVER_NAME' => 'localhost',
  1897. 'DOCUMENT_ROOT' => '/Library/WebServer/Documents',
  1898. 'SCRIPT_FILENAME' => '/Library/WebServer/Documents/site/index.php',
  1899. 'REQUEST_URI' => '/site/index.php/',
  1900. 'SCRIPT_NAME' => '/site/index.php',
  1901. 'PHP_SELF' => '/site/index.php/',
  1902. ],
  1903. ],
  1904. [
  1905. 'url' => '',
  1906. 'base' => '/site/index.php',
  1907. 'webroot' => '/site/webroot/',
  1908. ],
  1909. ],
  1910. [
  1911. 'Apache - No rewrite, document root set above top level cake dir, request path, with GET',
  1912. [
  1913. 'App' => [
  1914. 'base' => false,
  1915. 'baseUrl' => '/site/index.php',
  1916. 'dir' => 'TestApp',
  1917. 'webroot' => 'webroot'
  1918. ],
  1919. 'GET' => ['a' => 'b', 'c' => 'd'],
  1920. 'SERVER' => [
  1921. 'SERVER_NAME' => 'localhost',
  1922. 'DOCUMENT_ROOT' => '/Library/WebServer/Documents',
  1923. 'SCRIPT_FILENAME' => '/Library/WebServer/Documents/site/index.php',
  1924. 'REQUEST_URI' => '/site/index.php/posts/index?a=b&c=d',
  1925. 'SCRIPT_NAME' => '/site/index.php',
  1926. 'PATH_INFO' => '/posts/index',
  1927. 'PHP_SELF' => '/site/index.php/posts/index',
  1928. 'QUERY_STRING' => 'a=b&c=d'
  1929. ],
  1930. ],
  1931. [
  1932. 'urlParams' => ['a' => 'b', 'c' => 'd'],
  1933. 'url' => 'posts/index',
  1934. 'base' => '/site/index.php',
  1935. 'webroot' => '/site/webroot/',
  1936. ],
  1937. ],
  1938. [
  1939. 'Apache - w/rewrite, document root set above top level cake dir, request root, no PATH_INFO',
  1940. [
  1941. 'App' => [
  1942. 'base' => false,
  1943. 'baseUrl' => false,
  1944. 'dir' => 'TestApp',
  1945. 'webroot' => 'webroot'
  1946. ],
  1947. 'SERVER' => [
  1948. 'SERVER_NAME' => 'localhost',
  1949. 'DOCUMENT_ROOT' => '/Library/WebServer/Documents',
  1950. 'SCRIPT_FILENAME' => '/Library/WebServer/Documents/site/index.php',
  1951. 'REQUEST_URI' => '/site/',
  1952. 'SCRIPT_NAME' => '/site/webroot/index.php',
  1953. 'PHP_SELF' => '/site/webroot/index.php',
  1954. ],
  1955. ],
  1956. [
  1957. 'url' => '',
  1958. 'base' => '/site',
  1959. 'webroot' => '/site/',
  1960. ],
  1961. ],
  1962. [
  1963. 'Apache - w/rewrite, document root above top level cake dir, request root, no PATH_INFO/REQUEST_URI',
  1964. [
  1965. 'App' => [
  1966. 'base' => false,
  1967. 'baseUrl' => false,
  1968. 'dir' => 'TestApp',
  1969. 'webroot' => 'webroot'
  1970. ],
  1971. 'SERVER' => [
  1972. 'SERVER_NAME' => 'localhost',
  1973. 'DOCUMENT_ROOT' => '/Library/WebServer/Documents',
  1974. 'SCRIPT_FILENAME' => '/Library/WebServer/Documents/site/index.php',
  1975. 'SCRIPT_NAME' => '/site/webroot/index.php',
  1976. 'PHP_SELF' => '/site/webroot/index.php',
  1977. 'PATH_INFO' => null,
  1978. 'REQUEST_URI' => null,
  1979. ],
  1980. ],
  1981. [
  1982. 'url' => '',
  1983. 'base' => '/site',
  1984. 'webroot' => '/site/',
  1985. ],
  1986. ],
  1987. [
  1988. 'Apache - w/rewrite, document root set to webroot, request root, no PATH_INFO/REQUEST_URI',
  1989. [
  1990. 'App' => [
  1991. 'base' => false,
  1992. 'baseUrl' => false,
  1993. 'dir' => 'TestApp',
  1994. 'webroot' => 'webroot'
  1995. ],
  1996. 'SERVER' => [
  1997. 'SERVER_NAME' => 'localhost',
  1998. 'DOCUMENT_ROOT' => '/Library/WebServer/Documents/site/webroot',
  1999. 'SCRIPT_FILENAME' => '/Library/WebServer/Documents/site/webroot/index.php',
  2000. 'SCRIPT_NAME' => '/index.php',
  2001. 'PHP_SELF' => '/index.php',
  2002. 'PATH_INFO' => null,
  2003. 'REQUEST_URI' => null,
  2004. ],
  2005. ],
  2006. [
  2007. 'url' => '',
  2008. 'base' => '',
  2009. 'webroot' => '/',
  2010. ],
  2011. ],
  2012. [
  2013. 'Apache - w/rewrite, document root set above top level cake dir, request root, absolute REQUEST_URI',
  2014. [
  2015. 'App' => [
  2016. 'base' => false,
  2017. 'baseUrl' => false,
  2018. 'dir' => 'TestApp',
  2019. 'webroot' => 'webroot'
  2020. ],
  2021. 'SERVER' => [
  2022. 'SERVER_NAME' => 'localhost',
  2023. 'DOCUMENT_ROOT' => '/Library/WebServer/Documents',
  2024. 'SCRIPT_FILENAME' => '/Library/WebServer/Documents/site/index.php',
  2025. 'REQUEST_URI' => '/site/posts/index',
  2026. 'SCRIPT_NAME' => '/site/webroot/index.php',
  2027. 'PHP_SELF' => '/site/webroot/index.php',
  2028. ],
  2029. ],
  2030. [
  2031. 'url' => 'posts/index',
  2032. 'base' => '/site',
  2033. 'webroot' => '/site/',
  2034. ],
  2035. ],
  2036. [
  2037. 'Nginx - w/rewrite, document root set to webroot, request root, no PATH_INFO',
  2038. [
  2039. 'App' => [
  2040. 'base' => false,
  2041. 'baseUrl' => false,
  2042. 'dir' => 'TestApp',
  2043. 'webroot' => 'webroot'
  2044. ],
  2045. 'GET' => ['/posts/add' => ''],
  2046. 'SERVER' => [
  2047. 'SERVER_NAME' => 'localhost',
  2048. 'DOCUMENT_ROOT' => '/Library/WebServer/Documents/site/webroot',
  2049. 'SCRIPT_FILENAME' => '/Library/WebServer/Documents/site/webroot/index.php',
  2050. 'SCRIPT_NAME' => '/index.php',
  2051. 'QUERY_STRING' => '/posts/add&',
  2052. 'PHP_SELF' => '/index.php',
  2053. 'PATH_INFO' => null,
  2054. 'REQUEST_URI' => '/posts/add',
  2055. ],
  2056. ],
  2057. [
  2058. 'url' => 'posts/add',
  2059. 'base' => '',
  2060. 'webroot' => '/',
  2061. 'urlParams' => []
  2062. ],
  2063. ],
  2064. [
  2065. 'Nginx - w/rewrite, document root set above top level cake dir, request root, no PATH_INFO, base parameter set',
  2066. [
  2067. 'App' => [
  2068. 'base' => false,
  2069. 'baseUrl' => false,
  2070. 'dir' => 'app',
  2071. 'webroot' => 'webroot'
  2072. ],
  2073. 'GET' => ['/site/posts/add' => ''],
  2074. 'SERVER' => [
  2075. 'SERVER_NAME' => 'localhost',
  2076. 'DOCUMENT_ROOT' => '/Library/WebServer/Documents',
  2077. 'SCRIPT_FILENAME' => '/Library/WebServer/Documents/site/App/webroot/index.php',
  2078. 'SCRIPT_NAME' => '/site/app/webroot/index.php',
  2079. 'QUERY_STRING' => '/site/posts/add&',
  2080. 'PHP_SELF' => '/site/webroot/index.php',
  2081. 'PATH_INFO' => null,
  2082. 'REQUEST_URI' => '/site/posts/add',
  2083. ],
  2084. ],
  2085. [
  2086. 'url' => 'posts/add',
  2087. 'base' => '/site',
  2088. 'webroot' => '/site/',
  2089. 'urlParams' => []
  2090. ],
  2091. ],
  2092. ];
  2093. }
  2094. /**
  2095. * Test environment detection
  2096. *
  2097. * @dataProvider environmentGenerator
  2098. * @param $name
  2099. * @param $env
  2100. * @param $expected
  2101. * @return void
  2102. */
  2103. public function testEnvironmentDetection($name, $env, $expected)
  2104. {
  2105. $_GET = [];
  2106. $this->_loadEnvironment($env);
  2107. $request = ServerRequestFactory::fromGlobals();
  2108. $uri = $request->getUri();
  2109. $this->assertEquals($expected['url'], $request->url, "URL is incorrect");
  2110. $this->assertEquals('/' . $expected['url'], $uri->getPath(), 'Uri->getPath() is incorrect');
  2111. $this->assertEquals($expected['base'], $request->base, "base is incorrect");
  2112. $this->assertEquals($expected['base'], $request->getAttribute('base'), "base is incorrect");
  2113. $this->assertEquals($expected['webroot'], $request->webroot, "webroot error");
  2114. $this->assertEquals($expected['webroot'], $request->getAttribute('webroot'), "webroot is incorrect");
  2115. if (isset($expected['urlParams'])) {
  2116. $this->assertEquals($expected['urlParams'], $request->query, "GET param mismatch");
  2117. }
  2118. }
  2119. /**
  2120. * Test the query() method
  2121. *
  2122. * @return void
  2123. */
  2124. public function testQuery()
  2125. {
  2126. $array = [
  2127. 'query' => ['foo' => 'bar', 'zero' => '0']
  2128. ];
  2129. $request = new ServerRequest($array);
  2130. $this->assertSame('bar', $request->query('foo'));
  2131. $this->assertSame('0', $request->query('zero'));
  2132. $this->assertNull($request->query('imaginary'));
  2133. $this->assertSame($array['query'], $request->query());
  2134. }
  2135. /**
  2136. * Test the getQuery() method
  2137. *
  2138. * @return void
  2139. */
  2140. public function testGetQuery()
  2141. {
  2142. $array = [
  2143. 'query' => [
  2144. 'foo' => 'bar',
  2145. 'zero' => '0',
  2146. 'test' => [
  2147. 'foo', 'bar'
  2148. ]
  2149. ]
  2150. ];
  2151. $request = new ServerRequest($array);
  2152. $this->assertEquals([
  2153. 'foo' => 'bar',
  2154. 'zero' => '0',
  2155. 'test' => [
  2156. 'foo', 'bar'
  2157. ]
  2158. ], $request->getQuery());
  2159. $this->assertSame('bar', $request->getQuery('foo'));
  2160. $this->assertSame('0', $request->getQuery('zero'));
  2161. $this->assertNull($request->getQuery('imaginary'));
  2162. $this->assertSame('default', $request->getQuery('imaginary', 'default'));
  2163. $this->assertFalse($request->getQuery('imaginary', false));
  2164. $this->assertSame(['foo', 'bar'], $request->getQuery('test'));
  2165. $this->assertSame('bar', $request->getQuery('test.1'));
  2166. $this->assertNull($request->getQuery('test.2'));
  2167. $this->assertSame('default', $request->getQuery('test.2', 'default'));
  2168. }
  2169. /**
  2170. * Test getQueryParams
  2171. *
  2172. * @return void
  2173. */
  2174. public function testGetQueryParams()
  2175. {
  2176. $get = [
  2177. 'test' => ['foo', 'bar'],
  2178. 'key' => 'value'
  2179. ];
  2180. $request = new ServerRequest([
  2181. 'query' => $get
  2182. ]);
  2183. $this->assertSame($get, $request->getQueryParams());
  2184. }
  2185. /**
  2186. * Test withQueryParams and immutability
  2187. *
  2188. * @return void
  2189. */
  2190. public function testWithQueryParams()
  2191. {
  2192. $get = [
  2193. 'test' => ['foo', 'bar'],
  2194. 'key' => 'value'
  2195. ];
  2196. $request = new ServerRequest([
  2197. 'query' => $get
  2198. ]);
  2199. $new = $request->withQueryParams(['new' => 'data']);
  2200. $this->assertSame($get, $request->getQueryParams());
  2201. $this->assertSame(['new' => 'data'], $new->getQueryParams());
  2202. }
  2203. /**
  2204. * Test getServerParams
  2205. *
  2206. * @return void
  2207. */
  2208. public function testGetServerParams()
  2209. {
  2210. $vars = [
  2211. 'REQUEST_METHOD' => 'PUT',
  2212. 'HTTPS' => 'on',
  2213. ];
  2214. $request = new ServerRequest([
  2215. 'environment' => $vars
  2216. ]);
  2217. $expected = $vars + [
  2218. 'CONTENT_TYPE' => null,
  2219. 'HTTP_CONTENT_TYPE' => null,
  2220. 'ORIGINAL_REQUEST_METHOD' => 'PUT',
  2221. ];
  2222. $this->assertSame($expected, $request->getServerParams());
  2223. }
  2224. /**
  2225. * Test using param()
  2226. *
  2227. * @return void
  2228. */
  2229. public function testReadingParams()
  2230. {
  2231. $request = new ServerRequest();
  2232. $request->addParams([
  2233. 'controller' => 'posts',
  2234. 'admin' => true,
  2235. 'truthy' => 1,
  2236. 'zero' => '0',
  2237. ]);
  2238. $this->assertFalse($request->param('not_set'));
  2239. $this->assertTrue($request->param('admin'));
  2240. $this->assertSame(1, $request->param('truthy'));
  2241. $this->assertSame('posts', $request->param('controller'));
  2242. $this->assertSame('0', $request->param('zero'));
  2243. }
  2244. /**
  2245. * Test the data() method reading
  2246. *
  2247. * @return void
  2248. */
  2249. public function testGetData()
  2250. {
  2251. $post = [
  2252. 'Model' => [
  2253. 'field' => 'value'
  2254. ]
  2255. ];
  2256. $request = new ServerRequest(compact('post'));
  2257. $this->assertEquals($post['Model'], $request->data('Model'));
  2258. $this->assertEquals($post['Model'], $request->getData('Model'));
  2259. $this->assertEquals($post, $request->data());
  2260. $this->assertEquals($post, $request->getData());
  2261. $this->assertNull($request->data('Model.imaginary'));
  2262. $this->assertNull($request->getData('Model.imaginary'));
  2263. $this->assertSame('value', $request->getData('Model.field', 'default'));
  2264. $this->assertSame('default', $request->getData('Model.imaginary', 'default'));
  2265. }
  2266. /**
  2267. * Test that getData() doesn't fail on scalar data.
  2268. *
  2269. * @return void
  2270. */
  2271. public function testGetDataOnStringData()
  2272. {
  2273. $post = 'strange, but could happen';
  2274. $request = new ServerRequest(compact('post'));
  2275. $this->assertNull($request->getData('Model'));
  2276. $this->assertNull($request->getData('Model.field'));
  2277. }
  2278. /**
  2279. * Test writing with data()
  2280. *
  2281. * @return void
  2282. */
  2283. public function testDataWriting()
  2284. {
  2285. $_POST['data'] = [
  2286. 'Model' => [
  2287. 'field' => 'value'
  2288. ]
  2289. ];
  2290. $request = new ServerRequest();
  2291. $result = $request->data('Model.new_value', 'new value');
  2292. $this->assertSame($result, $request, 'Return was not $this');
  2293. $this->assertEquals('new value', $request->data['Model']['new_value']);
  2294. $request->data('Post.title', 'New post')->data('Comment.1.author', 'Mark');
  2295. $this->assertEquals('New post', $request->data['Post']['title']);
  2296. $this->assertEquals('Mark', $request->data['Comment']['1']['author']);
  2297. }
  2298. /**
  2299. * Test writing falsey values.
  2300. *
  2301. * @return void
  2302. */
  2303. public function testDataWritingFalsey()
  2304. {
  2305. $request = new ServerRequest();
  2306. $request->data('Post.null', null);
  2307. $this->assertNull($request->data['Post']['null']);
  2308. $request->data('Post.false', false);
  2309. $this->assertFalse($request->data['Post']['false']);
  2310. $request->data('Post.zero', 0);
  2311. $this->assertSame(0, $request->data['Post']['zero']);
  2312. $request->data('Post.empty', '');
  2313. $this->assertSame('', $request->data['Post']['empty']);
  2314. }
  2315. /**
  2316. * Test reading params
  2317. *
  2318. * @dataProvider paramReadingDataProvider
  2319. */
  2320. public function testGetParam($toRead, $expected)
  2321. {
  2322. $request = new ServerRequest('/');
  2323. $request->addParams([
  2324. 'action' => 'index',
  2325. 'foo' => 'bar',
  2326. 'baz' => [
  2327. 'a' => [
  2328. 'b' => 'c',
  2329. ],
  2330. ],
  2331. 'admin' => true,
  2332. 'truthy' => 1,
  2333. 'zero' => '0',
  2334. ]);
  2335. $this->assertSame($expected, $request->param($toRead));
  2336. $this->assertSame($expected, $request->getParam($toRead));
  2337. }
  2338. /**
  2339. * Test getParam returning a default value.
  2340. *
  2341. * @return void
  2342. */
  2343. public function testGetParamDefault()
  2344. {
  2345. $request = new ServerRequest([
  2346. 'params' => [
  2347. 'controller' => 'Articles',
  2348. 'null' => null,
  2349. ]
  2350. ]);
  2351. $this->assertSame('Articles', $request->getParam('controller', 'default'));
  2352. $this->assertSame('default', $request->getParam('null', 'default'));
  2353. $this->assertNull($request->getParam('unset', null));
  2354. $this->assertFalse($request->getParam('unset'));
  2355. }
  2356. /**
  2357. * Data provider for testing reading values with ServerRequestFactory::param()
  2358. *
  2359. * @return array
  2360. */
  2361. public function paramReadingDataProvider()
  2362. {
  2363. return [
  2364. [
  2365. 'action',
  2366. 'index',
  2367. ],
  2368. [
  2369. 'baz',
  2370. [
  2371. 'a' => [
  2372. 'b' => 'c',
  2373. ],
  2374. ],
  2375. ],
  2376. [
  2377. 'baz.a.b',
  2378. 'c',
  2379. ],
  2380. [
  2381. 'does_not_exist',
  2382. false,
  2383. ],
  2384. [
  2385. 'admin',
  2386. true,
  2387. ],
  2388. [
  2389. 'truthy',
  2390. 1,
  2391. ],
  2392. [
  2393. 'zero',
  2394. '0',
  2395. ],
  2396. ];
  2397. }
  2398. /**
  2399. * test writing request params with param()
  2400. *
  2401. * @return void
  2402. */
  2403. public function testParamWriting()
  2404. {
  2405. $request = new ServerRequest('/');
  2406. $request->addParams([
  2407. 'action' => 'index',
  2408. ]);
  2409. $this->assertInstanceOf('Cake\Http\ServerRequest', $request->param('some', 'thing'), 'Method has not returned $this');
  2410. $request->param('Post.null', null);
  2411. $this->assertNull($request->params['Post']['null']);
  2412. $request->param('Post.false', false);
  2413. $this->assertFalse($request->params['Post']['false']);
  2414. $request->param('Post.zero', 0);
  2415. $this->assertSame(0, $request->params['Post']['zero']);
  2416. $request->param('Post.empty', '');
  2417. $this->assertSame('', $request->params['Post']['empty']);
  2418. $this->assertSame('index', $request->action);
  2419. $request->param('action', 'edit');
  2420. $this->assertSame('edit', $request->action);
  2421. }
  2422. /**
  2423. * Test accept language
  2424. *
  2425. * @return void
  2426. */
  2427. public function testAcceptLanguage()
  2428. {
  2429. $request = new ServerRequest();
  2430. // Weird language
  2431. $request->env('HTTP_ACCEPT_LANGUAGE', 'inexistent,en-ca');
  2432. $result = $request->acceptLanguage();
  2433. $this->assertEquals(['inexistent', 'en-ca'], $result, 'Languages do not match');
  2434. // No qualifier
  2435. $request->env('HTTP_ACCEPT_LANGUAGE', 'es_mx,en_ca');
  2436. $result = $request->acceptLanguage();
  2437. $this->assertEquals(['es-mx', 'en-ca'], $result, 'Languages do not match');
  2438. // With qualifier
  2439. $request->env('HTTP_ACCEPT_LANGUAGE', 'en-US,en;q=0.8,pt-BR;q=0.6,pt;q=0.4');
  2440. $result = $request->acceptLanguage();
  2441. $this->assertEquals(['en-us', 'en', 'pt-br', 'pt'], $result, 'Languages do not match');
  2442. // With spaces
  2443. $request->env('HTTP_ACCEPT_LANGUAGE', 'da, en-gb;q=0.8, en;q=0.7');
  2444. $result = $request->acceptLanguage();
  2445. $this->assertEquals(['da', 'en-gb', 'en'], $result, 'Languages do not match');
  2446. // Checking if requested
  2447. $request->env('HTTP_ACCEPT_LANGUAGE', 'es_mx,en_ca');
  2448. $result = $request->acceptLanguage();
  2449. $result = $request->acceptLanguage('en-ca');
  2450. $this->assertTrue($result);
  2451. $result = $request->acceptLanguage('en-CA');
  2452. $this->assertTrue($result);
  2453. $result = $request->acceptLanguage('en-us');
  2454. $this->assertFalse($result);
  2455. $result = $request->acceptLanguage('en-US');
  2456. $this->assertFalse($result);
  2457. }
  2458. /**
  2459. * Test the here() method
  2460. *
  2461. * @return void
  2462. */
  2463. public function testHere()
  2464. {
  2465. Configure::write('App.base', '/base_path');
  2466. $q = ['test' => 'value'];
  2467. $request = new ServerRequest([
  2468. 'query' => $q,
  2469. 'url' => '/posts/add/1/value',
  2470. 'base' => '/base_path'
  2471. ]);
  2472. $result = $request->here();
  2473. $this->assertEquals('/base_path/posts/add/1/value?test=value', $result);
  2474. $result = $request->here(false);
  2475. $this->assertEquals('/posts/add/1/value?test=value', $result);
  2476. $request = new ServerRequest([
  2477. 'url' => '/posts/base_path/1/value',
  2478. 'query' => ['test' => 'value'],
  2479. 'base' => '/base_path'
  2480. ]);
  2481. $result = $request->here();
  2482. $this->assertEquals('/base_path/posts/base_path/1/value?test=value', $result);
  2483. $result = $request->here(false);
  2484. $this->assertEquals('/posts/base_path/1/value?test=value', $result);
  2485. }
  2486. /**
  2487. * Test the here() with space in URL
  2488. *
  2489. * @return void
  2490. */
  2491. public function testHereWithSpaceInUrl()
  2492. {
  2493. Configure::write('App.base', '');
  2494. $_GET = ['/admin/settings/settings/prefix/Access_Control' => ''];
  2495. $request = new ServerRequest('/admin/settings/settings/prefix/Access%20Control');
  2496. $result = $request->here();
  2497. $this->assertEquals('/admin/settings/settings/prefix/Access%20Control', $result);
  2498. }
  2499. /**
  2500. * Test the input() method.
  2501. *
  2502. * @return void
  2503. */
  2504. public function testSetInput()
  2505. {
  2506. $request = new ServerRequest();
  2507. $request->setInput('I came from setInput');
  2508. $result = $request->input();
  2509. $this->assertEquals('I came from setInput', $result);
  2510. }
  2511. /**
  2512. * Test the input() method.
  2513. *
  2514. * @return void
  2515. */
  2516. public function testInput()
  2517. {
  2518. $request = new ServerRequest([
  2519. 'input' => 'I came from stdin'
  2520. ]);
  2521. $result = $request->input();
  2522. $this->assertEquals('I came from stdin', $result);
  2523. }
  2524. /**
  2525. * Test input() decoding.
  2526. *
  2527. * @return void
  2528. */
  2529. public function testInputDecode()
  2530. {
  2531. $request = new ServerRequest([
  2532. 'input' => '{"name":"value"}'
  2533. ]);
  2534. $result = $request->input('json_decode');
  2535. $this->assertEquals(['name' => 'value'], (array)$result);
  2536. }
  2537. /**
  2538. * Test input() decoding with additional arguments.
  2539. *
  2540. * @return void
  2541. */
  2542. public function testInputDecodeExtraParams()
  2543. {
  2544. $xml = <<<XML
  2545. <?xml version="1.0" encoding="utf-8"?>
  2546. <post>
  2547. <title id="title">Test</title>
  2548. </post>
  2549. XML;
  2550. $request = new ServerRequest([
  2551. 'input' => $xml
  2552. ]);
  2553. $result = $request->input('Cake\Utility\Xml::build', ['return' => 'domdocument']);
  2554. $this->assertInstanceOf('DOMDocument', $result);
  2555. $this->assertEquals(
  2556. 'Test',
  2557. $result->getElementsByTagName('title')->item(0)->childNodes->item(0)->wholeText
  2558. );
  2559. }
  2560. /**
  2561. * Test getBody
  2562. *
  2563. * @return void
  2564. */
  2565. public function testGetBody()
  2566. {
  2567. $request = new ServerRequest([
  2568. 'input' => 'key=val&some=data'
  2569. ]);
  2570. $result = $request->getBody();
  2571. $this->assertInstanceOf('Psr\Http\Message\StreamInterface', $result);
  2572. $this->assertEquals('key=val&some=data', $result->getContents());
  2573. }
  2574. /**
  2575. * Test withBody
  2576. *
  2577. * @return void
  2578. */
  2579. public function testWithBody()
  2580. {
  2581. $request = new ServerRequest([
  2582. 'input' => 'key=val&some=data'
  2583. ]);
  2584. $body = $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock();
  2585. $new = $request->withBody($body);
  2586. $this->assertNotSame($new, $request);
  2587. $this->assertNotSame($body, $request->getBody());
  2588. $this->assertSame($body, $new->getBody());
  2589. }
  2590. /**
  2591. * Test getUri
  2592. *
  2593. * @return void
  2594. */
  2595. public function testGetUri()
  2596. {
  2597. $request = new ServerRequest(['url' => 'articles/view/3']);
  2598. $this->assertEquals('articles/view/3', $request->url);
  2599. $result = $request->getUri();
  2600. $this->assertInstanceOf('Psr\Http\Message\UriInterface', $result);
  2601. $this->assertEquals('/articles/view/3', $result->getPath());
  2602. }
  2603. /**
  2604. * Test withUri
  2605. *
  2606. * @return void
  2607. */
  2608. public function testWithUri()
  2609. {
  2610. $request = new ServerRequest([
  2611. 'environment' => [
  2612. 'HTTP_HOST' => 'example.com',
  2613. ],
  2614. 'url' => 'articles/view/3'
  2615. ]);
  2616. $uri = $this->getMockBuilder('Psr\Http\Message\UriInterface')->getMock();
  2617. $new = $request->withUri($uri);
  2618. $this->assertNotSame($new, $request);
  2619. $this->assertNotSame($uri, $request->getUri());
  2620. $this->assertSame($uri, $new->getUri());
  2621. $this->assertSame('articles/view/3', $new->url);
  2622. $this->assertSame('articles/view/3', $request->url);
  2623. $this->assertSame('example.com', $new->getHeaderLine('Host'));
  2624. }
  2625. /**
  2626. * Test withUri() and preserveHost
  2627. *
  2628. * @return void
  2629. */
  2630. public function testWithUriPreserveHost()
  2631. {
  2632. $request = new ServerRequest([
  2633. 'environment' => [
  2634. 'HTTP_HOST' => 'localhost'
  2635. ],
  2636. 'url' => 'articles/view/3'
  2637. ]);
  2638. $uri = new Uri();
  2639. $uri = $uri->withHost('example.com')
  2640. ->withPort(123)
  2641. ->withPath('articles/view/3');
  2642. $new = $request->withUri($uri, false);
  2643. $this->assertNotSame($new, $request);
  2644. $this->assertSame('example.com:123', $new->getHeaderLine('Host'));
  2645. }
  2646. /**
  2647. * Test withUri() and preserveHost missing the host header
  2648. *
  2649. * @return void
  2650. */
  2651. public function testWithUriPreserveHostNoHostHeader()
  2652. {
  2653. $request = new ServerRequest([
  2654. 'url' => 'articles/view/3'
  2655. ]);
  2656. $uri = new Uri();
  2657. $uri = $uri->withHost('example.com')
  2658. ->withPort(123)
  2659. ->withPath('articles/view/3');
  2660. $new = $request->withUri($uri, false);
  2661. $this->assertSame('example.com:123', $new->getHeaderLine('Host'));
  2662. }
  2663. /**
  2664. * Test is('requested') and isRequested()
  2665. *
  2666. * @return void
  2667. */
  2668. public function testIsRequested()
  2669. {
  2670. $request = new ServerRequest();
  2671. $request->addParams([
  2672. 'controller' => 'posts',
  2673. 'action' => 'index',
  2674. 'plugin' => null,
  2675. 'requested' => 1
  2676. ]);
  2677. $this->assertTrue($request->is('requested'));
  2678. $this->assertTrue($request->isRequested());
  2679. $request = new ServerRequest();
  2680. $request->addParams([
  2681. 'controller' => 'posts',
  2682. 'action' => 'index',
  2683. 'plugin' => null,
  2684. ]);
  2685. $this->assertFalse($request->is('requested'));
  2686. $this->assertFalse($request->isRequested());
  2687. }
  2688. /**
  2689. * Test the cookie() method.
  2690. *
  2691. * @return void
  2692. */
  2693. public function testGetCookie()
  2694. {
  2695. $request = new ServerRequest([
  2696. 'cookies' => [
  2697. 'testing' => 'A value in the cookie',
  2698. 'user' => [
  2699. 'remember' => '1'
  2700. ]
  2701. ]
  2702. ]);
  2703. $this->assertEquals('A value in the cookie', $request->cookie('testing'));
  2704. $this->assertEquals('A value in the cookie', $request->getCookie('testing'));
  2705. $this->assertNull($request->cookie('not there'));
  2706. $this->assertNull($request->getCookie('not there'));
  2707. $this->assertSame('default', $request->getCookie('not there', 'default'));
  2708. $this->assertSame('1', $request->getCookie('user.remember'));
  2709. $this->assertSame('1', $request->getCookie('user.remember', 'default'));
  2710. $this->assertSame('default', $request->getCookie('user.not there', 'default'));
  2711. }
  2712. /**
  2713. * Test getCookieParams()
  2714. *
  2715. * @return void
  2716. */
  2717. public function testGetCookieParams()
  2718. {
  2719. $cookies = [
  2720. 'testing' => 'A value in the cookie'
  2721. ];
  2722. $request = new ServerRequest(['cookies' => $cookies]);
  2723. $this->assertSame($cookies, $request->getCookieParams());
  2724. }
  2725. /**
  2726. * Test withCookieParams()
  2727. *
  2728. * @return void
  2729. */
  2730. public function testWithCookieParams()
  2731. {
  2732. $cookies = [
  2733. 'testing' => 'A value in the cookie'
  2734. ];
  2735. $request = new ServerRequest(['cookies' => $cookies]);
  2736. $new = $request->withCookieParams(['remember_me' => 1]);
  2737. $this->assertNotSame($new, $request);
  2738. $this->assertSame($cookies, $request->getCookieParams());
  2739. $this->assertSame(['remember_me' => 1], $new->getCookieParams());
  2740. }
  2741. /**
  2742. * Test getting a cookie collection from a request.
  2743. *
  2744. * @return void
  2745. */
  2746. public function testGetCookieCollection()
  2747. {
  2748. $cookies = [
  2749. 'remember_me' => '1',
  2750. 'color' => 'blue'
  2751. ];
  2752. $request = new ServerRequest(['cookies' => $cookies]);
  2753. $cookies = $request->getCookieCollection();
  2754. $this->assertInstanceOf(CookieCollection::class, $cookies);
  2755. $this->assertCount(2, $cookies);
  2756. $this->assertSame('1', $cookies->get('remember_me')->getValue());
  2757. $this->assertSame('blue', $cookies->get('color')->getValue());
  2758. }
  2759. /**
  2760. * Test replacing cookies from a collection
  2761. *
  2762. * @return void
  2763. */
  2764. public function testWithCookieCollection()
  2765. {
  2766. $cookies = new CookieCollection([new Cookie('remember_me', 1), new Cookie('color', 'red')]);
  2767. $request = new ServerRequest(['cookies' => ['bad' => 'goaway']]);
  2768. $new = $request->withCookieCollection($cookies);
  2769. $this->assertNotSame($new, $request, 'Should clone');
  2770. $this->assertSame(['bad' => 'goaway'], $request->getCookieParams());
  2771. $this->assertSame(['remember_me' => 1, 'color' => 'red'], $new->getCookieParams());
  2772. $cookies = $new->getCookieCollection();
  2773. $this->assertCount(2, $cookies);
  2774. $this->assertSame('red', $cookies->get('color')->getValue());
  2775. }
  2776. /**
  2777. * TestAllowMethod
  2778. *
  2779. * @return void
  2780. */
  2781. public function testAllowMethod()
  2782. {
  2783. $request = new ServerRequest(['environment' => [
  2784. 'url' => '/posts/edit/1',
  2785. 'REQUEST_METHOD' => 'PUT'
  2786. ]]);
  2787. $this->assertTrue($request->allowMethod('put'));
  2788. $request->env('REQUEST_METHOD', 'DELETE');
  2789. $this->assertTrue($request->allowMethod(['post', 'delete']));
  2790. }
  2791. /**
  2792. * Test allowMethod throwing exception
  2793. *
  2794. * @return void
  2795. */
  2796. public function testAllowMethodException()
  2797. {
  2798. $request = new ServerRequest([
  2799. 'url' => '/posts/edit/1',
  2800. 'environment' => ['REQUEST_METHOD' => 'PUT']
  2801. ]);
  2802. try {
  2803. $request->allowMethod(['POST', 'DELETE']);
  2804. $this->fail('An expected exception has not been raised.');
  2805. } catch (MethodNotAllowedException $e) {
  2806. $this->assertEquals(['Allow' => 'POST, DELETE'], $e->responseHeader());
  2807. }
  2808. $this->expectException(MethodNotAllowedException::class);
  2809. $request->allowMethod('POST');
  2810. }
  2811. /**
  2812. * Tests getting the sessions from the request
  2813. *
  2814. * @return void
  2815. */
  2816. public function testSession()
  2817. {
  2818. $session = new Session;
  2819. $request = new ServerRequest(['session' => $session]);
  2820. $this->assertSame($session, $request->session());
  2821. $request = ServerRequestFactory::fromGlobals();
  2822. $this->assertEquals($session, $request->session());
  2823. }
  2824. /**
  2825. * Tests getting the session from the request
  2826. *
  2827. * @return void
  2828. */
  2829. public function testGetSession()
  2830. {
  2831. $session = new Session;
  2832. $request = new ServerRequest(['session' => $session]);
  2833. $this->assertSame($session, $request->getSession());
  2834. $request = ServerRequestFactory::fromGlobals();
  2835. $this->assertEquals($session, $request->getSession());
  2836. }
  2837. /**
  2838. * Tests setting the session to the request
  2839. *
  2840. * @return void
  2841. */
  2842. public function testWithtSession()
  2843. {
  2844. $session = new Session;
  2845. $request = new ServerRequest();
  2846. $newRequest = $request->withSession($session);
  2847. $this->assertNotSame($newRequest, $request);
  2848. $this->assertSame($session, $newRequest->getSession());
  2849. }
  2850. /**
  2851. * Test the content type method.
  2852. *
  2853. * @return void
  2854. */
  2855. public function testContentType()
  2856. {
  2857. $_SERVER['HTTP_CONTENT_TYPE'] = 'application/json';
  2858. $request = ServerRequestFactory::fromGlobals();
  2859. $this->assertEquals('application/json', $request->contentType());
  2860. $_SERVER['CONTENT_TYPE'] = 'application/xml';
  2861. $request = ServerRequestFactory::fromGlobals();
  2862. $this->assertEquals('application/xml', $request->contentType(), 'prefer non http header.');
  2863. }
  2864. /**
  2865. * Tests that overriding the method to GET will clean all request
  2866. * data, to better simulate a GET request.
  2867. *
  2868. * @return void
  2869. */
  2870. public function testMethodOverrideEmptyData()
  2871. {
  2872. $post = ['_method' => 'GET', 'foo' => 'bar'];
  2873. $request = new ServerRequest([
  2874. 'post' => $post,
  2875. 'environment' => ['REQUEST_METHOD' => 'POST']
  2876. ]);
  2877. $this->assertEmpty($request->data);
  2878. $post = ['_method' => 'GET', 'foo' => 'bar'];
  2879. $request = new ServerRequest([
  2880. 'post' => ['foo' => 'bar'],
  2881. 'environment' => [
  2882. 'REQUEST_METHOD' => 'POST',
  2883. 'HTTP_X_HTTP_METHOD_OVERRIDE' => 'GET'
  2884. ]
  2885. ]);
  2886. $this->assertEmpty($request->data);
  2887. }
  2888. /**
  2889. * Test updating params in a psr7 fashion.
  2890. *
  2891. * @return void
  2892. */
  2893. public function testWithParam()
  2894. {
  2895. $request = new ServerRequest([
  2896. 'params' => ['controller' => 'Articles']
  2897. ]);
  2898. $result = $request->withParam('action', 'view');
  2899. $this->assertNotSame($result, $request, 'New instance should be made');
  2900. $this->assertFalse($request->param('action'), 'No side-effect on original');
  2901. $this->assertSame('view', $result->param('action'));
  2902. $result = $request->withParam('action', 'index')
  2903. ->withParam('plugin', 'DebugKit')
  2904. ->withParam('prefix', 'Admin');
  2905. $this->assertNotSame($result, $request, 'New instance should be made');
  2906. $this->assertFalse($request->param('action'), 'No side-effect on original');
  2907. $this->assertSame('index', $result->param('action'));
  2908. $this->assertSame('DebugKit', $result->param('plugin'));
  2909. $this->assertSame('Admin', $result->param('prefix'));
  2910. }
  2911. /**
  2912. * Test getting the parsed body parameters.
  2913. *
  2914. * @return void
  2915. */
  2916. public function testGetParsedBody()
  2917. {
  2918. $data = ['title' => 'First', 'body' => 'Best Article!'];
  2919. $request = new ServerRequest(['post' => $data]);
  2920. $this->assertSame($data, $request->getParsedBody());
  2921. $request = new ServerRequest();
  2922. $this->assertSame([], $request->getParsedBody());
  2923. }
  2924. /**
  2925. * Test replacing the parsed body parameters.
  2926. *
  2927. * @return void
  2928. */
  2929. public function testWithParsedBody()
  2930. {
  2931. $data = ['title' => 'First', 'body' => 'Best Article!'];
  2932. $request = new ServerRequest([]);
  2933. $new = $request->withParsedBody($data);
  2934. $this->assertNotSame($request, $new);
  2935. $this->assertSame([], $request->getParsedBody());
  2936. $this->assertSame($data, $new->getParsedBody());
  2937. }
  2938. /**
  2939. * Test updating POST data in a psr7 fashion.
  2940. *
  2941. * @return void
  2942. */
  2943. public function testWithData()
  2944. {
  2945. $request = new ServerRequest([
  2946. 'post' => [
  2947. 'Model' => [
  2948. 'field' => 'value'
  2949. ]
  2950. ]
  2951. ]);
  2952. $result = $request->withData('Model.new_value', 'new value');
  2953. $this->assertNull($request->data('Model.new_value'), 'Original request should not change.');
  2954. $this->assertNotSame($result, $request);
  2955. $this->assertEquals('new value', $result->data('Model.new_value'));
  2956. $this->assertEquals('new value', $result->data['Model']['new_value']);
  2957. $this->assertEquals('value', $result->data('Model.field'));
  2958. }
  2959. /**
  2960. * Test updating POST data when keys don't exist
  2961. *
  2962. * @return void
  2963. */
  2964. public function testWithDataMissingIntermediaryKeys()
  2965. {
  2966. $request = new ServerRequest([
  2967. 'post' => [
  2968. 'Model' => [
  2969. 'field' => 'value'
  2970. ]
  2971. ]
  2972. ]);
  2973. $result = $request->withData('Model.field.new_value', 'new value');
  2974. $this->assertEquals(
  2975. 'new value',
  2976. $result->data('Model.field.new_value')
  2977. );
  2978. $this->assertEquals(
  2979. 'new value',
  2980. $result->data['Model']['field']['new_value']
  2981. );
  2982. }
  2983. /**
  2984. * Test updating POST data with falsey values
  2985. *
  2986. * @return void
  2987. */
  2988. public function testWithDataFalseyValues()
  2989. {
  2990. $request = new ServerRequest([
  2991. 'post' => []
  2992. ]);
  2993. $result = $request->withData('false', false)
  2994. ->withData('null', null)
  2995. ->withData('empty_string', '')
  2996. ->withData('zero', 0)
  2997. ->withData('zero_string', '0');
  2998. $expected = [
  2999. 'false' => false,
  3000. 'null' => null,
  3001. 'empty_string' => '',
  3002. 'zero' => 0,
  3003. 'zero_string' => '0'
  3004. ];
  3005. $this->assertSame($expected, $result->data());
  3006. }
  3007. /**
  3008. * Test setting attributes.
  3009. *
  3010. * @return void
  3011. */
  3012. public function testWithAttribute()
  3013. {
  3014. $request = new ServerRequest([]);
  3015. $this->assertNull($request->getAttribute('key'));
  3016. $this->assertSame('default', $request->getAttribute('key', 'default'));
  3017. $new = $request->withAttribute('key', 'value');
  3018. $this->assertNotEquals($new, $request, 'Should be different');
  3019. $this->assertNull($request->getAttribute('key'), 'Old instance not modified');
  3020. $this->assertSame('value', $new->getAttribute('key'));
  3021. $update = $new->withAttribute('key', ['complex']);
  3022. $this->assertNotEquals($update, $new, 'Should be different');
  3023. $this->assertSame(['complex'], $update->getAttribute('key'));
  3024. }
  3025. /**
  3026. * Test that withAttribute() can modify the deprecated public properties.
  3027. *
  3028. * @return void
  3029. */
  3030. public function testWithAttributesCompatibility()
  3031. {
  3032. $request = new ServerRequest([
  3033. 'params' => [
  3034. 'controller' => 'Articles',
  3035. 'action' => 'index'
  3036. ],
  3037. 'base' => '/cakeapp',
  3038. 'webroot' => '/cakeapp/'
  3039. ]);
  3040. $new = $request->withAttribute('base', '/replace')
  3041. ->withAttribute('webroot', '/replace/')
  3042. ->withAttribute('params', ['controller' => 'Tags']);
  3043. // Original request should not change.
  3044. $this->assertSame('/cakeapp', $request->getAttribute('base'));
  3045. $this->assertSame('/cakeapp/', $request->getAttribute('webroot'));
  3046. $this->assertSame(
  3047. ['controller' => 'Articles', 'action' => 'index'],
  3048. $request->getAttribute('params')
  3049. );
  3050. $this->assertSame('/replace', $new->getAttribute('base'));
  3051. $this->assertSame('/replace', $new->base);
  3052. $this->assertSame('/replace/', $new->getAttribute('webroot'));
  3053. $this->assertSame('/replace/', $new->webroot);
  3054. $this->assertSame(['controller' => 'Tags'], $new->getAttribute('params'));
  3055. $this->assertSame(['controller' => 'Tags'], $new->params);
  3056. }
  3057. /**
  3058. * Test that getAttribute() can read deprecated public properties.
  3059. *
  3060. * @dataProvider emulatedPropertyProvider
  3061. * @return void
  3062. */
  3063. public function testGetAttributesCompatibility($prop)
  3064. {
  3065. $request = new ServerRequest([
  3066. 'params' => [
  3067. 'controller' => 'Articles',
  3068. 'action' => 'index'
  3069. ],
  3070. 'base' => '/cakeapp',
  3071. 'webroot' => '/cakeapp/'
  3072. ]);
  3073. if ($prop === 'session') {
  3074. $this->assertSame($request->session(), $request->getAttribute($prop));
  3075. } else {
  3076. $this->assertSame($request->{$prop}, $request->getAttribute($prop));
  3077. }
  3078. }
  3079. /**
  3080. * Test getting all attributes.
  3081. *
  3082. * @return void
  3083. */
  3084. public function testGetAttributes()
  3085. {
  3086. $request = new ServerRequest([]);
  3087. $new = $request->withAttribute('key', 'value')
  3088. ->withAttribute('nully', null)
  3089. ->withAttribute('falsey', false);
  3090. $this->assertFalse($new->getAttribute('falsey'));
  3091. $this->assertNull($new->getAttribute('nully'));
  3092. $expected = [
  3093. 'key' => 'value',
  3094. 'nully' => null,
  3095. 'falsey' => false,
  3096. 'params' => [
  3097. 'plugin' => null,
  3098. 'controller' => null,
  3099. 'action' => null,
  3100. '_ext' => null,
  3101. 'pass' => [],
  3102. ],
  3103. 'webroot' => '',
  3104. 'base' => ''
  3105. ];
  3106. $this->assertEquals($expected, $new->getAttributes());
  3107. }
  3108. /**
  3109. * Test unsetting attributes.
  3110. *
  3111. * @return void
  3112. */
  3113. public function testWithoutAttribute()
  3114. {
  3115. $request = new ServerRequest([]);
  3116. $new = $request->withAttribute('key', 'value');
  3117. $update = $request->withoutAttribute('key');
  3118. $this->assertNotEquals($update, $new, 'Should be different');
  3119. $this->assertNull($update->getAttribute('key'));
  3120. }
  3121. /**
  3122. * Test that withoutAttribute() cannot remove deprecated public properties.
  3123. *
  3124. * @dataProvider emulatedPropertyProvider
  3125. * @expectedException InvalidArgumentException
  3126. * @return void
  3127. */
  3128. public function testWithoutAttributesDenyEmulatedProperties($prop)
  3129. {
  3130. $request = new ServerRequest([]);
  3131. $request->withoutAttribute($prop);
  3132. }
  3133. /**
  3134. * Test the requestTarget methods.
  3135. *
  3136. * @return void
  3137. */
  3138. public function testWithRequestTarget()
  3139. {
  3140. $request = new ServerRequest([
  3141. 'environment' => [
  3142. 'REQUEST_URI' => '/articles/view/1',
  3143. 'QUERY_STRING' => 'comments=1&open=0'
  3144. ],
  3145. 'base' => '/basedir'
  3146. ]);
  3147. $this->assertEquals(
  3148. '/articles/view/1?comments=1&open=0',
  3149. $request->getRequestTarget(),
  3150. 'Should not include basedir.'
  3151. );
  3152. $new = $request->withRequestTarget('/articles/view/3');
  3153. $this->assertNotSame($new, $request);
  3154. $this->assertEquals(
  3155. '/articles/view/1?comments=1&open=0',
  3156. $request->getRequestTarget(),
  3157. 'should be unchanged.'
  3158. );
  3159. $this->assertEquals('/articles/view/3', $new->getRequestTarget(), 'reflects method call');
  3160. }
  3161. /**
  3162. * Data provider for emulated property tests.
  3163. *
  3164. * @return array
  3165. */
  3166. public function emulatedPropertyProvider()
  3167. {
  3168. return [
  3169. ['params'],
  3170. ['base'],
  3171. ['webroot'],
  3172. ['session']
  3173. ];
  3174. }
  3175. /**
  3176. * loadEnvironment method
  3177. *
  3178. * @param array $env
  3179. * @return void
  3180. */
  3181. protected function _loadEnvironment($env)
  3182. {
  3183. if (isset($env['App'])) {
  3184. Configure::write('App', $env['App']);
  3185. }
  3186. if (isset($env['GET'])) {
  3187. foreach ($env['GET'] as $key => $val) {
  3188. $_GET[$key] = $val;
  3189. }
  3190. }
  3191. if (isset($env['POST'])) {
  3192. foreach ($env['POST'] as $key => $val) {
  3193. $_POST[$key] = $val;
  3194. }
  3195. }
  3196. if (isset($env['SERVER'])) {
  3197. foreach ($env['SERVER'] as $key => $val) {
  3198. $_SERVER[$key] = $val;
  3199. }
  3200. }
  3201. }
  3202. }