ResponseTest.php 101 KB

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