ResponseTest.php 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://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. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 2.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Http;
  16. include_once CORE_TEST_CASES . DS . 'Http' . DS . 'server_mocks.php';
  17. use Cake\Http\Cookie\Cookie;
  18. use Cake\Http\Cookie\CookieCollection;
  19. use Cake\Http\CorsBuilder;
  20. use Cake\Http\Exception\NotFoundException;
  21. use Cake\Http\Response;
  22. use Cake\Http\ServerRequest;
  23. use Cake\TestSuite\TestCase;
  24. use Zend\Diactoros\Stream;
  25. /**
  26. * ResponseTest
  27. */
  28. class ResponseTest extends TestCase
  29. {
  30. /**
  31. * SERVER variable backup.
  32. *
  33. * @var array
  34. */
  35. protected $server = [];
  36. /**
  37. * setup
  38. *
  39. * @return void
  40. */
  41. public function setUp()
  42. {
  43. parent::setUp();
  44. $this->server = $_SERVER;
  45. }
  46. /**
  47. * teardown
  48. *
  49. * @return void
  50. */
  51. public function tearDown()
  52. {
  53. parent::tearDown();
  54. $_SERVER = $this->server;
  55. unset($GLOBALS['mockedHeadersSent']);
  56. }
  57. /**
  58. * Tests the request object constructor
  59. *
  60. * @return void
  61. */
  62. public function testConstruct()
  63. {
  64. $response = new Response();
  65. $this->assertSame('', (string)$response->getBody());
  66. $this->assertEquals('UTF-8', $response->getCharset());
  67. $this->assertEquals('text/html', $response->getType());
  68. $this->assertEquals('text/html; charset=UTF-8', $response->getHeaderLine('Content-Type'));
  69. $this->assertEquals(200, $response->getStatusCode());
  70. $options = [
  71. 'body' => 'This is the body',
  72. 'charset' => 'my-custom-charset',
  73. 'type' => 'mp3',
  74. 'status' => '203'
  75. ];
  76. $response = new Response($options);
  77. $this->assertEquals('This is the body', (string)$response->getBody());
  78. $this->assertEquals('my-custom-charset', $response->getCharset());
  79. $this->assertEquals('audio/mpeg', $response->getType());
  80. $this->assertEquals('audio/mpeg', $response->getHeaderLine('Content-Type'));
  81. $this->assertEquals(203, $response->getStatusCode());
  82. }
  83. /**
  84. * Test statusCodes constructor argument.
  85. *
  86. * @group deprecated
  87. * @return void
  88. */
  89. public function testConstructCustomCodes()
  90. {
  91. $this->deprecated(function () {
  92. $options = [
  93. 'body' => 'This is the body',
  94. 'charset' => 'ISO-8859-1',
  95. 'type' => 'txt',
  96. 'status' => '422',
  97. 'statusCodes' => [
  98. 422 => 'Unprocessable Entity'
  99. ]
  100. ];
  101. $response = new Response($options);
  102. $this->assertEquals($options['body'], (string)$response->getBody());
  103. $this->assertEquals($options['charset'], $response->getCharset());
  104. $this->assertEquals($response->getMimeType($options['type']), $response->getType());
  105. $this->assertEquals($options['status'], $response->getStatusCode());
  106. $this->assertEquals('text/plain; charset=ISO-8859-1', $response->getHeaderLine('Content-Type'));
  107. });
  108. }
  109. /**
  110. * Tests the body method
  111. *
  112. * @group deprecated
  113. * @return void
  114. */
  115. public function testBody()
  116. {
  117. $this->deprecated(function () {
  118. $response = new Response();
  119. $this->assertNull($response->body());
  120. $response->body('Response body');
  121. $this->assertEquals('Response body', $response->body());
  122. $this->assertEquals('Changed Body', $response->body('Changed Body'));
  123. $response = new Response();
  124. $response->body(0);
  125. $this->assertEquals(0, $response->body());
  126. $response = new Response();
  127. $response->body('0');
  128. $this->assertEquals('0', $response->body());
  129. $response = new Response();
  130. $response->body(null);
  131. $this->assertNull($response->body());
  132. });
  133. }
  134. /**
  135. * Tests the charset method
  136. *
  137. * @group deprecated
  138. * @return void
  139. */
  140. public function testCharset()
  141. {
  142. $this->deprecated(function () {
  143. $response = new Response();
  144. $this->assertEquals('UTF-8', $response->charset());
  145. $response->charset('iso-8859-1');
  146. $this->assertEquals('iso-8859-1', $response->charset());
  147. $this->assertEquals('UTF-16', $response->charset('UTF-16'));
  148. });
  149. }
  150. /**
  151. * Tests the getCharset/withCharset methods
  152. *
  153. * @return void
  154. */
  155. public function testWithCharset()
  156. {
  157. $response = new Response();
  158. $this->assertEquals('text/html; charset=UTF-8', $response->getHeaderLine('Content-Type'));
  159. $new = $response->withCharset('iso-8859-1');
  160. $this->assertNotContains('iso', $response->getHeaderLine('Content-Type'), 'Old instance not changed');
  161. $this->assertSame('iso-8859-1', $new->getCharset());
  162. $this->assertEquals('text/html; charset=iso-8859-1', $new->getHeaderLine('Content-Type'));
  163. }
  164. /**
  165. * Tests the statusCode method
  166. *
  167. * @group deprecated
  168. * @return void
  169. */
  170. public function testStatusCode()
  171. {
  172. $this->deprecated(function () {
  173. $response = new Response();
  174. $this->assertEquals(200, $response->statusCode());
  175. $response->statusCode(404);
  176. $this->assertEquals(404, $response->getStatusCode(), 'Sets shared state.');
  177. $this->assertEquals(404, $response->statusCode());
  178. $this->assertEquals('Not Found', $response->getReasonPhrase());
  179. $this->assertEquals(500, $response->statusCode(500));
  180. });
  181. }
  182. /**
  183. * Test invalid status codes
  184. *
  185. * @group deprecated
  186. * @return void
  187. */
  188. public function testStatusCodeInvalid()
  189. {
  190. $this->expectException(\InvalidArgumentException::class);
  191. $this->deprecated(function () {
  192. $response = new Response();
  193. $response->statusCode(1001);
  194. });
  195. }
  196. /**
  197. * Tests the type method
  198. *
  199. * @group deprecated
  200. * @return void
  201. */
  202. public function testType()
  203. {
  204. $this->deprecated(function () {
  205. $response = new Response();
  206. $this->assertEquals('text/html', $response->type());
  207. $response->type('pdf');
  208. $this->assertEquals('application/pdf', $response->type());
  209. $this->assertEquals('application/crazy-mime', $response->type('application/crazy-mime'));
  210. $this->assertEquals('application/json', $response->type('json'));
  211. $this->assertEquals('text/vnd.wap.wml', $response->type('wap'));
  212. $this->assertEquals('application/vnd.wap.xhtml+xml', $response->type('xhtml-mobile'));
  213. $this->assertEquals('text/csv', $response->type('csv'));
  214. $response->type(['keynote' => 'application/keynote', 'bat' => 'application/bat']);
  215. $this->assertEquals('application/keynote', $response->type('keynote'));
  216. $this->assertEquals('application/bat', $response->type('bat'));
  217. $this->assertFalse($response->type('wackytype'));
  218. });
  219. }
  220. /**
  221. * Tests the getType method
  222. *
  223. * @return void
  224. */
  225. public function testGetType()
  226. {
  227. $response = new Response();
  228. $this->assertEquals('text/html', $response->getType());
  229. $this->assertEquals(
  230. 'application/pdf',
  231. $response->withType('pdf')->getType()
  232. );
  233. $this->assertEquals(
  234. 'custom/stuff',
  235. $response->withType('custom/stuff')->getType()
  236. );
  237. $this->assertEquals(
  238. 'application/json',
  239. $response->withType('json')->getType()
  240. );
  241. }
  242. /**
  243. * Tests the withType method
  244. *
  245. * @return void
  246. */
  247. public function testWithTypeAlias()
  248. {
  249. $response = new Response();
  250. $this->assertEquals(
  251. 'text/html; charset=UTF-8',
  252. $response->getHeaderLine('Content-Type'),
  253. 'Default content-type should match'
  254. );
  255. $new = $response->withType('pdf');
  256. $this->assertNotSame($new, $response, 'Should be a new instance');
  257. $this->assertSame(
  258. 'text/html; charset=UTF-8',
  259. $response->getHeaderLine('Content-Type'),
  260. 'Original object should not be modified'
  261. );
  262. $this->assertSame('application/pdf', $new->getHeaderLine('Content-Type'));
  263. $this->assertSame(
  264. 'application/json; charset=UTF-8',
  265. $new->withType('json')->getHeaderLine('Content-Type')
  266. );
  267. }
  268. /**
  269. * test withType() and full mime-types
  270. *
  271. * @return void
  272. */
  273. public function withTypeFull()
  274. {
  275. $response = new Response();
  276. $this->assertEquals(
  277. 'application/json',
  278. $response->withType('application/json')->getHeaderLine('Content-Type'),
  279. 'Should not add charset to explicit type'
  280. );
  281. $this->assertEquals(
  282. 'custom/stuff',
  283. $response->withType('custom/stuff')->getHeaderLine('Content-Type'),
  284. 'Should allow arbitrary types'
  285. );
  286. }
  287. /**
  288. * Test that an invalid type raises an exception
  289. *
  290. * @return void
  291. */
  292. public function testWithTypeInvalidType()
  293. {
  294. $this->expectException(\InvalidArgumentException::class);
  295. $this->expectExceptionMessage('"beans" is an invalid content type');
  296. $response = new Response();
  297. $response->withType('beans');
  298. }
  299. /**
  300. * Tests the header method
  301. *
  302. * @group deprecated
  303. * @return void
  304. */
  305. public function testHeader()
  306. {
  307. $this->deprecated(function () {
  308. $response = new Response();
  309. $headers = [
  310. 'Content-Type' => 'text/html; charset=UTF-8',
  311. ];
  312. $this->assertEquals($headers, $response->header());
  313. $response->header('Location', 'http://example.com');
  314. $headers += ['Location' => 'http://example.com'];
  315. $this->assertEquals($headers, $response->header());
  316. // Headers with the same name are overwritten
  317. $response->header('Location', 'http://example2.com');
  318. $headers = [
  319. 'Content-Type' => 'text/html; charset=UTF-8',
  320. 'Location' => 'http://example2.com'
  321. ];
  322. $this->assertEquals($headers, $response->header());
  323. $response->header(['WWW-Authenticate' => 'Negotiate']);
  324. $headers += ['WWW-Authenticate' => 'Negotiate'];
  325. $this->assertEquals($headers, $response->header());
  326. $response->header(['WWW-Authenticate' => 'Not-Negotiate']);
  327. $headers['WWW-Authenticate'] = 'Not-Negotiate';
  328. $this->assertEquals($headers, $response->header());
  329. $response->header(['Age' => 12, 'Allow' => 'GET, HEAD']);
  330. $headers += ['Age' => 12, 'Allow' => 'GET, HEAD'];
  331. $this->assertEquals($headers, $response->header());
  332. // String headers are allowed
  333. $response->header('Content-Language: da');
  334. $headers += ['Content-Language' => 'da'];
  335. $this->assertEquals($headers, $response->header());
  336. $response->header('Content-Language: da');
  337. $headers += ['Content-Language' => 'da'];
  338. $this->assertEquals($headers, $response->header());
  339. $response->header(['Content-Encoding: gzip', 'Vary: *', 'Pragma' => 'no-cache']);
  340. $headers += ['Content-Encoding' => 'gzip', 'Vary' => '*', 'Pragma' => 'no-cache'];
  341. $this->assertEquals($headers, $response->header());
  342. $response->header('Access-Control-Allow-Origin', ['domain1', 'domain2']);
  343. $headers += ['Access-Control-Allow-Origin' => ['domain1', 'domain2']];
  344. $this->assertEquals($headers, $response->header());
  345. });
  346. }
  347. /**
  348. * Tests the send method
  349. *
  350. * @group deprecated
  351. * @return void
  352. */
  353. public function testSend()
  354. {
  355. $GLOBALS['mockedHeadersSent'] = false;
  356. $this->deprecated(function () {
  357. $response = $this->getMockBuilder('Cake\Http\Response')
  358. ->setMethods(['_sendHeader', '_sendContent'])
  359. ->getMock();
  360. $response->header([
  361. 'Content-Language' => 'es',
  362. 'WWW-Authenticate' => 'Negotiate',
  363. 'Access-Control-Allow-Origin' => ['domain1', 'domain2'],
  364. ]);
  365. $response->cookie(['name' => 'thing', 'value' => 'value']);
  366. $response->body('the response body');
  367. $response->expects($this->once())->method('_sendContent')->with('the response body');
  368. $response->expects($this->at(0))
  369. ->method('_sendHeader')->with('HTTP/1.1 200 OK');
  370. $response->expects($this->at(1))
  371. ->method('_sendHeader')->with('Content-Type', 'text/html; charset=UTF-8');
  372. $response->expects($this->at(2))
  373. ->method('_sendHeader')->with('Content-Language', 'es');
  374. $response->expects($this->at(3))
  375. ->method('_sendHeader')->with('WWW-Authenticate', 'Negotiate');
  376. $response->expects($this->at(4))
  377. ->method('_sendHeader')->with('Access-Control-Allow-Origin', 'domain1');
  378. $response->expects($this->at(5))
  379. ->method('_sendHeader')->with('Access-Control-Allow-Origin', 'domain2');
  380. $response->send();
  381. $this->assertCount(1, $GLOBALS['mockedCookies']);
  382. $this->assertSame('value', $GLOBALS['mockedCookies'][0]['value']);
  383. $this->assertSame('thing', $GLOBALS['mockedCookies'][0]['name']);
  384. });
  385. }
  386. /**
  387. * Data provider for content type tests.
  388. *
  389. * @return array
  390. */
  391. public static function charsetTypeProvider()
  392. {
  393. return [
  394. ['mp3', 'audio/mpeg'],
  395. ['js', 'application/javascript; charset=UTF-8'],
  396. ['json', 'application/json; charset=UTF-8'],
  397. ['xml', 'application/xml; charset=UTF-8'],
  398. ['txt', 'text/plain; charset=UTF-8'],
  399. ];
  400. }
  401. /**
  402. * Tests the send method and changing the content type
  403. *
  404. * @group deprecated
  405. * @dataProvider charsetTypeProvider
  406. * @return void
  407. */
  408. public function testSendChangingContentType($original, $expected)
  409. {
  410. $this->deprecated(function () use ($original, $expected) {
  411. $response = new Response();
  412. $response->type($original);
  413. $response->body('the response body');
  414. $this->assertEquals($expected, $response->getHeaderLine('Content-Type'));
  415. });
  416. }
  417. /**
  418. * Tests the send method and changing the content type to JS without adding the charset
  419. *
  420. * @group deprecated
  421. * @return void
  422. */
  423. public function testCharsetSetContentTypeWithoutCharset()
  424. {
  425. $this->deprecated(function () {
  426. $response = new Response();
  427. $response->type('js');
  428. $response->charset('');
  429. $this->assertEquals('application/javascript', $response->getHeaderLine('Content-Type'));
  430. });
  431. }
  432. /**
  433. * Tests the send method and changing the content type
  434. *
  435. * @group deprecated
  436. * @return void
  437. */
  438. public function testLocationSetsStatus()
  439. {
  440. $this->deprecated(function () {
  441. $response = new Response();
  442. $response->location('http://www.example.com');
  443. $this->assertEquals(302, $response->getStatusCode());
  444. });
  445. }
  446. /**
  447. * Test that setting certain status codes clears the status code.
  448. *
  449. * @group deprecated
  450. * @return void
  451. */
  452. public function testStatusClearsContentType()
  453. {
  454. $this->deprecated(function () {
  455. $response = new Response();
  456. $response->statusCode(204);
  457. $response->statusCode(304);
  458. $this->assertFalse($response->hasHeader('Content-Type'));
  459. $this->assertSame(304, $response->getStatusCode());
  460. $response = new Response();
  461. $response->type('pdf');
  462. $response->statusCode(204);
  463. $this->assertFalse($response->hasHeader('Content-Type'));
  464. $this->assertSame(204, $response->getStatusCode());
  465. $response = new Response();
  466. $response->statusCode(204);
  467. $response->type('pdf');
  468. $this->assertFalse($response->hasHeader('Content-Type'));
  469. });
  470. }
  471. /**
  472. * Test that setting certain status codes clears the status code.
  473. *
  474. * @return void
  475. */
  476. public function testWithStatusClearsContentType()
  477. {
  478. $response = new Response();
  479. $new = $response->withType('pdf')
  480. ->withStatus(204);
  481. $this->assertFalse($new->hasHeader('Content-Type'));
  482. $this->assertSame(204, $new->getStatusCode());
  483. $response = new Response();
  484. $new = $response->withStatus(304)
  485. ->withType('pdf');
  486. $this->assertFalse($new->hasHeader('Content-Type'));
  487. }
  488. /**
  489. * Tests the send method and changing the content type
  490. *
  491. * @group deprecated
  492. * @return void
  493. */
  494. public function testSendWithCallableBody()
  495. {
  496. $this->deprecated(function () {
  497. $response = $this->getMockBuilder('Cake\Http\Response')
  498. ->setMethods(['_sendHeader'])
  499. ->getMock();
  500. $response->body(function () {
  501. echo 'the response body';
  502. });
  503. ob_start();
  504. $response->send();
  505. $this->assertEquals('the response body', ob_get_clean());
  506. });
  507. }
  508. /**
  509. * Tests that the returned a string from a body callable is also sent
  510. * as the response body
  511. *
  512. * @group deprecated
  513. * @return void
  514. */
  515. public function testSendWithCallableBodyWithReturn()
  516. {
  517. $this->deprecated(function () {
  518. $response = $this->getMockBuilder('Cake\Http\Response')
  519. ->setMethods(['_sendHeader'])
  520. ->getMock();
  521. $response->body(function () {
  522. return 'the response body';
  523. });
  524. ob_start();
  525. $response->send();
  526. $this->assertEquals('the response body', ob_get_clean());
  527. });
  528. }
  529. /**
  530. * Tests the disableCache method
  531. *
  532. * @group deprecated
  533. * @return void
  534. */
  535. public function testDisableCache()
  536. {
  537. $this->deprecated(function () {
  538. $response = new Response();
  539. $expected = [
  540. 'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT',
  541. 'Last-Modified' => gmdate('D, d M Y H:i:s') . ' GMT',
  542. 'Cache-Control' => 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
  543. 'Content-Type' => 'text/html; charset=UTF-8',
  544. ];
  545. $response->disableCache();
  546. $this->assertEquals($expected, $response->header());
  547. });
  548. }
  549. /**
  550. * Tests the withDisabledCache method
  551. *
  552. * @return void
  553. */
  554. public function testWithDisabledCache()
  555. {
  556. $response = new Response();
  557. $expected = [
  558. 'Expires' => ['Mon, 26 Jul 1997 05:00:00 GMT'],
  559. 'Last-Modified' => [gmdate('D, d M Y H:i:s') . ' GMT'],
  560. 'Cache-Control' => ['no-store, no-cache, must-revalidate, post-check=0, pre-check=0'],
  561. 'Content-Type' => ['text/html; charset=UTF-8'],
  562. ];
  563. $new = $response->withDisabledCache();
  564. $this->assertFalse($response->hasHeader('Expires'), 'Old instance not mutated.');
  565. $this->assertEquals($expected, $new->getHeaders());
  566. }
  567. /**
  568. * Tests the cache method
  569. *
  570. * @group deprecated
  571. * @return void
  572. */
  573. public function testCache()
  574. {
  575. $this->deprecated(function () {
  576. $response = new Response();
  577. $since = time();
  578. $time = new \DateTime('+1 day', new \DateTimeZone('UTC'));
  579. $response->expires('+1 day');
  580. $expected = [
  581. 'Date' => gmdate('D, j M Y G:i:s ', $since) . 'GMT',
  582. 'Last-Modified' => gmdate('D, j M Y H:i:s ', $since) . 'GMT',
  583. 'Expires' => $time->format('D, j M Y H:i:s') . ' GMT',
  584. 'Cache-Control' => 'public, max-age=' . ($time->format('U') - time()),
  585. 'Content-Type' => 'text/html; charset=UTF-8',
  586. ];
  587. $response->cache($since);
  588. $this->assertEquals($expected, $response->header());
  589. $response = new Response();
  590. $since = time();
  591. $time = '+5 day';
  592. $expected = [
  593. 'Date' => gmdate('D, j M Y G:i:s ', $since) . 'GMT',
  594. 'Last-Modified' => gmdate('D, j M Y H:i:s ', $since) . 'GMT',
  595. 'Expires' => gmdate('D, j M Y H:i:s', strtotime($time)) . ' GMT',
  596. 'Cache-Control' => 'public, max-age=' . (strtotime($time) - time()),
  597. 'Content-Type' => 'text/html; charset=UTF-8',
  598. ];
  599. $response->cache($since, $time);
  600. $this->assertEquals($expected, $response->header());
  601. $response = new Response();
  602. $since = time();
  603. $time = time();
  604. $expected = [
  605. 'Date' => gmdate('D, j M Y G:i:s ', $since) . 'GMT',
  606. 'Last-Modified' => gmdate('D, j M Y H:i:s ', $since) . 'GMT',
  607. 'Expires' => gmdate('D, j M Y H:i:s', $time) . ' GMT',
  608. 'Cache-Control' => 'public, max-age=0',
  609. 'Content-Type' => 'text/html; charset=UTF-8',
  610. ];
  611. $response->cache($since, $time);
  612. $this->assertEquals($expected, $response->header());
  613. });
  614. }
  615. /**
  616. * Tests the withCache method
  617. *
  618. * @return void
  619. */
  620. public function testWithCache()
  621. {
  622. $response = new Response();
  623. $since = $time = time();
  624. $new = $response->withCache($since, $time);
  625. $this->assertFalse($response->hasHeader('Date'));
  626. $this->assertFalse($response->hasHeader('Last-Modified'));
  627. $this->assertEquals(gmdate('D, j M Y G:i:s ', $since) . 'GMT', $new->getHeaderLine('Date'));
  628. $this->assertEquals(gmdate('D, j M Y H:i:s ', $since) . 'GMT', $new->getHeaderLine('Last-Modified'));
  629. $this->assertEquals(gmdate('D, j M Y H:i:s', $time) . ' GMT', $new->getHeaderLine('Expires'));
  630. $this->assertEquals('public, max-age=0', $new->getHeaderLine('Cache-Control'));
  631. }
  632. /**
  633. * Tests the compress method
  634. *
  635. * @return void
  636. */
  637. public function testCompress()
  638. {
  639. $this->skipIf(defined('HHVM_VERSION'), 'HHVM does not implement ob_gzhandler');
  640. $response = new Response();
  641. if (ini_get('zlib.output_compression') === '1' || !extension_loaded('zlib')) {
  642. $this->assertFalse($response->compress());
  643. $this->markTestSkipped('Is not possible to test output compression');
  644. }
  645. $_SERVER['HTTP_ACCEPT_ENCODING'] = '';
  646. $result = $response->compress();
  647. $this->assertFalse($result);
  648. $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip';
  649. $result = $response->compress();
  650. $this->assertTrue($result);
  651. $this->assertContains('ob_gzhandler', ob_list_handlers());
  652. ob_get_clean();
  653. }
  654. /**
  655. * Tests the httpCodes method
  656. *
  657. * @group deprecated
  658. * @return void
  659. */
  660. public function testHttpCodes()
  661. {
  662. $this->expectException(\InvalidArgumentException::class);
  663. $this->deprecated(function () {
  664. $response = new Response();
  665. $result = $response->httpCodes();
  666. $this->assertCount(65, $result);
  667. $result = $response->httpCodes(100);
  668. $expected = [100 => 'Continue'];
  669. $this->assertEquals($expected, $result);
  670. $codes = [
  671. 381 => 'Unicorn Moved',
  672. 555 => 'Unexpected Minotaur'
  673. ];
  674. $result = $response->httpCodes($codes);
  675. $this->assertTrue($result);
  676. $this->assertCount(67, $response->httpCodes());
  677. $result = $response->httpCodes(381);
  678. $expected = [381 => 'Unicorn Moved'];
  679. $this->assertEquals($expected, $result);
  680. $codes = [404 => 'Sorry Bro'];
  681. $result = $response->httpCodes($codes);
  682. $this->assertTrue($result);
  683. $this->assertCount(67, $response->httpCodes());
  684. $result = $response->httpCodes(404);
  685. $expected = [404 => 'Sorry Bro'];
  686. $this->assertEquals($expected, $result);
  687. //Throws exception
  688. $response->httpCodes([
  689. 0 => 'Nothing Here',
  690. -1 => 'Reverse Infinity',
  691. 12345 => 'Universal Password',
  692. 'Hello' => 'World'
  693. ]);
  694. });
  695. }
  696. /**
  697. * Tests the download method
  698. *
  699. * @group deprecated
  700. * @return void
  701. */
  702. public function testDownload()
  703. {
  704. $this->deprecated(function () {
  705. $response = new Response();
  706. $expected = [
  707. 'Content-Type' => 'text/html; charset=UTF-8',
  708. 'Content-Disposition' => 'attachment; filename="myfile.mp3"'
  709. ];
  710. $response->download('myfile.mp3');
  711. $this->assertEquals($expected, $response->header());
  712. });
  713. }
  714. /**
  715. * Tests the withDownload method
  716. *
  717. * @return void
  718. */
  719. public function testWithDownload()
  720. {
  721. $response = new Response();
  722. $new = $response->withDownload('myfile.mp3');
  723. $this->assertFalse($response->hasHeader('Content-Disposition'), 'No mutation');
  724. $expected = 'attachment; filename="myfile.mp3"';
  725. $this->assertEquals($expected, $new->getHeaderLine('Content-Disposition'));
  726. }
  727. /**
  728. * Tests the mapType method
  729. *
  730. * @return void
  731. */
  732. public function testMapType()
  733. {
  734. $response = new Response();
  735. $this->assertEquals('wav', $response->mapType('audio/x-wav'));
  736. $this->assertEquals('pdf', $response->mapType('application/pdf'));
  737. $this->assertEquals('xml', $response->mapType('text/xml'));
  738. $this->assertEquals('html', $response->mapType('*/*'));
  739. $this->assertEquals('csv', $response->mapType('application/vnd.ms-excel'));
  740. $expected = ['json', 'xhtml', 'css'];
  741. $result = $response->mapType(['application/json', 'application/xhtml+xml', 'text/css']);
  742. $this->assertEquals($expected, $result);
  743. }
  744. /**
  745. * Tests the outputCompressed method
  746. *
  747. * @return void
  748. */
  749. public function testOutputCompressed()
  750. {
  751. $response = new Response();
  752. $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip';
  753. $result = $response->outputCompressed();
  754. $this->assertFalse($result);
  755. $_SERVER['HTTP_ACCEPT_ENCODING'] = '';
  756. $result = $response->outputCompressed();
  757. $this->assertFalse($result);
  758. if (!extension_loaded('zlib')) {
  759. $this->markTestSkipped('Skipping further tests for outputCompressed as zlib extension is not loaded');
  760. }
  761. $this->skipIf(defined('HHVM_VERSION'), 'HHVM does not implement ob_gzhandler');
  762. if (ini_get('zlib.output_compression') !== '1') {
  763. ob_start('ob_gzhandler');
  764. }
  765. $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip';
  766. $result = $response->outputCompressed();
  767. $this->assertTrue($result);
  768. $_SERVER['HTTP_ACCEPT_ENCODING'] = '';
  769. $result = $response->outputCompressed();
  770. $this->assertFalse($result);
  771. if (ini_get('zlib.output_compression') !== '1') {
  772. ob_get_clean();
  773. }
  774. }
  775. /**
  776. * Tests getting/setting the protocol
  777. *
  778. * @group deprecated
  779. * @return void
  780. */
  781. public function testProtocol()
  782. {
  783. $GLOBALS['mockedHeadersSent'] = false;
  784. $this->deprecated(function () {
  785. $response = $this->getMockBuilder('Cake\Http\Response')
  786. ->setMethods(['_sendHeader', '_sendContent'])
  787. ->getMock();
  788. $response->protocol('HTTP/1.0');
  789. $this->assertEquals('HTTP/1.0', $response->protocol());
  790. $response->expects($this->at(0))
  791. ->method('_sendHeader')->with('HTTP/1.0 200 OK');
  792. $response->send();
  793. });
  794. }
  795. /**
  796. * Tests getting/setting the Content-Length
  797. *
  798. * @group deprecated
  799. * @return void
  800. */
  801. public function testLength()
  802. {
  803. $this->deprecated(function () {
  804. $response = new Response();
  805. $response->length(100);
  806. $this->assertEquals(100, $response->length());
  807. $this->assertEquals('100', $response->getHeaderLine('Content-Length'));
  808. });
  809. }
  810. /**
  811. * Tests settings the content length
  812. *
  813. * @return void
  814. */
  815. public function testWithLength()
  816. {
  817. $response = new Response();
  818. $this->assertFalse($response->hasHeader('Content-Length'));
  819. $new = $response->withLength(100);
  820. $this->assertFalse($response->hasHeader('Content-Length'), 'Old instance not modified');
  821. $this->assertSame('100', $new->getHeaderLine('Content-Length'));
  822. }
  823. /**
  824. * Tests setting the expiration date
  825. *
  826. * @group deprecated
  827. * @return void
  828. */
  829. public function testExpires()
  830. {
  831. $this->deprecated(function () {
  832. $format = 'D, j M Y H:i:s';
  833. $response = new Response();
  834. $now = new \DateTime('now', new \DateTimeZone('America/Los_Angeles'));
  835. $response->expires($now);
  836. $now->setTimeZone(new \DateTimeZone('UTC'));
  837. $this->assertEquals($now->format($format) . ' GMT', $response->expires());
  838. $this->assertEquals($now->format($format) . ' GMT', $response->getHeaderLine('Expires'));
  839. $now = time();
  840. $response = new Response();
  841. $response->expires($now);
  842. $this->assertEquals(gmdate($format) . ' GMT', $response->expires());
  843. $this->assertEquals(gmdate($format) . ' GMT', $response->getHeaderLine('Expires'));
  844. $response = new Response();
  845. $time = new \DateTime('+1 day', new \DateTimeZone('UTC'));
  846. $response->expires('+1 day');
  847. $this->assertEquals($time->format($format) . ' GMT', $response->expires());
  848. $this->assertEquals($time->format($format) . ' GMT', $response->getHeaderLine('Expires'));
  849. });
  850. }
  851. /**
  852. * Tests the withExpires method
  853. *
  854. * @return void
  855. */
  856. public function testWithExpires()
  857. {
  858. $format = 'D, j M Y H:i:s';
  859. $response = new Response();
  860. $now = new \DateTime('now', new \DateTimeZone('America/Los_Angeles'));
  861. $new = $response->withExpires($now);
  862. $this->assertFalse($response->hasHeader('Expires'));
  863. $now->setTimeZone(new \DateTimeZone('UTC'));
  864. $this->assertEquals($now->format($format) . ' GMT', $new->getHeaderLine('Expires'));
  865. $now = time();
  866. $new = $response->withExpires($now);
  867. $this->assertEquals(gmdate($format) . ' GMT', $new->getHeaderLine('Expires'));
  868. $time = new \DateTime('+1 day', new \DateTimeZone('UTC'));
  869. $new = $response->withExpires('+1 day');
  870. $this->assertEquals($time->format($format) . ' GMT', $new->getHeaderLine('Expires'));
  871. }
  872. /**
  873. * Tests setting the modification date
  874. *
  875. * @group deprecated
  876. * @return void
  877. */
  878. public function testModified()
  879. {
  880. $this->deprecated(function () {
  881. $format = 'D, j M Y H:i:s';
  882. $response = new Response();
  883. $now = new \DateTime('now', new \DateTimeZone('America/Los_Angeles'));
  884. $response->modified($now);
  885. $now->setTimeZone(new \DateTimeZone('UTC'));
  886. $this->assertEquals($now->format($format) . ' GMT', $response->modified());
  887. $this->assertEquals($now->format($format) . ' GMT', $response->getHeaderLine('Last-Modified'));
  888. $response = new Response();
  889. $now = time();
  890. $response->modified($now);
  891. $this->assertEquals(gmdate($format) . ' GMT', $response->modified());
  892. $this->assertEquals(gmdate($format) . ' GMT', $response->getHeaderLine('Last-Modified'));
  893. $response = new Response();
  894. $time = new \DateTime('+1 day', new \DateTimeZone('UTC'));
  895. $response->modified('+1 day');
  896. $this->assertEquals($time->format($format) . ' GMT', $response->modified());
  897. $this->assertEquals($time->format($format) . ' GMT', $response->getHeaderLine('Last-Modified'));
  898. });
  899. }
  900. /**
  901. * Tests the withModified method
  902. *
  903. * @return void
  904. */
  905. public function testWithModified()
  906. {
  907. $format = 'D, j M Y H:i:s';
  908. $response = new Response();
  909. $now = new \DateTime('now', new \DateTimeZone('America/Los_Angeles'));
  910. $new = $response->withModified($now);
  911. $this->assertFalse($response->hasHeader('Last-Modified'));
  912. $now->setTimeZone(new \DateTimeZone('UTC'));
  913. $this->assertEquals($now->format($format) . ' GMT', $new->getHeaderLine('Last-Modified'));
  914. $now = time();
  915. $new = $response->withModified($now);
  916. $this->assertEquals(gmdate($format) . ' GMT', $new->getHeaderLine('Last-Modified'));
  917. $time = new \DateTime('+1 day', new \DateTimeZone('UTC'));
  918. $new = $response->withModified('+1 day');
  919. $this->assertEquals($time->format($format) . ' GMT', $new->getHeaderLine('Last-Modified'));
  920. }
  921. /**
  922. * Tests setting of public/private Cache-Control directives
  923. *
  924. * @return void
  925. */
  926. public function testSharable()
  927. {
  928. $response = new Response();
  929. $this->assertNull($response->sharable());
  930. $response->sharable(true);
  931. $this->assertTrue($response->sharable());
  932. $this->assertEquals('public', $response->getHeaderLine('Cache-Control'));
  933. $response = new Response();
  934. $response->sharable(false);
  935. $this->assertFalse($response->sharable());
  936. $this->assertEquals('private', $response->getHeaderLine('Cache-Control'));
  937. $response = new Response();
  938. $response->sharable(true, 3600);
  939. $this->assertEquals('public, max-age=3600', $response->getHeaderLine('Cache-Control'));
  940. $response = new Response();
  941. $response->sharable(false, 3600);
  942. $this->assertEquals('private, max-age=3600', $response->getHeaderLine('Cache-Control'));
  943. }
  944. /**
  945. * Tests withSharable()
  946. *
  947. * @return void
  948. */
  949. public function testWithSharable()
  950. {
  951. $response = new Response();
  952. $new = $response->withSharable(true);
  953. $this->assertFalse($response->hasHeader('Cache-Control'), 'old instance unchanged');
  954. $this->assertEquals('public', $new->getHeaderLine('Cache-Control'));
  955. $new = $response->withSharable(false);
  956. $this->assertEquals('private', $new->getHeaderLine('Cache-Control'));
  957. $new = $response->withSharable(true, 3600);
  958. $this->assertEquals('public, max-age=3600', $new->getHeaderLine('Cache-Control'));
  959. $new = $response->withSharable(false, 3600);
  960. $this->assertEquals('private, max-age=3600', $new->getHeaderLine('Cache-Control'));
  961. }
  962. /**
  963. * Tests setting of max-age Cache-Control directive
  964. *
  965. * @return void
  966. */
  967. public function testMaxAge()
  968. {
  969. $response = new Response();
  970. $this->assertNull($response->maxAge());
  971. $response->maxAge(3600);
  972. $this->assertEquals(3600, $response->maxAge());
  973. $this->assertEquals('max-age=3600', $response->getHeaderLine('Cache-Control'));
  974. $response = new Response();
  975. $response->maxAge(3600);
  976. $response->sharable(false);
  977. $this->assertEquals('max-age=3600, private', $response->getHeaderLine('Cache-Control'));
  978. }
  979. /**
  980. * Tests withMaxAge()
  981. *
  982. * @return void
  983. */
  984. public function testWithMaxAge()
  985. {
  986. $response = new Response();
  987. $this->assertFalse($response->hasHeader('Cache-Control'));
  988. $new = $response->withMaxAge(3600);
  989. $this->assertEquals('max-age=3600', $new->getHeaderLine('Cache-Control'));
  990. $new = $response->withMaxAge(3600)
  991. ->withSharable(false);
  992. $this->assertEquals('max-age=3600, private', $new->getHeaderLine('Cache-Control'));
  993. }
  994. /**
  995. * Tests setting of s-maxage Cache-Control directive
  996. *
  997. * @return void
  998. */
  999. public function testSharedMaxAge()
  1000. {
  1001. $response = new Response();
  1002. $this->assertNull($response->maxAge());
  1003. $response->sharedMaxAge(3600);
  1004. $this->assertEquals(3600, $response->sharedMaxAge());
  1005. $this->assertEquals('s-maxage=3600', $response->getHeaderLine('Cache-Control'));
  1006. $response = new Response();
  1007. $response->sharedMaxAge(3600);
  1008. $response->sharable(true);
  1009. $this->assertEquals('s-maxage=3600, public', $response->getHeaderLine('Cache-Control'));
  1010. }
  1011. /**
  1012. * Tests setting of s-maxage Cache-Control directive
  1013. *
  1014. * @return void
  1015. */
  1016. public function testWithSharedMaxAge()
  1017. {
  1018. $response = new Response();
  1019. $new = $response->withSharedMaxAge(3600);
  1020. $this->assertFalse($response->hasHeader('Cache-Control'));
  1021. $this->assertEquals('s-maxage=3600', $new->getHeaderLine('Cache-Control'));
  1022. $new = $response->withSharedMaxAge(3600)->withSharable(true);
  1023. $this->assertEquals('s-maxage=3600, public', $new->getHeaderLine('Cache-Control'));
  1024. }
  1025. /**
  1026. * Tests setting of must-revalidate Cache-Control directive
  1027. *
  1028. * @group deprecated
  1029. * @return void
  1030. */
  1031. public function testMustRevalidate()
  1032. {
  1033. $this->deprecated(function () {
  1034. $response = new Response();
  1035. $this->assertFalse($response->mustRevalidate());
  1036. $response->mustRevalidate(true);
  1037. $this->assertTrue($response->mustRevalidate());
  1038. $this->assertEquals('must-revalidate', $response->getHeaderLine('Cache-Control'));
  1039. $response->mustRevalidate(false);
  1040. $this->assertFalse($response->mustRevalidate());
  1041. $response = new Response();
  1042. $response->sharedMaxAge(3600);
  1043. $response->mustRevalidate(true);
  1044. $this->assertEquals('s-maxage=3600, must-revalidate', $response->getHeaderLine('Cache-Control'));
  1045. });
  1046. }
  1047. /**
  1048. * Tests setting of must-revalidate Cache-Control directive
  1049. *
  1050. * @return void
  1051. */
  1052. public function testWithMustRevalidate()
  1053. {
  1054. $response = new Response();
  1055. $this->assertFalse($response->hasHeader('Cache-Control'));
  1056. $new = $response->withMustRevalidate(true);
  1057. $this->assertFalse($response->hasHeader('Cache-Control'));
  1058. $this->assertEquals('must-revalidate', $new->getHeaderLine('Cache-Control'));
  1059. $new = $new->withMustRevalidate(false);
  1060. $this->assertEmpty($new->getHeaderLine('Cache-Control'));
  1061. }
  1062. /**
  1063. * Tests getting/setting the Vary header
  1064. *
  1065. * @group deprecated
  1066. * @return void
  1067. */
  1068. public function testVary()
  1069. {
  1070. $this->deprecated(function () {
  1071. $response = new Response();
  1072. $response->vary('Accept-encoding');
  1073. $this->assertEquals('Accept-encoding', $response->getHeaderLine('vary'));
  1074. $response = new Response();
  1075. $response->vary(['Accept-language', 'Accept-encoding']);
  1076. $this->assertEquals(['Accept-language', 'Accept-encoding'], $response->vary());
  1077. $this->assertEquals('Accept-language, Accept-encoding', $response->getHeaderLine('vary'));
  1078. });
  1079. }
  1080. /**
  1081. * Tests withVary()
  1082. *
  1083. * @return void
  1084. */
  1085. public function testWithVary()
  1086. {
  1087. $response = new Response();
  1088. $new = $response->withVary('Accept-encoding');
  1089. $this->assertFalse($response->hasHeader('Vary'));
  1090. $this->assertEquals('Accept-encoding', $new->getHeaderLine('Vary'));
  1091. $new = $response->withVary(['Accept-encoding', 'Accept-language']);
  1092. $this->assertFalse($response->hasHeader('Vary'));
  1093. $this->assertEquals('Accept-encoding,Accept-language', $new->getHeaderLine('Vary'));
  1094. }
  1095. /**
  1096. * Tests getting/setting the Etag header
  1097. *
  1098. * @group deprecated
  1099. * @return void
  1100. */
  1101. public function testEtag()
  1102. {
  1103. $this->deprecated(function () {
  1104. $response = new Response();
  1105. $response->etag('something');
  1106. $this->assertEquals('"something"', $response->etag());
  1107. $this->assertEquals('"something"', $response->getHeaderLine('Etag'));
  1108. $response = new Response();
  1109. $response->etag('something', true);
  1110. $this->assertEquals('W/"something"', $response->etag());
  1111. $this->assertEquals('W/"something"', $response->getHeaderLine('Etag'));
  1112. });
  1113. }
  1114. /**
  1115. * Tests withEtag()
  1116. *
  1117. * @return void
  1118. */
  1119. public function testWithEtag()
  1120. {
  1121. $response = new Response();
  1122. $new = $response->withEtag('something');
  1123. $this->assertFalse($response->hasHeader('Etag'));
  1124. $this->assertEquals('"something"', $new->getHeaderLine('Etag'));
  1125. $new = $response->withEtag('something', true);
  1126. $this->assertEquals('W/"something"', $new->getHeaderLine('Etag'));
  1127. }
  1128. /**
  1129. * Tests that the response is able to be marked as not modified
  1130. *
  1131. * @return void
  1132. */
  1133. public function testNotModified()
  1134. {
  1135. $response = new Response();
  1136. $response = $response->withStringBody('something')
  1137. ->withStatus(200)
  1138. ->withLength(100)
  1139. ->withModified('now');
  1140. $response->notModified();
  1141. $this->assertFalse($response->hasHeader('Content-Length'));
  1142. $this->assertFalse($response->hasHeader('Modified'));
  1143. $this->assertEmpty((string)$response->getBody());
  1144. $this->assertEquals(304, $response->getStatusCode());
  1145. }
  1146. /**
  1147. * Tests withNotModified()
  1148. *
  1149. * @return void
  1150. */
  1151. public function testWithNotModified()
  1152. {
  1153. $response = new Response(['body' => 'something']);
  1154. $response = $response->withLength(100)
  1155. ->withStatus(200)
  1156. ->withHeader('Last-Modified', 'value')
  1157. ->withHeader('Content-Language', 'en-EN')
  1158. ->withHeader('X-things', 'things')
  1159. ->withType('application/json');
  1160. $new = $response->withNotModified();
  1161. $this->assertTrue($response->hasHeader('Content-Language'), 'old instance not changed');
  1162. $this->assertTrue($response->hasHeader('Content-Length'), 'old instance not changed');
  1163. $this->assertFalse($new->hasHeader('Content-Type'));
  1164. $this->assertFalse($new->hasHeader('Content-Length'));
  1165. $this->assertFalse($new->hasHeader('Content-Language'));
  1166. $this->assertFalse($new->hasHeader('Last-Modified'));
  1167. $this->assertSame('things', $new->getHeaderLine('X-things'), 'Other headers are retained');
  1168. $this->assertSame(304, $new->getStatusCode());
  1169. $this->assertSame('', $new->getBody()->getContents());
  1170. }
  1171. /**
  1172. * Test checkNotModified method
  1173. *
  1174. * @return void
  1175. */
  1176. public function testCheckNotModifiedByEtagStar()
  1177. {
  1178. $request = new ServerRequest();
  1179. $request = $request->withHeader('If-None-Match', '*');
  1180. $response = new Response();
  1181. $response = $response->withEtag('something')
  1182. ->withHeader('Content-Length', 99);
  1183. $this->assertTrue($response->checkNotModified($request));
  1184. $this->assertFalse($response->hasHeader('Content-Type'), 'etags match, should be unmodified');
  1185. }
  1186. /**
  1187. * Test checkNotModified method
  1188. *
  1189. * @return void
  1190. */
  1191. public function testCheckNotModifiedByEtagExact()
  1192. {
  1193. $request = new ServerRequest();
  1194. $request = $request->withHeader('If-None-Match', 'W/"something", "other"');
  1195. $response = new Response();
  1196. $response = $response->withEtag('something', true)
  1197. ->withHeader('Content-Length', 99);
  1198. $this->assertTrue($response->checkNotModified($request));
  1199. $this->assertFalse($response->hasHeader('Content-Type'), 'etags match, should be unmodified');
  1200. }
  1201. /**
  1202. * Test checkNotModified method
  1203. *
  1204. * @return void
  1205. */
  1206. public function testCheckNotModifiedByEtagAndTime()
  1207. {
  1208. $request = new ServerRequest();
  1209. $request = $request->withHeader('If-Modified-Since', '2012-01-01 00:00:00')
  1210. ->withHeader('If-None-Match', 'W/"something", "other"');
  1211. $response = new Response();
  1212. $response = $response->withModified('2012-01-01 00:00:00')
  1213. ->withEtag('something', true)
  1214. ->withHeader('Content-Length', 99);
  1215. $this->assertTrue($response->checkNotModified($request));
  1216. $this->assertFalse($response->hasHeader('Content-Length'), 'etags match, should be unmodified');
  1217. }
  1218. /**
  1219. * Test checkNotModified method
  1220. *
  1221. * @return void
  1222. */
  1223. public function testCheckNotModifiedByEtagAndTimeMismatch()
  1224. {
  1225. $request = new ServerRequest();
  1226. $request = $request->withHeader('If-Modified-Since', '2012-01-01 00:00:00')
  1227. ->withHeader('If-None-Match', 'W/"something", "other"');
  1228. $response = new Response();
  1229. $response = $response->withModified('2012-01-01 00:00:01')
  1230. ->withEtag('something', true)
  1231. ->withHeader('Content-Length', 99);
  1232. $this->assertFalse($response->checkNotModified($request));
  1233. $this->assertTrue($response->hasHeader('Content-Length'), 'timestamp in response is newer');
  1234. }
  1235. /**
  1236. * Test checkNotModified method
  1237. *
  1238. * @return void
  1239. */
  1240. public function testCheckNotModifiedByEtagMismatch()
  1241. {
  1242. $request = new ServerRequest();
  1243. $request = $request->withHeader('If-Modified-Since', '2012-01-01 00:00:00')
  1244. ->withHeader('If-None-Match', 'W/"something-else", "other"');
  1245. $response = new Response();
  1246. $response = $response->withModified('2012-01-01 00:00:00')
  1247. ->withEtag('something', true)
  1248. ->withHeader('Content-Length', 99);
  1249. $this->assertFalse($response->checkNotModified($request));
  1250. $this->assertTrue($response->hasHeader('Content-Length'), 'etags do not match');
  1251. }
  1252. /**
  1253. * Test checkNotModified method
  1254. *
  1255. * @return void
  1256. */
  1257. public function testCheckNotModifiedByTime()
  1258. {
  1259. $request = new ServerRequest();
  1260. $request = $request->withHeader('If-Modified-Since', '2012-01-01 00:00:00');
  1261. $response = new Response();
  1262. $response = $response->withModified('2012-01-01 00:00:00')
  1263. ->withHeader('Content-Length', 99);
  1264. $this->assertTrue($response->checkNotModified($request));
  1265. $this->assertFalse($response->hasHeader('Content-Length'), 'modified time matches');
  1266. }
  1267. /**
  1268. * Test checkNotModified method
  1269. *
  1270. * @return void
  1271. */
  1272. public function testCheckNotModifiedNoHints()
  1273. {
  1274. $request = new ServerRequest();
  1275. $request = $request->withHeader('If-None-Match', 'W/"something", "other"')
  1276. ->withHeader('If-Modified-Since', '2012-01-01 00:00:00');
  1277. $response = $this->getMockBuilder('Cake\Http\Response')
  1278. ->setMethods(['notModified'])
  1279. ->getMock();
  1280. $response->expects($this->never())->method('notModified');
  1281. $this->assertFalse($response->checkNotModified($request));
  1282. }
  1283. /**
  1284. * Test cookie setting
  1285. *
  1286. * @group deprecated
  1287. * @return void
  1288. */
  1289. public function testCookieSettings()
  1290. {
  1291. $this->deprecated(function () {
  1292. $response = new Response();
  1293. $cookie = [
  1294. 'name' => 'CakeTestCookie[Testing]'
  1295. ];
  1296. $response->cookie($cookie);
  1297. $expected = [
  1298. 'name' => 'CakeTestCookie[Testing]',
  1299. 'value' => '',
  1300. 'expire' => 0,
  1301. 'path' => '/',
  1302. 'domain' => '',
  1303. 'secure' => false,
  1304. 'httpOnly' => false
  1305. ];
  1306. $result = $response->cookie('CakeTestCookie[Testing]');
  1307. $this->assertEquals($expected, $result);
  1308. $cookie = [
  1309. 'name' => 'CakeTestCookie[Testing2]',
  1310. 'value' => '[a,b,c]',
  1311. 'expire' => 1000,
  1312. 'path' => '/test',
  1313. 'secure' => true
  1314. ];
  1315. $response->cookie($cookie);
  1316. $expected = [
  1317. 'CakeTestCookie[Testing]' => [
  1318. 'name' => 'CakeTestCookie[Testing]',
  1319. 'value' => '',
  1320. 'expire' => 0,
  1321. 'path' => '/',
  1322. 'domain' => '',
  1323. 'secure' => false,
  1324. 'httpOnly' => false
  1325. ],
  1326. 'CakeTestCookie[Testing2]' => [
  1327. 'name' => 'CakeTestCookie[Testing2]',
  1328. 'value' => '[a,b,c]',
  1329. 'expire' => 1000,
  1330. 'path' => '/test',
  1331. 'domain' => '',
  1332. 'secure' => true,
  1333. 'httpOnly' => false
  1334. ]
  1335. ];
  1336. $result = $response->cookie();
  1337. $this->assertEquals($expected, $result);
  1338. $cookie = $expected['CakeTestCookie[Testing]'];
  1339. $cookie['value'] = 'test';
  1340. $response->cookie($cookie);
  1341. $expected = [
  1342. 'CakeTestCookie[Testing]' => [
  1343. 'name' => 'CakeTestCookie[Testing]',
  1344. 'value' => 'test',
  1345. 'expire' => 0,
  1346. 'path' => '/',
  1347. 'domain' => '',
  1348. 'secure' => false,
  1349. 'httpOnly' => false
  1350. ],
  1351. 'CakeTestCookie[Testing2]' => [
  1352. 'name' => 'CakeTestCookie[Testing2]',
  1353. 'value' => '[a,b,c]',
  1354. 'expire' => 1000,
  1355. 'path' => '/test',
  1356. 'domain' => '',
  1357. 'secure' => true,
  1358. 'httpOnly' => false
  1359. ]
  1360. ];
  1361. $result = $response->cookie();
  1362. $this->assertEquals($expected, $result);
  1363. });
  1364. }
  1365. /**
  1366. * Test setting cookies with no value
  1367. *
  1368. * @return void
  1369. */
  1370. public function testWithCookieEmpty()
  1371. {
  1372. $response = new Response();
  1373. $new = $response->withCookie('testing');
  1374. $this->assertNull($response->getCookie('testing'), 'withCookie does not mutate');
  1375. $expected = [
  1376. 'name' => 'testing',
  1377. 'value' => '',
  1378. 'expire' => 0,
  1379. 'path' => '/',
  1380. 'domain' => '',
  1381. 'secure' => false,
  1382. 'httpOnly' => false];
  1383. $result = $new->getCookie('testing');
  1384. $this->assertEquals($expected, $result);
  1385. }
  1386. /**
  1387. * Test setting cookies with scalar values
  1388. *
  1389. * @return void
  1390. */
  1391. public function testWithCookieScalar()
  1392. {
  1393. $response = new Response();
  1394. $new = $response->withCookie('testing', 'abc123');
  1395. $this->assertNull($response->getCookie('testing'), 'withCookie does not mutate');
  1396. $this->assertEquals('abc123', $new->getCookie('testing')['value']);
  1397. $new = $response->withCookie('testing', 99);
  1398. $this->assertEquals(99, $new->getCookie('testing')['value']);
  1399. $new = $response->withCookie('testing', false);
  1400. $this->assertFalse($new->getCookie('testing')['value']);
  1401. $new = $response->withCookie('testing', true);
  1402. $this->assertTrue($new->getCookie('testing')['value']);
  1403. }
  1404. /**
  1405. * Test withCookie() and array data.
  1406. *
  1407. * @return void
  1408. */
  1409. public function testWithCookieArray()
  1410. {
  1411. $response = new Response();
  1412. $cookie = [
  1413. 'name' => 'ignored key',
  1414. 'value' => '[a,b,c]',
  1415. 'expire' => 1000,
  1416. 'path' => '/test',
  1417. 'secure' => true
  1418. ];
  1419. $new = $response->withCookie('testing', $cookie);
  1420. $this->assertNull($response->getCookie('testing'), 'withCookie does not mutate');
  1421. $expected = [
  1422. 'name' => 'testing',
  1423. 'value' => '[a,b,c]',
  1424. 'expire' => 1000,
  1425. 'path' => '/test',
  1426. 'domain' => '',
  1427. 'secure' => true,
  1428. 'httpOnly' => false
  1429. ];
  1430. $this->assertEquals($expected, $new->getCookie('testing'));
  1431. }
  1432. /**
  1433. * Test withCookie() and a cookie instance
  1434. *
  1435. * @return void
  1436. */
  1437. public function testWithCookieObject()
  1438. {
  1439. $response = new Response();
  1440. $cookie = new Cookie('yay', 'a value');
  1441. $new = $response->withCookie($cookie);
  1442. $this->assertNull($response->getCookie('yay'), 'withCookie does not mutate');
  1443. $this->assertNotEmpty($new->getCookie('yay'));
  1444. $this->assertSame($cookie, $new->getCookieCollection()->get('yay'));
  1445. }
  1446. public function testWithExpiredCookieScalar()
  1447. {
  1448. $response = new Response();
  1449. $response = $response->withCookie('testing', 'abc123');
  1450. $this->assertEquals('abc123', $response->getCookie('testing')['value']);
  1451. $new = $response->withExpiredCookie('testing');
  1452. $this->assertNull($response->getCookie('testing')['expire']);
  1453. $this->assertEquals('1', $new->getCookie('testing')['expire']);
  1454. }
  1455. public function testWithExpiredCookieOptions()
  1456. {
  1457. $options = [
  1458. 'name' => 'testing',
  1459. 'value' => 'abc123',
  1460. 'domain' => 'cakephp.org',
  1461. 'path' => '/custompath/',
  1462. 'secure' => true,
  1463. 'httpOnly' => true,
  1464. 'expire' => (string)strtotime('+14 days'),
  1465. ];
  1466. $response = new Response();
  1467. $response = $response->withCookie('testing', $options);
  1468. $this->assertEquals($options, $response->getCookie('testing'));
  1469. $new = $response->withExpiredCookie('testing', $options);
  1470. $this->assertEquals($options['expire'], $response->getCookie('testing')['expire']);
  1471. $this->assertEquals('1', $new->getCookie('testing')['expire']);
  1472. $this->assertEquals('', $new->getCookie('testing')['value']);
  1473. }
  1474. public function testWithExpiredCookieObject()
  1475. {
  1476. $response = new Response();
  1477. $cookie = new Cookie('yay', 'a value');
  1478. $response = $response->withCookie($cookie);
  1479. $this->assertEquals('a value', $response->getCookie('yay')['value']);
  1480. $new = $response->withExpiredCookie($cookie);
  1481. $this->assertNull($response->getCookie('yay')['expire']);
  1482. $this->assertEquals('1', $new->getCookie('yay')['expire']);
  1483. }
  1484. /**
  1485. * Test getCookies() and array data.
  1486. *
  1487. * @return void
  1488. */
  1489. public function testGetCookies()
  1490. {
  1491. $response = new Response();
  1492. $new = $response->withCookie('testing', 'a')
  1493. ->withCookie('test2', ['value' => 'b', 'path' => '/test', 'secure' => true]);
  1494. $expected = [
  1495. 'testing' => [
  1496. 'name' => 'testing',
  1497. 'value' => 'a',
  1498. 'expire' => null,
  1499. 'path' => '/',
  1500. 'domain' => '',
  1501. 'secure' => false,
  1502. 'httpOnly' => false
  1503. ],
  1504. 'test2' => [
  1505. 'name' => 'test2',
  1506. 'value' => 'b',
  1507. 'expire' => null,
  1508. 'path' => '/test',
  1509. 'domain' => '',
  1510. 'secure' => true,
  1511. 'httpOnly' => false
  1512. ]
  1513. ];
  1514. $this->assertEquals($expected, $new->getCookies());
  1515. }
  1516. /**
  1517. * Test getCookies() and array data.
  1518. *
  1519. * @return void
  1520. */
  1521. public function testGetCookiesArrayValue()
  1522. {
  1523. $response = new Response();
  1524. $cookie = (new Cookie('urmc'))
  1525. ->withValue(['user_id' => 1, 'token' => 'abc123'])
  1526. ->withHttpOnly(true);
  1527. $new = $response->withCookie($cookie);
  1528. $expected = [
  1529. 'urmc' => [
  1530. 'name' => 'urmc',
  1531. 'value' => '{"user_id":1,"token":"abc123"}',
  1532. 'expire' => null,
  1533. 'path' => '',
  1534. 'domain' => '',
  1535. 'secure' => false,
  1536. 'httpOnly' => true
  1537. ],
  1538. ];
  1539. $this->assertEquals($expected, $new->getCookies());
  1540. }
  1541. /**
  1542. * Test getCookieCollection() as array data
  1543. *
  1544. * @return void
  1545. */
  1546. public function testGetCookieCollection()
  1547. {
  1548. $response = new Response();
  1549. $new = $response->withCookie('testing', 'a')
  1550. ->withCookie('test2', ['value' => 'b', 'path' => '/test', 'secure' => true]);
  1551. $cookies = $response->getCookieCollection();
  1552. $this->assertInstanceOf(CookieCollection::class, $cookies);
  1553. $this->assertCount(0, $cookies, 'Original response not mutated');
  1554. $cookies = $new->getCookieCollection();
  1555. $this->assertInstanceOf(CookieCollection::class, $cookies);
  1556. $this->assertCount(2, $cookies);
  1557. $this->assertTrue($cookies->has('testing'));
  1558. $this->assertTrue($cookies->has('test2'));
  1559. }
  1560. /**
  1561. * Test that cors() returns a builder.
  1562. *
  1563. * @return void
  1564. */
  1565. public function testCors()
  1566. {
  1567. $request = new ServerRequest([
  1568. 'environment' => ['HTTP_ORIGIN' => 'http://example.com']
  1569. ]);
  1570. $response = new Response();
  1571. $builder = $response->cors($request);
  1572. $this->assertInstanceOf(CorsBuilder::class, $builder);
  1573. $this->assertSame($response, $builder->build(), 'Empty builder returns same object');
  1574. }
  1575. /**
  1576. * Test CORS with additional parameters
  1577. *
  1578. * @group deprecated
  1579. * @dataProvider corsData
  1580. * @param Request $request
  1581. * @param string $origin
  1582. * @param string|array $domains
  1583. * @param string|array $methods
  1584. * @param string|array $headers
  1585. * @param string|bool $expectedOrigin
  1586. * @param string|bool $expectedMethods
  1587. * @param string|bool $expectedHeaders
  1588. * @return void
  1589. */
  1590. public function testCorsParameters($request, $origin, $domains, $methods, $headers, $expectedOrigin, $expectedMethods = false, $expectedHeaders = false)
  1591. {
  1592. $this->deprecated(function () use ($request, $origin, $domains, $methods, $headers, $expectedOrigin, $expectedMethods, $expectedHeaders) {
  1593. $request = $request->withEnv('HTTP_ORIGIN', $origin);
  1594. $response = new Response();
  1595. $result = $response->cors($request, $domains, $methods, $headers);
  1596. $this->assertInstanceOf('Cake\Network\CorsBuilder', $result);
  1597. if ($expectedOrigin) {
  1598. $this->assertTrue($response->hasHeader('Access-Control-Allow-Origin'));
  1599. $this->assertEquals($expectedOrigin, $response->getHeaderLine('Access-Control-Allow-Origin'));
  1600. }
  1601. if ($expectedMethods) {
  1602. $this->assertTrue($response->hasHeader('Access-Control-Allow-Methods'));
  1603. $this->assertEquals($expectedMethods, $response->getHeaderLine('Access-Control-Allow-Methods'));
  1604. }
  1605. if ($expectedHeaders) {
  1606. $this->assertTrue($response->hasHeader('Access-Control-Allow-Headers'));
  1607. $this->assertEquals($expectedHeaders, $response->getHeaderLine('Access-Control-Allow-Headers'));
  1608. }
  1609. });
  1610. }
  1611. /**
  1612. * Feed for testCors
  1613. *
  1614. * @return array
  1615. */
  1616. public function corsData()
  1617. {
  1618. $fooRequest = new ServerRequest();
  1619. $secureRequest = function () {
  1620. $secureRequest = $this->getMockBuilder('Cake\Http\ServerRequest')
  1621. ->setMethods(['is'])
  1622. ->getMock();
  1623. $secureRequest->expects($this->any())
  1624. ->method('is')
  1625. ->with('ssl')
  1626. ->will($this->returnValue(true));
  1627. return $secureRequest;
  1628. };
  1629. return [
  1630. [$fooRequest, null, '*', '', '', false, false],
  1631. [$fooRequest, 'http://www.foo.com', '*', '', '', '*', false],
  1632. [$fooRequest, 'http://www.foo.com', 'www.foo.com', '', '', 'http://www.foo.com', false],
  1633. [$fooRequest, 'http://www.foo.com', '*.foo.com', '', '', 'http://www.foo.com', false],
  1634. [$fooRequest, 'http://www.foo.com', 'http://*.foo.com', '', '', 'http://www.foo.com', false],
  1635. [$fooRequest, 'http://www.foo.com', 'https://www.foo.com', '', '', false, false],
  1636. [$fooRequest, 'http://www.foo.com', 'https://*.foo.com', '', '', false, false],
  1637. [$fooRequest, 'http://www.foo.com', ['*.bar.com', '*.foo.com'], '', '', 'http://www.foo.com', false],
  1638. [$fooRequest, 'http://not-foo.com', '*.foo.com', '', '', false, false],
  1639. [$fooRequest, 'http://bad.academy', '*.acad.my', '', '', false, false],
  1640. [$fooRequest, 'http://www.foo.com.at.bad.com', '*.foo.com', '', '', false, false],
  1641. [$fooRequest, 'https://www.foo.com', '*.foo.com', '', '', false, false],
  1642. [$secureRequest(), 'https://www.bar.com', 'www.bar.com', '', '', 'https://www.bar.com', false],
  1643. [$secureRequest(), 'https://www.bar.com', 'http://www.bar.com', '', '', false, false],
  1644. [$secureRequest(), 'https://www.bar.com', '*.bar.com', '', '', 'https://www.bar.com', false],
  1645. [$secureRequest(), 'http://www.bar.com', '*.bar.com', '', '', false, false],
  1646. [$fooRequest, 'http://www.foo.com', '*', 'GET', '', '*', 'GET'],
  1647. [$fooRequest, 'http://www.foo.com', '*.foo.com', 'GET', '', 'http://www.foo.com', 'GET'],
  1648. [$fooRequest, 'http://www.foo.com', '*.foo.com', ['GET', 'POST'], '', 'http://www.foo.com', 'GET, POST'],
  1649. [$fooRequest, 'http://www.foo.com', '*', '', 'X-CakePHP', '*', false, 'X-CakePHP'],
  1650. [$fooRequest, 'http://www.foo.com', '*', '', ['X-CakePHP', 'X-MyApp'], '*', false, 'X-CakePHP, X-MyApp'],
  1651. [$fooRequest, 'http://www.foo.com', '*', ['GET', 'OPTIONS'], ['X-CakePHP', 'X-MyApp'], '*', 'GET, OPTIONS', 'X-CakePHP, X-MyApp'],
  1652. ];
  1653. }
  1654. /**
  1655. * testFileNotFound
  1656. *
  1657. * @group deprecated
  1658. * @return void
  1659. */
  1660. public function testFileNotFound()
  1661. {
  1662. $this->expectException(\Cake\Http\Exception\NotFoundException::class);
  1663. $this->deprecated(function () {
  1664. $response = new Response();
  1665. $response->file('/some/missing/folder/file.jpg');
  1666. });
  1667. }
  1668. /**
  1669. * test withFile() not found
  1670. *
  1671. * @return void
  1672. */
  1673. public function testWithFileNotFound()
  1674. {
  1675. $this->expectException(\Cake\Http\Exception\NotFoundException::class);
  1676. $response = new Response();
  1677. $response->withFile('/some/missing/folder/file.jpg');
  1678. }
  1679. /**
  1680. * Provider for various kinds of unacceptable files.
  1681. *
  1682. * @return array
  1683. */
  1684. public function invalidFileProvider()
  1685. {
  1686. return [
  1687. ['my/../cat.gif', 'The requested file contains `..` and will not be read.'],
  1688. ['my\..\cat.gif', 'The requested file contains `..` and will not be read.'],
  1689. ['my/ca..t.gif', 'my/ca..t.gif was not found or not readable'],
  1690. ['my/ca..t/image.gif', 'my/ca..t/image.gif was not found or not readable'],
  1691. ];
  1692. }
  1693. /**
  1694. * test invalid file paths.
  1695. *
  1696. * @group deprecated
  1697. * @dataProvider invalidFileProvider
  1698. * @return void
  1699. */
  1700. public function testFileInvalidPath($path, $expectedMessage)
  1701. {
  1702. $this->deprecated(function () use ($path, $expectedMessage) {
  1703. $response = new Response();
  1704. try {
  1705. $response->file($path);
  1706. } catch (NotFoundException $e) {
  1707. $this->assertContains($expectedMessage, $e->getMessage());
  1708. }
  1709. });
  1710. }
  1711. /**
  1712. * test withFile and invalid paths
  1713. *
  1714. * @dataProvider invalidFileProvider
  1715. * @return void
  1716. */
  1717. public function testWithFileInvalidPath($path, $expectedMessage)
  1718. {
  1719. $response = new Response();
  1720. try {
  1721. $response->withFile($path);
  1722. } catch (NotFoundException $e) {
  1723. $this->assertContains($expectedMessage, $e->getMessage());
  1724. }
  1725. }
  1726. /**
  1727. * testFile method
  1728. *
  1729. * @group deprecated
  1730. * @return void
  1731. */
  1732. public function testFile()
  1733. {
  1734. $this->deprecated(function () {
  1735. $response = $this->getMockBuilder('Cake\Http\Response')
  1736. ->setMethods(['_sendHeader', '_isActive'])
  1737. ->getMock();
  1738. $response->expects($this->exactly(1))
  1739. ->method('_isActive')
  1740. ->will($this->returnValue(true));
  1741. $response->file(TEST_APP . 'vendor/css/test_asset.css');
  1742. ob_start();
  1743. $result = $response->send();
  1744. $this->assertTrue($result !== false);
  1745. $output = ob_get_clean();
  1746. $expected = '/* this is the test asset css file */';
  1747. $this->assertEquals($expected, trim($output));
  1748. $this->assertEquals($expected, trim($response->getBody()->getContents()));
  1749. $this->assertEquals('text/css', $response->getType());
  1750. $this->assertEquals('bytes', $response->getHeaderLine('Accept-Ranges'));
  1751. });
  1752. }
  1753. /**
  1754. * test withFile() + download & name
  1755. *
  1756. * @return void
  1757. */
  1758. public function testWithFileDownloadAndName()
  1759. {
  1760. $response = new Response();
  1761. $new = $response->withFile(
  1762. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1763. [
  1764. 'name' => 'something_special.css',
  1765. 'download' => true,
  1766. ]
  1767. );
  1768. $this->assertEquals(
  1769. 'text/html; charset=UTF-8',
  1770. $response->getHeaderLine('Content-Type'),
  1771. 'No mutation'
  1772. );
  1773. $this->assertEquals(
  1774. 'text/css; charset=UTF-8',
  1775. $new->getHeaderLine('Content-Type')
  1776. );
  1777. $this->assertEquals(
  1778. 'attachment; filename="something_special.css"',
  1779. $new->getHeaderLine('Content-Disposition')
  1780. );
  1781. $this->assertEquals('bytes', $new->getHeaderLine('Accept-Ranges'));
  1782. $this->assertEquals('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  1783. $body = $new->getBody();
  1784. $this->assertInstanceOf('Zend\Diactoros\Stream', $body);
  1785. $expected = '/* this is the test asset css file */';
  1786. $this->assertEquals($expected, trim($body->getContents()));
  1787. $this->assertEquals($expected, trim($new->getFile()->read()));
  1788. }
  1789. /**
  1790. * testFileWithDownloadAndName
  1791. *
  1792. * @group deprecated
  1793. * @return void
  1794. */
  1795. public function testFileWithDownloadAndName()
  1796. {
  1797. $this->deprecated(function () {
  1798. $response = $this->getMockBuilder('Cake\Http\Response')
  1799. ->setMethods(['download', '_sendHeader', '_isActive'])
  1800. ->getMock();
  1801. $response->expects($this->once())
  1802. ->method('download')
  1803. ->with('something_special.css');
  1804. $response->expects($this->exactly(1))
  1805. ->method('_isActive')
  1806. ->will($this->returnValue(true));
  1807. $response->file(
  1808. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1809. [
  1810. 'name' => 'something_special.css',
  1811. 'download' => true,
  1812. ]
  1813. );
  1814. ob_start();
  1815. $result = $response->send();
  1816. $output = ob_get_clean();
  1817. $this->assertEquals("/* this is the test asset css file */\n", $output);
  1818. $this->assertNotFalse($result);
  1819. $this->assertEquals('text/css', $response->getType());
  1820. $this->assertEquals('bytes', $response->getHeaderLine('Accept-Ranges'));
  1821. $this->assertEquals('binary', $response->getHeaderLine('Content-Transfer-Encoding'));
  1822. });
  1823. }
  1824. /**
  1825. * testFileWithUnknownFileTypeGeneric method
  1826. *
  1827. * @group deprecated
  1828. * @return void
  1829. */
  1830. public function testFileWithUnknownFileTypeGeneric()
  1831. {
  1832. $this->deprecated(function () {
  1833. $_SERVER['HTTP_USER_AGENT'] = 'Some generic browser';
  1834. $response = $this->getMockBuilder('Cake\Http\Response')
  1835. ->setMethods(['download', '_sendHeader', '_isActive'])
  1836. ->getMock();
  1837. $response->expects($this->once())
  1838. ->method('download')
  1839. ->with('no_section.ini');
  1840. $response->expects($this->exactly(1))
  1841. ->method('_isActive')
  1842. ->will($this->returnValue(true));
  1843. $response->file(CONFIG . 'no_section.ini');
  1844. ob_start();
  1845. $result = $response->send();
  1846. $output = ob_get_clean();
  1847. $this->assertEquals("some_key = some_value\nbool_key = 1\n", $output);
  1848. $this->assertNotFalse($result);
  1849. $this->assertEquals('text/html', $response->getType());
  1850. $this->assertEquals('bytes', $response->getHeaderLine('Accept-Ranges'));
  1851. $this->assertEquals('binary', $response->getHeaderLine('Content-Transfer-Encoding'));
  1852. });
  1853. }
  1854. /**
  1855. * test withFile() + a generic agent
  1856. *
  1857. * @return void
  1858. */
  1859. public function testWithFileUnknownFileTypeGeneric()
  1860. {
  1861. $response = new Response();
  1862. $new = $response->withFile(CONFIG . 'no_section.ini');
  1863. $this->assertEquals('text/html; charset=UTF-8', $new->getHeaderLine('Content-Type'));
  1864. $this->assertEquals(
  1865. 'attachment; filename="no_section.ini"',
  1866. $new->getHeaderLine('Content-Disposition')
  1867. );
  1868. $this->assertEquals('bytes', $new->getHeaderLine('Accept-Ranges'));
  1869. $body = $new->getBody();
  1870. $expected = "some_key = some_value\nbool_key = 1\n";
  1871. $this->assertEquals($expected, $body->getContents());
  1872. }
  1873. /**
  1874. * testFileWithUnknownFileTypeOpera method
  1875. *
  1876. * @group deprecated
  1877. * @return void
  1878. */
  1879. public function testFileWithUnknownFileTypeOpera()
  1880. {
  1881. $this->deprecated(function () {
  1882. $_SERVER['HTTP_USER_AGENT'] = 'Opera/9.80 (Windows NT 6.0; U; en) Presto/2.8.99 Version/11.10';
  1883. $response = $this->getMockBuilder('Cake\Http\Response')
  1884. ->setMethods(['download', '_sendHeader', '_isActive'])
  1885. ->getMock();
  1886. $response->expects($this->once())
  1887. ->method('download')
  1888. ->with('no_section.ini');
  1889. $response->expects($this->exactly(1))
  1890. ->method('_isActive')
  1891. ->will($this->returnValue(true));
  1892. $response->file(CONFIG . 'no_section.ini');
  1893. ob_start();
  1894. $result = $response->send();
  1895. $output = ob_get_clean();
  1896. $this->assertEquals("some_key = some_value\nbool_key = 1\n", $output);
  1897. $this->assertNotFalse($result);
  1898. $this->assertEquals('application/octet-stream', $response->getType());
  1899. $this->assertEquals('bytes', $response->getHeaderLine('Accept-Ranges'));
  1900. $this->assertEquals('binary', $response->getHeaderLine('Content-Transfer-Encoding'));
  1901. });
  1902. }
  1903. /**
  1904. * test withFile() + opera
  1905. *
  1906. * @return void
  1907. */
  1908. public function testWithFileUnknownFileTypeOpera()
  1909. {
  1910. $_SERVER['HTTP_USER_AGENT'] = 'Opera/9.80 (Windows NT 6.0; U; en) Presto/2.8.99 Version/11.10';
  1911. $response = new Response();
  1912. $new = $response->withFile(CONFIG . 'no_section.ini');
  1913. $this->assertEquals('application/octet-stream', $new->getHeaderLine('Content-Type'));
  1914. $this->assertEquals(
  1915. 'attachment; filename="no_section.ini"',
  1916. $new->getHeaderLine('Content-Disposition')
  1917. );
  1918. }
  1919. /**
  1920. * testFileWithUnknownFileTypeIE method
  1921. *
  1922. * @group deprecated
  1923. * @return void
  1924. */
  1925. public function testFileWithUnknownFileTypeIE()
  1926. {
  1927. $this->deprecated(function () {
  1928. $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; Media Center PC 4.0; SLCC1; .NET CLR 3.0.04320)';
  1929. $response = $this->getMockBuilder('Cake\Http\Response')
  1930. ->setMethods(['download', '_isActive', '_sendHeade'])
  1931. ->getMock();
  1932. $response->expects($this->once())
  1933. ->method('download')
  1934. ->with('config.ini');
  1935. $response->expects($this->exactly(1))
  1936. ->method('_isActive')
  1937. ->will($this->returnValue(true));
  1938. $response->file(CONFIG . 'no_section.ini', [
  1939. 'name' => 'config.ini'
  1940. ]);
  1941. ob_start();
  1942. $result = $response->send();
  1943. $output = ob_get_clean();
  1944. $this->assertEquals("some_key = some_value\nbool_key = 1\n", $output);
  1945. $this->assertNotFalse($result);
  1946. $this->assertEquals('application/force-download', $response->getType());
  1947. $this->assertEquals('bytes', $response->getHeaderLine('Accept-Ranges'));
  1948. $this->assertEquals('binary', $response->getHeaderLine('Content-Transfer-Encoding'));
  1949. });
  1950. }
  1951. /**
  1952. * test withFile() + old IE
  1953. *
  1954. * @return void
  1955. */
  1956. public function testWithFileUnknownFileTypeOldIe()
  1957. {
  1958. $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; Media Center PC 4.0; SLCC1; .NET CLR 3.0.04320)';
  1959. $response = new Response();
  1960. $new = $response->withFile(CONFIG . 'no_section.ini');
  1961. $this->assertEquals('application/force-download', $new->getHeaderLine('Content-Type'));
  1962. }
  1963. /**
  1964. * testFileWithUnknownFileNoDownload method
  1965. *
  1966. * @group deprecated
  1967. * @return void
  1968. */
  1969. public function testFileWithUnknownFileNoDownload()
  1970. {
  1971. $this->deprecated(function () {
  1972. $_SERVER['HTTP_USER_AGENT'] = 'Some generic browser';
  1973. $response = $this->getMockBuilder('Cake\Http\Response')
  1974. ->setMethods(['download'])
  1975. ->getMock();
  1976. $response->expects($this->never())
  1977. ->method('download');
  1978. $response->file(CONFIG . 'no_section.ini', [
  1979. 'download' => false
  1980. ]);
  1981. $this->assertEquals('bytes', $response->getHeaderLine('Accept-Ranges'));
  1982. $this->assertEquals('text/html', $response->getType());
  1983. });
  1984. }
  1985. /**
  1986. * test withFile() + no download
  1987. *
  1988. * @return void
  1989. */
  1990. public function testWithFileNoDownload()
  1991. {
  1992. $response = new Response();
  1993. $new = $response->withFile(CONFIG . 'no_section.ini', [
  1994. 'download' => false
  1995. ]);
  1996. $this->assertEquals(
  1997. 'text/html; charset=UTF-8',
  1998. $new->getHeaderLine('Content-Type')
  1999. );
  2000. $this->assertFalse($new->hasHeader('Content-Disposition'));
  2001. $this->assertFalse($new->hasHeader('Content-Transfer-Encoding'));
  2002. }
  2003. /**
  2004. * test getFile method
  2005. *
  2006. * @group deprecated
  2007. * @return void
  2008. */
  2009. public function testGetFile()
  2010. {
  2011. $this->deprecated(function () {
  2012. $response = new Response();
  2013. $this->assertNull($response->getFile(), 'No file to get');
  2014. $response->file(TEST_APP . 'vendor/css/test_asset.css');
  2015. $file = $response->getFile();
  2016. $this->assertInstanceOf('Cake\Filesystem\File', $file, 'Should get a file');
  2017. $this->assertPathEquals(TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css', $file->path);
  2018. });
  2019. }
  2020. /**
  2021. * testConnectionAbortedOnBuffering method
  2022. *
  2023. * @group deprecated
  2024. * @return void
  2025. */
  2026. public function testConnectionAbortedOnBuffering()
  2027. {
  2028. $this->deprecated(function () {
  2029. $response = $this->getMockBuilder('Cake\Http\Response')
  2030. ->setMethods([
  2031. 'download',
  2032. '_sendHeader',
  2033. '_isActive',
  2034. ])
  2035. ->getMock();
  2036. $response->expects($this->at(0))
  2037. ->method('_isActive')
  2038. ->will($this->returnValue(false));
  2039. $response->file(TEST_APP . 'vendor/css/test_asset.css');
  2040. ob_start();
  2041. $result = $response->send();
  2042. ob_end_clean();
  2043. $this->assertNull($result);
  2044. $this->assertEquals('text/css', $response->getType());
  2045. $this->assertFalse($response->hasHeader('Content-Range'));
  2046. });
  2047. }
  2048. /**
  2049. * Test downloading files with UPPERCASE extensions.
  2050. *
  2051. * @group deprecated
  2052. * @return void
  2053. */
  2054. public function testFileUpperExtension()
  2055. {
  2056. $this->deprecated(function () {
  2057. $response = new Response();
  2058. $response->file(TEST_APP . 'vendor/img/test_2.JPG');
  2059. $this->assertSame('image/jpeg', $response->getType());
  2060. });
  2061. }
  2062. /**
  2063. * Test that uppercase extensions result in correct content-types
  2064. *
  2065. * @return void
  2066. */
  2067. public function testWithFileUpperExtension()
  2068. {
  2069. $response = new Response();
  2070. $new = $response->withFile(TEST_APP . 'vendor/img/test_2.JPG');
  2071. $this->assertEquals('image/jpeg', $new->getHeaderLine('Content-Type'));
  2072. }
  2073. /**
  2074. * A data provider for testing various ranges
  2075. *
  2076. * @return array
  2077. */
  2078. public static function rangeProvider()
  2079. {
  2080. return [
  2081. // suffix-byte-range
  2082. [
  2083. 'bytes=-25', 25, 'bytes 13-37/38'
  2084. ],
  2085. [
  2086. 'bytes=0-', 38, 'bytes 0-37/38'
  2087. ],
  2088. [
  2089. 'bytes=10-', 28, 'bytes 10-37/38'
  2090. ],
  2091. [
  2092. 'bytes=10-20', 11, 'bytes 10-20/38'
  2093. ],
  2094. // Spaced out
  2095. [
  2096. 'bytes = 10 - 20', 11, 'bytes 10-20/38'
  2097. ],
  2098. ];
  2099. }
  2100. /**
  2101. * Test the various range offset types.
  2102. *
  2103. * @group deprecated
  2104. * @dataProvider rangeProvider
  2105. * @return void
  2106. */
  2107. public function testFileRangeOffsets($range, $length, $offsetResponse)
  2108. {
  2109. $this->deprecated(function () use ($range, $length, $offsetResponse) {
  2110. $_SERVER['HTTP_RANGE'] = $range;
  2111. $response = $this->getMockBuilder('Cake\Http\Response')
  2112. ->setMethods([
  2113. '_sendHeader',
  2114. '_isActive',
  2115. ])
  2116. ->getMock();
  2117. $response->expects($this->any())
  2118. ->method('_isActive')
  2119. ->will($this->returnValue(true));
  2120. $response->file(
  2121. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  2122. ['download' => true]
  2123. );
  2124. ob_start();
  2125. $result = $response->send();
  2126. ob_get_clean();
  2127. $this->assertEquals(
  2128. 'attachment; filename="test_asset.css"',
  2129. $response->getHeaderLine('Content-Disposition')
  2130. );
  2131. $this->assertEquals('binary', $response->getHeaderLine('Content-Transfer-Encoding'));
  2132. $this->assertEquals('bytes', $response->getHeaderLine('Accept-Ranges'));
  2133. $this->assertEquals($length, $response->getHeaderLine('Content-Length'));
  2134. $this->assertEquals($offsetResponse, $response->getHeaderLine('Content-Range'));
  2135. });
  2136. }
  2137. /**
  2138. * Test withFile() & the various range offset types.
  2139. *
  2140. * @dataProvider rangeProvider
  2141. * @return void
  2142. */
  2143. public function testWithFileRangeOffsets($range, $length, $offsetResponse)
  2144. {
  2145. $_SERVER['HTTP_RANGE'] = $range;
  2146. $response = new Response();
  2147. $new = $response->withFile(
  2148. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  2149. ['download' => true]
  2150. );
  2151. $this->assertEquals(
  2152. 'attachment; filename="test_asset.css"',
  2153. $new->getHeaderLine('Content-Disposition')
  2154. );
  2155. $this->assertEquals('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  2156. $this->assertEquals('bytes', $new->getHeaderLine('Accept-Ranges'));
  2157. $this->assertEquals($length, $new->getHeaderLine('Content-Length'));
  2158. $this->assertEquals($offsetResponse, $new->getHeaderLine('Content-Range'));
  2159. }
  2160. /**
  2161. * Test fetching ranges from a file.
  2162. *
  2163. * @group deprecated
  2164. * @return void
  2165. */
  2166. public function testFileRange()
  2167. {
  2168. $this->deprecated(function () {
  2169. $_SERVER['HTTP_RANGE'] = 'bytes=8-25';
  2170. $response = $this->getMockBuilder('Cake\Http\Response')
  2171. ->setMethods([
  2172. '_sendHeader',
  2173. '_isActive',
  2174. ])
  2175. ->getMock();
  2176. $response->expects($this->any())
  2177. ->method('_isActive')
  2178. ->will($this->returnValue(true));
  2179. $response->file(
  2180. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  2181. ['download' => true]
  2182. );
  2183. ob_start();
  2184. $result = $response->send();
  2185. $output = ob_get_clean();
  2186. $this->assertEquals('is the test asset ', $output);
  2187. $this->assertNotFalse($result);
  2188. $this->assertEquals(
  2189. 'attachment; filename="test_asset.css"',
  2190. $response->getHeaderLine('Content-Disposition')
  2191. );
  2192. $this->assertEquals('binary', $response->getHeaderLine('Content-Transfer-Encoding'));
  2193. $this->assertEquals('bytes', $response->getHeaderLine('Accept-Ranges'));
  2194. $this->assertEquals('18', $response->getHeaderLine('Content-Length'));
  2195. $this->assertEquals('bytes 8-25/38', $response->getHeaderLine('Content-Range'));
  2196. $this->assertEquals(206, $response->getStatusCode());
  2197. });
  2198. }
  2199. /**
  2200. * Test withFile() fetching ranges from a file.
  2201. *
  2202. * @return void
  2203. */
  2204. public function testWithFileRange()
  2205. {
  2206. $_SERVER['HTTP_RANGE'] = 'bytes=8-25';
  2207. $response = new Response();
  2208. $new = $response->withFile(
  2209. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  2210. ['download' => true]
  2211. );
  2212. $this->assertEquals(
  2213. 'attachment; filename="test_asset.css"',
  2214. $new->getHeaderLine('Content-Disposition')
  2215. );
  2216. $this->assertEquals('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  2217. $this->assertEquals('bytes', $new->getHeaderLine('Accept-Ranges'));
  2218. $this->assertEquals('18', $new->getHeaderLine('Content-Length'));
  2219. $this->assertEquals('bytes 8-25/38', $new->getHeaderLine('Content-Range'));
  2220. $this->assertEquals(206, $new->getStatusCode());
  2221. }
  2222. /**
  2223. * Provider for invalid range header values.
  2224. *
  2225. * @return array
  2226. */
  2227. public function invalidFileRangeProvider()
  2228. {
  2229. return [
  2230. // malformed range
  2231. [
  2232. 'bytes=0,38'
  2233. ],
  2234. // malformed punctuation
  2235. [
  2236. 'bytes: 0 - 38'
  2237. ],
  2238. ];
  2239. }
  2240. /**
  2241. * Test invalid file ranges.
  2242. *
  2243. * @group deprecated
  2244. * @dataProvider invalidFileRangeProvider
  2245. * @return void
  2246. */
  2247. public function testFileRangeInvalid($range)
  2248. {
  2249. $this->deprecated(function () use ($range) {
  2250. $_SERVER['HTTP_RANGE'] = $range;
  2251. $response = $this->getMockBuilder('Cake\Http\Response')
  2252. ->setMethods([
  2253. '_sendHeader',
  2254. '_isActive',
  2255. ])
  2256. ->getMock();
  2257. $response->file(
  2258. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  2259. ['download' => true]
  2260. );
  2261. $this->assertEquals('text/css', $response->getType());
  2262. $this->assertEquals(
  2263. 'attachment; filename="test_asset.css"',
  2264. $response->getHeaderLine('Content-Disposition')
  2265. );
  2266. $this->assertEquals('binary', $response->getHeaderLine('Content-Transfer-Encoding'));
  2267. $this->assertEquals('bytes', $response->getHeaderLine('Accept-Ranges'));
  2268. $this->assertEquals('38', $response->getHeaderLine('Content-Length'));
  2269. $this->assertEquals('bytes 0-37/38', $response->getHeaderLine('Content-Range'));
  2270. });
  2271. }
  2272. /**
  2273. * Test withFile() and invalid ranges
  2274. *
  2275. * @dataProvider invalidFileRangeProvider
  2276. * @return void
  2277. */
  2278. public function testWithFileInvalidRange($range)
  2279. {
  2280. $_SERVER['HTTP_RANGE'] = $range;
  2281. $response = new Response();
  2282. $new = $response->withFile(
  2283. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  2284. ['download' => true]
  2285. );
  2286. $this->assertEquals(
  2287. 'attachment; filename="test_asset.css"',
  2288. $new->getHeaderLine('Content-Disposition')
  2289. );
  2290. $this->assertEquals('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  2291. $this->assertEquals('bytes', $new->getHeaderLine('Accept-Ranges'));
  2292. $this->assertEquals('38', $new->getHeaderLine('Content-Length'));
  2293. $this->assertEquals('bytes 0-37/38', $new->getHeaderLine('Content-Range'));
  2294. $this->assertEquals(206, $new->getStatusCode());
  2295. }
  2296. /**
  2297. * Test reversed file ranges.
  2298. *
  2299. * @group deprecated
  2300. * @return void
  2301. */
  2302. public function testFileRangeReversed()
  2303. {
  2304. $this->deprecated(function () {
  2305. $_SERVER['HTTP_RANGE'] = 'bytes=30-2';
  2306. $response = $this->getMockBuilder('Cake\Http\Response')
  2307. ->setMethods([
  2308. '_sendHeader',
  2309. '_isActive',
  2310. ])
  2311. ->getMock();
  2312. $response->file(
  2313. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  2314. ['download' => true]
  2315. );
  2316. $this->assertEquals(416, $response->getStatusCode());
  2317. $this->assertEquals('bytes', $response->getHeaderLine('Accept-Ranges'));
  2318. $this->assertEquals(
  2319. 'attachment; filename="test_asset.css"',
  2320. $response->getHeaderLine('Content-Disposition')
  2321. );
  2322. $this->assertEquals('binary', $response->getHeaderLine('Content-Transfer-Encoding'));
  2323. $this->assertEquals('bytes 0-37/38', $response->getHeaderLine('Content-Range'));
  2324. });
  2325. }
  2326. /**
  2327. * Test withFile() and a reversed range
  2328. *
  2329. * @return void
  2330. */
  2331. public function testWithFileReversedRange()
  2332. {
  2333. $_SERVER['HTTP_RANGE'] = 'bytes=30-2';
  2334. $response = new Response();
  2335. $new = $response->withFile(
  2336. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  2337. ['download' => true]
  2338. );
  2339. $this->assertEquals(
  2340. 'attachment; filename="test_asset.css"',
  2341. $new->getHeaderLine('Content-Disposition')
  2342. );
  2343. $this->assertEquals('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  2344. $this->assertEquals('bytes', $new->getHeaderLine('Accept-Ranges'));
  2345. $this->assertEquals('bytes 0-37/38', $new->getHeaderLine('Content-Range'));
  2346. $this->assertEquals(416, $new->getStatusCode());
  2347. }
  2348. /**
  2349. * testFileRangeOffsetsNoDownload method
  2350. *
  2351. * @group deprecated
  2352. * @dataProvider rangeProvider
  2353. * @return void
  2354. */
  2355. public function testFileRangeOffsetsNoDownload($range, $length, $offsetResponse)
  2356. {
  2357. $this->deprecated(function () use ($range, $length, $offsetResponse) {
  2358. $_SERVER['HTTP_RANGE'] = $range;
  2359. $response = $this->getMockBuilder('Cake\Http\Response')
  2360. ->setMethods([
  2361. '_sendHeader',
  2362. '_isActive',
  2363. ])
  2364. ->getMock();
  2365. $response->expects($this->any())
  2366. ->method('_isActive')
  2367. ->will($this->returnValue(true));
  2368. $response->file(
  2369. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  2370. ['download' => false]
  2371. );
  2372. ob_start();
  2373. $result = $response->send();
  2374. ob_get_clean();
  2375. $this->assertEquals('bytes', $response->getHeaderLine('Accept-Ranges'));
  2376. $this->assertEquals($length, $response->getHeaderLine('Content-Length'));
  2377. $this->assertEquals($offsetResponse, $response->getHeaderLine('Content-Range'));
  2378. });
  2379. }
  2380. /**
  2381. * testFileRangeNoDownload method
  2382. *
  2383. * @group deprecated
  2384. * @return void
  2385. */
  2386. public function testFileRangeNoDownload()
  2387. {
  2388. $this->deprecated(function () {
  2389. $_SERVER['HTTP_RANGE'] = 'bytes=8-25';
  2390. $response = $this->getMockBuilder('Cake\Http\Response')
  2391. ->setMethods([
  2392. '_sendHeader',
  2393. '_isActive',
  2394. ])
  2395. ->getMock();
  2396. $response->expects($this->any())
  2397. ->method('_isActive')
  2398. ->will($this->returnValue(true));
  2399. $response->file(
  2400. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  2401. ['download' => false]
  2402. );
  2403. ob_start();
  2404. $result = $response->send();
  2405. $output = ob_get_clean();
  2406. $this->assertEquals('bytes', $response->getHeaderLine('Accept-Ranges'));
  2407. $this->assertEquals('18', $response->getHeaderLine('Content-Length'));
  2408. $this->assertEquals('bytes 8-25/38', $response->getHeaderLine('Content-Range'));
  2409. $this->assertEquals('text/css', $response->getType());
  2410. $this->assertEquals(206, $response->getStatusCode());
  2411. $this->assertEquals('is the test asset ', $output);
  2412. $this->assertNotFalse($result);
  2413. });
  2414. }
  2415. /**
  2416. * testFileRangeInvalidNoDownload method
  2417. *
  2418. * @group deprecated
  2419. * @return void
  2420. */
  2421. public function testFileRangeInvalidNoDownload()
  2422. {
  2423. $this->deprecated(function () {
  2424. $_SERVER['HTTP_RANGE'] = 'bytes=30-2';
  2425. $response = new Response();
  2426. $response->file(
  2427. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  2428. ['download' => false]
  2429. );
  2430. $this->assertEquals(416, $response->statusCode());
  2431. $this->assertEquals('bytes', $response->getHeaderLine('Accept-Ranges'));
  2432. $this->assertEquals('text/css', $response->getType());
  2433. $this->assertEquals('bytes 0-37/38', $response->getHeaderLine('Content-Range'));
  2434. });
  2435. }
  2436. /**
  2437. * Test the location method.
  2438. *
  2439. * @group deprecated
  2440. * @return void
  2441. */
  2442. public function testLocation()
  2443. {
  2444. $this->deprecated(function () {
  2445. $response = new Response();
  2446. $this->assertNull($response->location(), 'No header should be set.');
  2447. $this->assertNull($response->location('http://example.org'), 'Setting a location should return null');
  2448. $this->assertEquals('http://example.org', $response->location(), 'Reading a location should return the value.');
  2449. });
  2450. }
  2451. /**
  2452. * Test the withLocation method.
  2453. *
  2454. * @return void
  2455. */
  2456. public function testWithLocation()
  2457. {
  2458. $response = new Response();
  2459. $this->assertSame('', $response->getHeaderLine('Location'), 'No header should be set.');
  2460. $new = $response->withLocation('http://example.org');
  2461. $this->assertNotSame($new, $response);
  2462. $this->assertSame('', $response->getHeaderLine('Location'), 'No header should be set');
  2463. $this->assertSame('http://example.org', $new->getHeaderLine('Location'), 'Header should be set');
  2464. $this->assertSame(302, $new->getStatusCode(), 'Status should be updated');
  2465. }
  2466. /**
  2467. * Test get protocol version.
  2468. *
  2469. * @return void
  2470. */
  2471. public function getProtocolVersion()
  2472. {
  2473. $response = new Response();
  2474. $version = $response->getProtocolVersion();
  2475. $this->assertEquals('1.1', $version);
  2476. }
  2477. /**
  2478. * Test with protocol.
  2479. *
  2480. * @return void
  2481. */
  2482. public function testWithProtocol()
  2483. {
  2484. $response = new Response();
  2485. $version = $response->getProtocolVersion();
  2486. $this->assertEquals('1.1', $version);
  2487. $response2 = $response->withProtocolVersion('1.0');
  2488. $version = $response2->getProtocolVersion();
  2489. $this->assertEquals('1.0', $version);
  2490. $version = $response->getProtocolVersion();
  2491. $this->assertEquals('1.1', $version);
  2492. $this->assertNotEquals($response, $response2);
  2493. }
  2494. /**
  2495. * Test with protocol.
  2496. *
  2497. * @return void
  2498. */
  2499. public function testWithStatusCode()
  2500. {
  2501. $response = new Response();
  2502. $statusCode = $response->getStatusCode();
  2503. $this->assertEquals(200, $statusCode);
  2504. $response2 = $response->withStatus(404);
  2505. $statusCode = $response2->getStatusCode();
  2506. $this->assertEquals(404, $statusCode);
  2507. $statusCode = $response->getStatusCode();
  2508. $this->assertEquals(200, $statusCode);
  2509. $this->assertNotEquals($response, $response2);
  2510. }
  2511. /**
  2512. * Test get reason phrase.
  2513. *
  2514. * @return void
  2515. */
  2516. public function testGetReasonPhrase()
  2517. {
  2518. $response = new Response();
  2519. $this->assertSame('OK', $response->getReasonPhrase());
  2520. $response = $response->withStatus(404);
  2521. $reasonPhrase = $response->getReasonPhrase();
  2522. $this->assertEquals('Not Found', $reasonPhrase);
  2523. }
  2524. /**
  2525. * Test with body.
  2526. *
  2527. * @return void
  2528. */
  2529. public function testWithBody()
  2530. {
  2531. $response = new Response();
  2532. $body = $response->getBody();
  2533. $body->rewind();
  2534. $result = $body->getContents();
  2535. $this->assertEquals('', $result);
  2536. $stream = new Stream('php://memory', 'wb+');
  2537. $stream->write('test1');
  2538. $response2 = $response->withBody($stream);
  2539. $body = $response2->getBody();
  2540. $body->rewind();
  2541. $result = $body->getContents();
  2542. $this->assertEquals('test1', $result);
  2543. $body = $response->getBody();
  2544. $body->rewind();
  2545. $result = $body->getContents();
  2546. $this->assertEquals('', $result);
  2547. }
  2548. /**
  2549. * Test with string body.
  2550. *
  2551. * @return void
  2552. */
  2553. public function testWithStringBody()
  2554. {
  2555. $response = new Response();
  2556. $newResponse = $response->withStringBody('Foo');
  2557. $body = $newResponse->getBody();
  2558. $this->assertSame('Foo', (string)$body);
  2559. $this->assertNotSame($response, $newResponse);
  2560. $response = new Response();
  2561. $newResponse = $response->withStringBody('');
  2562. $body = $newResponse->getBody();
  2563. $this->assertSame('', (string)$body);
  2564. $this->assertNotSame($response, $newResponse);
  2565. $response = new Response();
  2566. $newResponse = $response->withStringBody(null);
  2567. $body = $newResponse->getBody();
  2568. $this->assertSame('', (string)$body);
  2569. $this->assertNotSame($response, $newResponse);
  2570. $response = new Response();
  2571. $newResponse = $response->withStringBody(1337);
  2572. $body = $newResponse->getBody();
  2573. $this->assertSame('1337', (string)$body);
  2574. $this->assertNotSame($response, $newResponse);
  2575. }
  2576. /**
  2577. * Test with string body with passed array.
  2578. *
  2579. * This should produce an "Array to string conversion" error
  2580. * which gets thrown as a \PHPUnit\Framework\Error\Error Exception by PHPUnit.
  2581. *
  2582. * @return void
  2583. */
  2584. public function testWithStringBodyArray()
  2585. {
  2586. $this->expectException(\PHPUnit\Framework\Error\Error::class);
  2587. $this->expectExceptionMessage('Array to string conversion');
  2588. $response = new Response();
  2589. $newResponse = $response->withStringBody(['foo' => 'bar']);
  2590. $body = $newResponse->getBody();
  2591. $this->assertSame('', (string)$body);
  2592. $this->assertNotSame($response, $newResponse);
  2593. }
  2594. /**
  2595. * Test get Body.
  2596. *
  2597. * @return void
  2598. */
  2599. public function testGetBody()
  2600. {
  2601. $response = new Response();
  2602. $stream = $response->getBody();
  2603. $this->assertInstanceOf('Psr\Http\Message\StreamInterface', $stream);
  2604. }
  2605. /**
  2606. * Test with header.
  2607. *
  2608. * @return void
  2609. */
  2610. public function testWithHeader()
  2611. {
  2612. $response = new Response();
  2613. $response2 = $response->withHeader('Accept', 'application/json');
  2614. $result = $response2->getHeaders();
  2615. $expected = [
  2616. 'Content-Type' => ['text/html; charset=UTF-8'],
  2617. 'Accept' => ['application/json']
  2618. ];
  2619. $this->assertEquals($expected, $result);
  2620. $this->assertFalse($response->hasHeader('Accept'));
  2621. }
  2622. /**
  2623. * Test get headers.
  2624. *
  2625. * @return void
  2626. */
  2627. public function testGetHeaders()
  2628. {
  2629. $response = new Response();
  2630. $headers = $response->getHeaders();
  2631. $response = $response->withAddedHeader('Location', 'localhost');
  2632. $response = $response->withAddedHeader('Accept', 'application/json');
  2633. $headers = $response->getHeaders();
  2634. $expected = [
  2635. 'Content-Type' => ['text/html; charset=UTF-8'],
  2636. 'Location' => ['localhost'],
  2637. 'Accept' => ['application/json']
  2638. ];
  2639. $this->assertEquals($expected, $headers);
  2640. }
  2641. /**
  2642. * Test without header.
  2643. *
  2644. * @return void
  2645. */
  2646. public function testWithoutHeader()
  2647. {
  2648. $response = new Response();
  2649. $response = $response->withAddedHeader('Location', 'localhost');
  2650. $response = $response->withAddedHeader('Accept', 'application/json');
  2651. $response2 = $response->withoutHeader('Location');
  2652. $headers = $response2->getHeaders();
  2653. $expected = [
  2654. 'Content-Type' => ['text/html; charset=UTF-8'],
  2655. 'Accept' => ['application/json']
  2656. ];
  2657. $this->assertEquals($expected, $headers);
  2658. }
  2659. /**
  2660. * Test get header.
  2661. *
  2662. * @return void
  2663. */
  2664. public function testGetHeader()
  2665. {
  2666. $response = new Response();
  2667. $response = $response->withAddedHeader('Location', 'localhost');
  2668. $result = $response->getHeader('Location');
  2669. $this->assertEquals(['localhost'], $result);
  2670. $result = $response->getHeader('location');
  2671. $this->assertEquals(['localhost'], $result);
  2672. $result = $response->getHeader('does-not-exist');
  2673. $this->assertEquals([], $result);
  2674. }
  2675. /**
  2676. * Test get header line.
  2677. *
  2678. * @return void
  2679. */
  2680. public function testGetHeaderLine()
  2681. {
  2682. $response = new Response();
  2683. $headers = $response->getHeaderLine('Accept');
  2684. $this->assertEquals('', $headers);
  2685. $response = $response->withAddedHeader('Accept', 'application/json');
  2686. $response = $response->withAddedHeader('Accept', 'application/xml');
  2687. $result = $response->getHeaderLine('Accept');
  2688. $expected = 'application/json,application/xml';
  2689. $this->assertEquals($expected, $result);
  2690. $result = $response->getHeaderLine('accept');
  2691. $this->assertEquals($expected, $result);
  2692. }
  2693. /**
  2694. * Test has header.
  2695. *
  2696. * @return void
  2697. */
  2698. public function testHasHeader()
  2699. {
  2700. $response = new Response();
  2701. $response = $response->withAddedHeader('Location', 'localhost');
  2702. $this->assertTrue($response->hasHeader('Location'));
  2703. $this->assertTrue($response->hasHeader('location'));
  2704. $this->assertTrue($response->hasHeader('locATIon'));
  2705. $this->assertFalse($response->hasHeader('Accept'));
  2706. $this->assertFalse($response->hasHeader('accept'));
  2707. }
  2708. /**
  2709. * Tests __debugInfo
  2710. *
  2711. * @return void
  2712. */
  2713. public function testDebugInfo()
  2714. {
  2715. $response = new Response();
  2716. $response = $response->withStringBody('Foo');
  2717. $result = $response->__debugInfo();
  2718. $expected = [
  2719. 'status' => 200,
  2720. 'contentType' => 'text/html',
  2721. 'headers' => [
  2722. 'Content-Type' => ['text/html; charset=UTF-8']
  2723. ],
  2724. 'file' => null,
  2725. 'fileRange' => [],
  2726. 'cookies' => new CookieCollection(),
  2727. 'cacheDirectives' => [],
  2728. 'body' => 'Foo'
  2729. ];
  2730. $this->assertEquals($expected, $result);
  2731. }
  2732. }