ResponseTest.php 102 KB

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