ResponseTest.php 105 KB

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