ResponseTest.php 104 KB

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