ResponseTest.php 101 KB

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