ResponseTest.php 104 KB

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