ResponseTest.php 103 KB

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