ResponseTest.php 102 KB

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