ResponseTest.php 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 2.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Http;
  17. include_once CORE_TEST_CASES . DS . 'Http' . DS . 'server_mocks.php';
  18. use Cake\Core\Configure;
  19. use Cake\Http\Cookie\Cookie;
  20. use Cake\Http\Cookie\CookieCollection;
  21. use Cake\Http\CorsBuilder;
  22. use Cake\Http\Exception\NotFoundException;
  23. use Cake\Http\Response;
  24. use Cake\Http\ServerRequest;
  25. use Cake\I18n\FrozenTime;
  26. use Cake\TestSuite\TestCase;
  27. use DateTime as NativeDateTime;
  28. use DateTimeImmutable;
  29. use DateTimeZone;
  30. use InvalidArgumentException;
  31. use Laminas\Diactoros\Stream;
  32. /**
  33. * ResponseTest
  34. */
  35. class ResponseTest extends TestCase
  36. {
  37. /**
  38. * SERVER variable backup.
  39. *
  40. * @var array
  41. */
  42. protected $server = [];
  43. /**
  44. * setup
  45. */
  46. public function setUp(): void
  47. {
  48. parent::setUp();
  49. $this->server = $_SERVER;
  50. }
  51. /**
  52. * teardown
  53. */
  54. public function tearDown(): void
  55. {
  56. parent::tearDown();
  57. $_SERVER = $this->server;
  58. unset($GLOBALS['mockedHeadersSent']);
  59. }
  60. /**
  61. * Tests the request object constructor
  62. */
  63. public function testConstruct(): void
  64. {
  65. $response = new Response();
  66. $this->assertSame('', (string)$response->getBody());
  67. $this->assertSame('UTF-8', $response->getCharset());
  68. $this->assertSame('text/html', $response->getType());
  69. $this->assertSame('text/html; charset=UTF-8', $response->getHeaderLine('Content-Type'));
  70. $this->assertSame(200, $response->getStatusCode());
  71. $options = [
  72. 'body' => 'This is the body',
  73. 'charset' => 'my-custom-charset',
  74. 'type' => 'mp3',
  75. 'status' => 203,
  76. ];
  77. $response = new Response($options);
  78. $this->assertSame('This is the body', (string)$response->getBody());
  79. $this->assertSame('my-custom-charset', $response->getCharset());
  80. $this->assertSame('audio/mpeg', $response->getType());
  81. $this->assertSame('audio/mpeg', $response->getHeaderLine('Content-Type'));
  82. $this->assertSame(203, $response->getStatusCode());
  83. }
  84. /**
  85. * Tests the getCharset/withCharset methods
  86. */
  87. public function testWithCharset(): void
  88. {
  89. $response = new Response();
  90. $this->assertSame('text/html; charset=UTF-8', $response->getHeaderLine('Content-Type'));
  91. $new = $response->withCharset('iso-8859-1');
  92. $this->assertStringNotContainsString('iso', $response->getHeaderLine('Content-Type'), 'Old instance not changed');
  93. $this->assertSame('iso-8859-1', $new->getCharset());
  94. $this->assertSame('text/html; charset=iso-8859-1', $new->getHeaderLine('Content-Type'));
  95. }
  96. /**
  97. * Tests the getType method
  98. */
  99. public function testGetType(): void
  100. {
  101. $response = new Response();
  102. $this->assertSame('text/html', $response->getType());
  103. $this->assertSame(
  104. 'application/pdf',
  105. $response->withType('pdf')->getType()
  106. );
  107. $this->assertSame(
  108. 'custom/stuff',
  109. $response->withType('custom/stuff')->getType()
  110. );
  111. $this->assertSame(
  112. 'application/json',
  113. $response->withType('json')->getType()
  114. );
  115. }
  116. public function testSetTypeMap(): void
  117. {
  118. $response = new Response();
  119. $response->setTypeMap('ical', 'text/calendar');
  120. $response = $response->withType('ical')->getType();
  121. $this->assertSame('text/calendar', $response);
  122. }
  123. public function testSetTypeMapAsArray(): void
  124. {
  125. $response = new Response();
  126. $response->setTypeMap('ical', ['text/calendar']);
  127. $response = $response->withType('ical')->getType();
  128. $this->assertSame('text/calendar', $response);
  129. }
  130. /**
  131. * Tests the withType method
  132. */
  133. public function testWithTypeAlias(): void
  134. {
  135. $response = new Response();
  136. $this->assertSame(
  137. 'text/html; charset=UTF-8',
  138. $response->getHeaderLine('Content-Type'),
  139. 'Default content-type should match'
  140. );
  141. $new = $response->withType('pdf');
  142. $this->assertNotSame($new, $response, 'Should be a new instance');
  143. $this->assertSame(
  144. 'text/html; charset=UTF-8',
  145. $response->getHeaderLine('Content-Type'),
  146. 'Original object should not be modified'
  147. );
  148. $this->assertSame('application/pdf', $new->getHeaderLine('Content-Type'));
  149. $json = $new->withType('json');
  150. $this->assertSame('application/json', $json->getHeaderLine('Content-Type'));
  151. $this->assertSame('application/json', $json->getType());
  152. }
  153. /**
  154. * test withType() and full mime-types
  155. */
  156. public function withTypeFull(): void
  157. {
  158. $response = new Response();
  159. $this->assertSame(
  160. 'application/json',
  161. $response->withType('application/json')->getHeaderLine('Content-Type'),
  162. 'Should not add charset to explicit type'
  163. );
  164. $this->assertSame(
  165. 'custom/stuff',
  166. $response->withType('custom/stuff')->getHeaderLine('Content-Type'),
  167. 'Should allow arbitrary types'
  168. );
  169. $this->assertSame(
  170. 'text/html; charset=UTF-8',
  171. $response->withType('text/html; charset=UTF-8')->getHeaderLine('Content-Type'),
  172. 'Should allow charset types'
  173. );
  174. }
  175. /**
  176. * Test that an invalid type raises an exception
  177. */
  178. public function testWithTypeInvalidType(): void
  179. {
  180. $this->expectException(InvalidArgumentException::class);
  181. $this->expectExceptionMessage('"beans" is an invalid content type');
  182. $response = new Response();
  183. $response->withType('beans');
  184. }
  185. /**
  186. * Data provider for content type tests.
  187. *
  188. * @return array
  189. */
  190. public static function charsetTypeProvider(): array
  191. {
  192. return [
  193. ['mp3', 'audio/mpeg'],
  194. ['js', 'application/javascript; charset=UTF-8'],
  195. ['xml', 'application/xml; charset=UTF-8'],
  196. ['txt', 'text/plain; charset=UTF-8'],
  197. ];
  198. }
  199. /**
  200. * Test that setting certain status codes clears the status code.
  201. */
  202. public function testWithStatusClearsContentType(): void
  203. {
  204. $response = new Response();
  205. $new = $response->withType('pdf')
  206. ->withStatus(204);
  207. $this->assertFalse($new->hasHeader('Content-Type'));
  208. $this->assertSame('', $new->getType());
  209. $this->assertSame(204, $new->getStatusCode(), 'Status code should clear content-type');
  210. $response = new Response();
  211. $new = $response->withStatus(304)
  212. ->withType('pdf');
  213. $this->assertSame('', $new->getType());
  214. $this->assertFalse(
  215. $new->hasHeader('Content-Type'),
  216. 'Type should not be retained because of status code.'
  217. );
  218. $response = new Response();
  219. $new = $response
  220. ->withHeader('Content-Type', 'application/json')
  221. ->withStatus(204);
  222. $this->assertFalse($new->hasHeader('Content-Type'), 'Should clear direct header');
  223. $this->assertSame('', $new->getType());
  224. }
  225. /**
  226. * Test that setting status codes doesn't overwrite content-type
  227. */
  228. public function testWithStatusDoesNotChangeContentType(): void
  229. {
  230. $response = new Response();
  231. $new = $response->withHeader('Content-Type', 'application/json')
  232. ->withStatus(403);
  233. $this->assertSame('application/json', $new->getHeaderLine('Content-Type'));
  234. $this->assertSame(403, $new->getStatusCode());
  235. $response = new Response();
  236. $new = $response->withStatus(403)
  237. ->withHeader('Content-Type', 'application/json');
  238. $this->assertSame('application/json', $new->getHeaderLine('Content-Type'));
  239. $this->assertSame(403, $new->getStatusCode());
  240. $this->assertSame('application/json', $new->getType());
  241. }
  242. /**
  243. * Tests the withDisabledCache method
  244. */
  245. public function testWithDisabledCache(): void
  246. {
  247. $response = new Response();
  248. $expected = [
  249. 'Expires' => ['Mon, 26 Jul 1997 05:00:00 GMT'],
  250. 'Last-Modified' => [gmdate(DATE_RFC7231)],
  251. 'Cache-Control' => ['no-store, no-cache, must-revalidate, post-check=0, pre-check=0'],
  252. 'Content-Type' => ['text/html; charset=UTF-8'],
  253. ];
  254. $new = $response->withDisabledCache();
  255. $this->assertFalse($response->hasHeader('Expires'), 'Old instance not mutated.');
  256. $this->assertEquals($expected, $new->getHeaders());
  257. }
  258. /**
  259. * Tests the withCache method
  260. */
  261. public function testWithCache(): void
  262. {
  263. $response = new Response();
  264. $since = $time = time();
  265. $new = $response->withCache($since, $time);
  266. $this->assertFalse($response->hasHeader('Date'));
  267. $this->assertFalse($response->hasHeader('Last-Modified'));
  268. $this->assertSame(gmdate(DATE_RFC7231, $since), $new->getHeaderLine('Date'));
  269. $this->assertSame(gmdate(DATE_RFC7231, $since), $new->getHeaderLine('Last-Modified'));
  270. $this->assertSame(gmdate(DATE_RFC7231, $time), $new->getHeaderLine('Expires'));
  271. $this->assertSame('public, max-age=0', $new->getHeaderLine('Cache-Control'));
  272. }
  273. /**
  274. * Tests the compress method
  275. */
  276. public function testCompress(): void
  277. {
  278. $response = new Response();
  279. if (ini_get('zlib.output_compression') === '1' || !extension_loaded('zlib')) {
  280. $this->assertFalse($response->compress());
  281. $this->markTestSkipped('Is not possible to test output compression');
  282. }
  283. $_SERVER['HTTP_ACCEPT_ENCODING'] = '';
  284. $result = $response->compress();
  285. $this->assertFalse($result);
  286. $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip';
  287. $result = $response->compress();
  288. $this->assertTrue($result);
  289. $this->assertContains('ob_gzhandler', ob_list_handlers());
  290. ob_get_clean();
  291. }
  292. /**
  293. * Tests the withDownload method
  294. */
  295. public function testWithDownload(): void
  296. {
  297. $response = new Response();
  298. $new = $response->withDownload('myfile.mp3');
  299. $this->assertFalse($response->hasHeader('Content-Disposition'), 'No mutation');
  300. $expected = 'attachment; filename="myfile.mp3"';
  301. $this->assertSame($expected, $new->getHeaderLine('Content-Disposition'));
  302. }
  303. /**
  304. * Tests the mapType method
  305. */
  306. public function testMapType(): void
  307. {
  308. $response = new Response();
  309. $this->assertSame('wav', $response->mapType('audio/x-wav'));
  310. $this->assertSame('pdf', $response->mapType('application/pdf'));
  311. $this->assertSame('xml', $response->mapType('text/xml'));
  312. $this->assertSame('html', $response->mapType('*/*'));
  313. $this->assertSame('csv', $response->mapType('application/vnd.ms-excel'));
  314. $expected = ['json', 'xhtml', 'css'];
  315. $result = $response->mapType(['application/json', 'application/xhtml+xml', 'text/css']);
  316. $this->assertEquals($expected, $result);
  317. }
  318. /**
  319. * Tests the outputCompressed method
  320. */
  321. public function testOutputCompressed(): void
  322. {
  323. $response = new Response();
  324. $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip';
  325. $result = $response->outputCompressed();
  326. $this->assertFalse($result);
  327. $_SERVER['HTTP_ACCEPT_ENCODING'] = '';
  328. $result = $response->outputCompressed();
  329. $this->assertFalse($result);
  330. if (!extension_loaded('zlib')) {
  331. $this->markTestSkipped('Skipping further tests for outputCompressed as zlib extension is not loaded');
  332. }
  333. if (ini_get('zlib.output_compression') !== '1') {
  334. ob_start('ob_gzhandler');
  335. }
  336. $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip';
  337. $result = $response->outputCompressed();
  338. $this->assertTrue($result);
  339. $_SERVER['HTTP_ACCEPT_ENCODING'] = '';
  340. $result = $response->outputCompressed();
  341. $this->assertFalse($result);
  342. if (ini_get('zlib.output_compression') !== '1') {
  343. ob_get_clean();
  344. }
  345. }
  346. /**
  347. * Tests settings the content length
  348. */
  349. public function testWithLength(): void
  350. {
  351. $response = new Response();
  352. $this->assertFalse($response->hasHeader('Content-Length'));
  353. $new = $response->withLength(100);
  354. $this->assertFalse($response->hasHeader('Content-Length'), 'Old instance not modified');
  355. $this->assertSame('100', $new->getHeaderLine('Content-Length'));
  356. }
  357. /**
  358. * Tests settings the link
  359. */
  360. public function testWithAddedLink(): void
  361. {
  362. $response = new Response();
  363. $this->assertFalse($response->hasHeader('Link'));
  364. $new = $response->withAddedLink('http://example.com', ['rel' => 'prev']);
  365. $this->assertFalse($response->hasHeader('Link'), 'Old instance not modified');
  366. $this->assertSame('<http://example.com>; rel="prev"', $new->getHeaderLine('Link'));
  367. $new = $response->withAddedLink('http://example.com');
  368. $this->assertSame('<http://example.com>', $new->getHeaderLine('Link'));
  369. $new = $response->withAddedLink('http://example.com?p=1', ['rel' => 'prev'])
  370. ->withAddedLink('http://example.com?p=2', ['rel' => 'next', 'foo' => 'bar']);
  371. $this->assertSame('<http://example.com?p=1>; rel="prev",<http://example.com?p=2>; rel="next"; foo="bar"', $new->getHeaderLine('Link'));
  372. }
  373. /**
  374. * Tests the withExpires method
  375. */
  376. public function testWithExpires(): void
  377. {
  378. $response = new Response();
  379. $now = new NativeDateTime('now', new DateTimeZone('America/Los_Angeles'));
  380. $new = $response->withExpires($now);
  381. $this->assertFalse($response->hasHeader('Expires'));
  382. $now->setTimeZone(new DateTimeZone('UTC'));
  383. $this->assertSame($now->format(DATE_RFC7231), $new->getHeaderLine('Expires'));
  384. $now = time();
  385. $new = $response->withExpires($now);
  386. $this->assertSame(gmdate(DATE_RFC7231), $new->getHeaderLine('Expires'));
  387. $time = new NativeDateTime('+1 day', new DateTimeZone('UTC'));
  388. $new = $response->withExpires('+1 day');
  389. $this->assertSame($time->format(DATE_RFC7231), $new->getHeaderLine('Expires'));
  390. }
  391. /**
  392. * Tests the withModified method
  393. */
  394. public function testWithModified(): void
  395. {
  396. $response = new Response();
  397. $now = new NativeDateTime('now', new DateTimeZone('America/Los_Angeles'));
  398. $new = $response->withModified($now);
  399. $this->assertFalse($response->hasHeader('Last-Modified'));
  400. $now->setTimeZone(new DateTimeZone('UTC'));
  401. $this->assertSame($now->format(DATE_RFC7231), $new->getHeaderLine('Last-Modified'));
  402. $now = time();
  403. $new = $response->withModified($now);
  404. $this->assertSame(gmdate(DATE_RFC7231, $now), $new->getHeaderLine('Last-Modified'));
  405. $now = new DateTimeImmutable();
  406. $new = $response->withModified($now);
  407. $this->assertSame(gmdate(DATE_RFC7231, $now->getTimestamp()), $new->getHeaderLine('Last-Modified'));
  408. $time = new NativeDateTime('+1 day', new DateTimeZone('UTC'));
  409. $new = $response->withModified('+1 day');
  410. $this->assertSame($time->format(DATE_RFC7231), $new->getHeaderLine('Last-Modified'));
  411. }
  412. /**
  413. * Tests withSharable()
  414. */
  415. public function testWithSharable(): void
  416. {
  417. $response = new Response();
  418. $new = $response->withSharable(true);
  419. $this->assertFalse($response->hasHeader('Cache-Control'), 'old instance unchanged');
  420. $this->assertSame('public', $new->getHeaderLine('Cache-Control'));
  421. $new = $response->withSharable(false);
  422. $this->assertSame('private', $new->getHeaderLine('Cache-Control'));
  423. $new = $response->withSharable(true, 3600);
  424. $this->assertSame('public, max-age=3600', $new->getHeaderLine('Cache-Control'));
  425. $new = $response->withSharable(false, 3600);
  426. $this->assertSame('private, max-age=3600', $new->getHeaderLine('Cache-Control'));
  427. }
  428. /**
  429. * Tests withMaxAge()
  430. */
  431. public function testWithMaxAge(): void
  432. {
  433. $response = new Response();
  434. $this->assertFalse($response->hasHeader('Cache-Control'));
  435. $new = $response->withMaxAge(3600);
  436. $this->assertSame('max-age=3600', $new->getHeaderLine('Cache-Control'));
  437. $new = $response->withMaxAge(3600)
  438. ->withSharable(false);
  439. $this->assertSame('max-age=3600, private', $new->getHeaderLine('Cache-Control'));
  440. }
  441. /**
  442. * Tests setting of s-maxage Cache-Control directive
  443. */
  444. public function testWithSharedMaxAge(): void
  445. {
  446. $response = new Response();
  447. $new = $response->withSharedMaxAge(3600);
  448. $this->assertFalse($response->hasHeader('Cache-Control'));
  449. $this->assertSame('s-maxage=3600', $new->getHeaderLine('Cache-Control'));
  450. $new = $response->withSharedMaxAge(3600)->withSharable(true);
  451. $this->assertSame('s-maxage=3600, public', $new->getHeaderLine('Cache-Control'));
  452. }
  453. /**
  454. * Tests setting of must-revalidate Cache-Control directive
  455. */
  456. public function testWithMustRevalidate(): void
  457. {
  458. $response = new Response();
  459. $this->assertFalse($response->hasHeader('Cache-Control'));
  460. $new = $response->withMustRevalidate(true);
  461. $this->assertFalse($response->hasHeader('Cache-Control'));
  462. $this->assertSame('must-revalidate', $new->getHeaderLine('Cache-Control'));
  463. $new = $new->withMustRevalidate(false);
  464. $this->assertEmpty($new->getHeaderLine('Cache-Control'));
  465. }
  466. /**
  467. * Tests withVary()
  468. */
  469. public function testWithVary(): void
  470. {
  471. $response = new Response();
  472. $new = $response->withVary('Accept-encoding');
  473. $this->assertFalse($response->hasHeader('Vary'));
  474. $this->assertSame('Accept-encoding', $new->getHeaderLine('Vary'));
  475. $new = $response->withVary(['Accept-encoding', 'Accept-language']);
  476. $this->assertFalse($response->hasHeader('Vary'));
  477. $this->assertSame('Accept-encoding,Accept-language', $new->getHeaderLine('Vary'));
  478. }
  479. /**
  480. * Tests withEtag()
  481. */
  482. public function testWithEtag(): void
  483. {
  484. $response = new Response();
  485. $new = $response->withEtag('something');
  486. $this->assertFalse($response->hasHeader('Etag'));
  487. $this->assertSame('"something"', $new->getHeaderLine('Etag'));
  488. $new = $response->withEtag('something', true);
  489. $this->assertSame('W/"something"', $new->getHeaderLine('Etag'));
  490. }
  491. /**
  492. * Tests that the response is able to be marked as not modified
  493. */
  494. public function testNotModified(): void
  495. {
  496. $response = new Response();
  497. $response = $response->withStringBody('something')
  498. ->withStatus(200)
  499. ->withLength(100)
  500. ->withModified('now');
  501. $this->deprecated(function () use ($response) {
  502. $response->notModified();
  503. });
  504. $this->assertFalse($response->hasHeader('Content-Length'));
  505. $this->assertFalse($response->hasHeader('Modified'));
  506. $this->assertEmpty((string)$response->getBody());
  507. $this->assertSame(304, $response->getStatusCode());
  508. }
  509. /**
  510. * Tests withNotModified()
  511. */
  512. public function testWithNotModified(): void
  513. {
  514. $response = new Response(['body' => 'something']);
  515. $response = $response->withLength(100)
  516. ->withStatus(200)
  517. ->withHeader('Last-Modified', 'value')
  518. ->withHeader('Content-Language', 'en-EN')
  519. ->withHeader('X-things', 'things')
  520. ->withType('application/json');
  521. $new = $response->withNotModified();
  522. $this->assertTrue($response->hasHeader('Content-Language'), 'old instance not changed');
  523. $this->assertTrue($response->hasHeader('Content-Length'), 'old instance not changed');
  524. $this->assertFalse($new->hasHeader('Content-Type'));
  525. $this->assertFalse($new->hasHeader('Content-Length'));
  526. $this->assertFalse($new->hasHeader('Content-Language'));
  527. $this->assertFalse($new->hasHeader('Last-Modified'));
  528. $this->assertSame('things', $new->getHeaderLine('X-things'), 'Other headers are retained');
  529. $this->assertSame(304, $new->getStatusCode());
  530. $this->assertSame('', $new->getBody()->getContents());
  531. }
  532. /**
  533. * Test checkNotModified method
  534. */
  535. public function testCheckNotModifiedByEtagStar(): void
  536. {
  537. $request = new ServerRequest();
  538. $request = $request->withHeader('If-None-Match', '*');
  539. $response = new Response();
  540. $response = $response->withEtag('something')
  541. ->withHeader('Content-Length', 99);
  542. $this->assertTrue($response->isNotModified($request));
  543. $this->deprecated(function () use ($response, $request) {
  544. $this->assertTrue($response->checkNotModified($request));
  545. $this->assertFalse($response->hasHeader('Content-Type'), 'etags match, should be unmodified');
  546. });
  547. }
  548. /**
  549. * Test checkNotModified method
  550. */
  551. public function testCheckNotModifiedByEtagExact(): void
  552. {
  553. $request = new ServerRequest();
  554. $request = $request->withHeader('If-None-Match', 'W/"something", "other"');
  555. $response = new Response();
  556. $response = $response->withEtag('something', true)
  557. ->withHeader('Content-Length', 99);
  558. $this->assertTrue($response->isNotModified($request));
  559. $this->deprecated(function () use ($request, $response) {
  560. $this->assertTrue($response->checkNotModified($request));
  561. $this->assertFalse($response->hasHeader('Content-Type'), 'etags match, should be unmodified');
  562. });
  563. }
  564. /**
  565. * Test checkNotModified method
  566. */
  567. public function testCheckNotModifiedByEtagAndTime(): void
  568. {
  569. $request = new ServerRequest();
  570. $request = $request->withHeader('If-Modified-Since', '2012-01-01 00:00:00')
  571. ->withHeader('If-None-Match', 'W/"something", "other"');
  572. $response = new Response();
  573. $response = $response->withModified('2012-01-01 00:00:00')
  574. ->withEtag('something', true)
  575. ->withHeader('Content-Length', 99);
  576. $this->assertTrue($response->isNotModified($request));
  577. $this->deprecated(function () use ($request, $response) {
  578. $this->assertTrue($response->checkNotModified($request));
  579. $this->assertFalse($response->hasHeader('Content-Length'), 'etags match, should be unmodified');
  580. });
  581. }
  582. /**
  583. * Test checkNotModified method
  584. */
  585. public function testCheckNotModifiedByEtagAndTimeMismatch(): void
  586. {
  587. $request = new ServerRequest();
  588. $request = $request->withHeader('If-Modified-Since', '2012-01-01 00:00:00')
  589. ->withHeader('If-None-Match', 'W/"something", "other"');
  590. $response = new Response();
  591. $response = $response->withModified('2012-01-01 00:00:01')
  592. ->withEtag('something', true)
  593. ->withHeader('Content-Length', 99);
  594. $this->assertFalse($response->isNotModified($request));
  595. $this->deprecated(function () use ($request, $response) {
  596. $this->assertFalse($response->checkNotModified($request));
  597. $this->assertTrue($response->hasHeader('Content-Length'), 'timestamp in response is newer');
  598. });
  599. }
  600. /**
  601. * Test checkNotModified method
  602. */
  603. public function testCheckNotModifiedByEtagMismatch(): void
  604. {
  605. $request = new ServerRequest();
  606. $request = $request->withHeader('If-Modified-Since', '2012-01-01 00:00:00')
  607. ->withHeader('If-None-Match', 'W/"something-else", "other"');
  608. $response = new Response();
  609. $response = $response->withModified('2012-01-01 00:00:00')
  610. ->withEtag('something', true)
  611. ->withHeader('Content-Length', 99);
  612. $this->assertFalse($response->isNotModified($request));
  613. $this->deprecated(function () use ($request, $response) {
  614. $this->assertFalse($response->checkNotModified($request));
  615. $this->assertTrue($response->hasHeader('Content-Length'), 'etags do not match');
  616. });
  617. }
  618. /**
  619. * Test checkNotModified method
  620. */
  621. public function testCheckNotModifiedByTime(): void
  622. {
  623. $request = new ServerRequest();
  624. $request = $request->withHeader('If-Modified-Since', '2012-01-01 00:00:00');
  625. $response = new Response();
  626. $response = $response->withModified('2012-01-01 00:00:00')
  627. ->withHeader('Content-Length', 99);
  628. $this->assertTrue($response->isNotModified($request));
  629. $this->deprecated(function () use ($request, $response) {
  630. $this->assertTrue($response->checkNotModified($request));
  631. $this->assertFalse($response->hasHeader('Content-Length'), 'modified time matches');
  632. });
  633. }
  634. /**
  635. * Test checkNotModified method
  636. */
  637. public function testCheckNotModifiedNoHints(): void
  638. {
  639. $request = new ServerRequest();
  640. $request = $request->withHeader('If-None-Match', 'W/"something", "other"')
  641. ->withHeader('If-Modified-Since', '2012-01-01 00:00:00');
  642. $response = new Response();
  643. $this->assertFalse($response->isNotModified($request));
  644. $this->deprecated(function () use ($request, $response) {
  645. $this->assertFalse($response->checkNotModified($request));
  646. $this->assertSame(200, $response->getStatusCode());
  647. });
  648. }
  649. /**
  650. * Test setting cookies with no value
  651. */
  652. public function testWithCookieEmpty(): void
  653. {
  654. $response = new Response();
  655. $new = $response->withCookie(new Cookie('testing'));
  656. $this->assertNull($response->getCookie('testing'), 'withCookie does not mutate');
  657. $expected = [
  658. 'name' => 'testing',
  659. 'value' => '',
  660. 'expires' => 0,
  661. 'path' => '/',
  662. 'domain' => '',
  663. 'secure' => false,
  664. 'httponly' => false,
  665. ];
  666. $result = $new->getCookie('testing');
  667. $this->assertEquals($expected, $result);
  668. }
  669. /**
  670. * Test setting cookies with scalar values
  671. */
  672. public function testWithCookieScalar(): void
  673. {
  674. $response = new Response();
  675. $new = $response->withCookie(new Cookie('testing', 'abc123'));
  676. $this->assertNull($response->getCookie('testing'), 'withCookie does not mutate');
  677. $this->assertSame('abc123', $new->getCookie('testing')['value']);
  678. $new = $response->withCookie(new Cookie('testing', 99));
  679. $this->assertSame(99, $new->getCookie('testing')['value']);
  680. $new = $response->withCookie(new Cookie('testing', false));
  681. $this->assertFalse($new->getCookie('testing')['value']);
  682. $new = $response->withCookie(new Cookie('testing', true));
  683. $this->assertTrue($new->getCookie('testing')['value']);
  684. }
  685. /**
  686. * Test withCookie() and duplicate data
  687. *
  688. * @throws \Exception
  689. */
  690. public function testWithDuplicateCookie(): void
  691. {
  692. $expiry = new DateTimeImmutable('+24 hours');
  693. $response = new Response();
  694. $cookie = new Cookie(
  695. 'testing',
  696. '[a,b,c]',
  697. $expiry,
  698. '/test',
  699. '',
  700. true
  701. );
  702. $new = $response->withCookie($cookie);
  703. $this->assertNull($response->getCookie('testing'), 'withCookie does not mutate');
  704. $expected = [
  705. 'name' => 'testing',
  706. 'value' => '[a,b,c]',
  707. 'expires' => $expiry,
  708. 'path' => '/test',
  709. 'domain' => '',
  710. 'secure' => true,
  711. 'httponly' => false,
  712. ];
  713. // Match the date time formatting to Response::convertCookieToArray
  714. $expected['expires'] = $expiry->format('U');
  715. $this->assertEquals($expected, $new->getCookie('testing'));
  716. }
  717. /**
  718. * Test withCookie() and a cookie instance
  719. */
  720. public function testWithCookieObject(): void
  721. {
  722. $response = new Response();
  723. $cookie = new Cookie('yay', 'a value');
  724. $new = $response->withCookie($cookie);
  725. $this->assertNull($response->getCookie('yay'), 'withCookie does not mutate');
  726. $this->assertNotEmpty($new->getCookie('yay'));
  727. $this->assertSame($cookie, $new->getCookieCollection()->get('yay'));
  728. }
  729. public function testWithExpiredCookieScalar(): void
  730. {
  731. $response = new Response();
  732. $response = $response->withCookie(new Cookie('testing', 'abc123'));
  733. $this->assertSame('abc123', $response->getCookie('testing')['value']);
  734. $new = $response->withExpiredCookie(new Cookie('testing'));
  735. $this->assertSame(0, $response->getCookie('testing')['expires']);
  736. $this->assertLessThan(FrozenTime::createFromTimestamp(1), (string)$new->getCookie('testing')['expires']);
  737. }
  738. /**
  739. * @throws \Exception If DateImmutable emits an error.
  740. */
  741. public function testWithExpiredCookieOptions(): void
  742. {
  743. $options = [
  744. 'name' => 'testing',
  745. 'value' => 'abc123',
  746. 'options' => [
  747. 'domain' => 'cakephp.org',
  748. 'path' => '/custompath/',
  749. 'secure' => true,
  750. 'httponly' => true,
  751. 'expires' => new DateTimeImmutable('+14 days'),
  752. ],
  753. ];
  754. $cookie = Cookie::create(
  755. $options['name'],
  756. $options['value'],
  757. $options['options']
  758. );
  759. $response = new Response();
  760. $response = $response->withCookie($cookie);
  761. $options['options']['expires'] = $options['options']['expires']->format('U');
  762. $expected = ['name' => $options['name'], 'value' => $options['value']] + $options['options'];
  763. $this->assertEquals($expected, $response->getCookie('testing'));
  764. $expiredCookie = $response->withExpiredCookie($cookie);
  765. $this->assertSame($expected['expires'], (string)$response->getCookie('testing')['expires']);
  766. $this->assertLessThan(FrozenTime::createFromTimestamp(1), (string)$expiredCookie->getCookie('testing')['expires']);
  767. }
  768. public function testWithExpiredCookieObject(): void
  769. {
  770. $response = new Response();
  771. $cookie = new Cookie('yay', 'a value');
  772. $response = $response->withCookie($cookie);
  773. $this->assertSame('a value', $response->getCookie('yay')['value']);
  774. $new = $response->withExpiredCookie($cookie);
  775. $this->assertSame(0, $response->getCookie('yay')['expires']);
  776. $this->assertSame(1, $new->getCookie('yay')['expires']);
  777. }
  778. public function testWithExpiredCookieNotUtc()
  779. {
  780. date_default_timezone_set('Europe/Paris');
  781. $response = new Response();
  782. $cookie = new Cookie('yay', 'a value');
  783. $response = $response->withExpiredCookie($cookie);
  784. date_default_timezone_set('UTC');
  785. $this->assertSame(1, $response->getCookie('yay')['expires']);
  786. }
  787. /**
  788. * Test getCookies() and array data.
  789. */
  790. public function testGetCookies(): void
  791. {
  792. $response = new Response();
  793. $new = $response->withCookie(new Cookie('testing', 'a'))
  794. ->withCookie(new Cookie('test2', 'b', null, '/test', '', true));
  795. $expected = [
  796. 'testing' => [
  797. 'name' => 'testing',
  798. 'value' => 'a',
  799. 'expires' => 0,
  800. 'path' => '/',
  801. 'domain' => '',
  802. 'secure' => false,
  803. 'httponly' => false,
  804. ],
  805. 'test2' => [
  806. 'name' => 'test2',
  807. 'value' => 'b',
  808. 'expires' => 0,
  809. 'path' => '/test',
  810. 'domain' => '',
  811. 'secure' => true,
  812. 'httponly' => false,
  813. ],
  814. ];
  815. $this->assertEquals($expected, $new->getCookies());
  816. }
  817. /**
  818. * Test getCookies() and array data.
  819. */
  820. public function testGetCookiesArrayValue(): void
  821. {
  822. $response = new Response();
  823. $cookie = (new Cookie('urmc'))
  824. ->withValue(['user_id' => 1, 'token' => 'abc123'])
  825. ->withHttpOnly(true);
  826. $new = $response->withCookie($cookie);
  827. $expected = [
  828. 'urmc' => [
  829. 'name' => 'urmc',
  830. 'value' => '{"user_id":1,"token":"abc123"}',
  831. 'expires' => 0,
  832. 'path' => '/',
  833. 'domain' => '',
  834. 'secure' => false,
  835. 'httponly' => true,
  836. ],
  837. ];
  838. $this->assertEquals($expected, $new->getCookies());
  839. }
  840. /**
  841. * Test getCookieCollection() as array data
  842. */
  843. public function testGetCookieCollection(): void
  844. {
  845. $response = new Response();
  846. $new = $response->withCookie(new Cookie('testing', 'a'))
  847. ->withCookie(new Cookie('test2', 'b', null, '/test', '', true));
  848. $cookies = $response->getCookieCollection();
  849. $this->assertInstanceOf(CookieCollection::class, $cookies);
  850. $this->assertCount(0, $cookies, 'Original response not mutated');
  851. $cookies = $new->getCookieCollection();
  852. $this->assertInstanceOf(CookieCollection::class, $cookies);
  853. $this->assertCount(2, $cookies);
  854. $this->assertTrue($cookies->has('testing'));
  855. $this->assertTrue($cookies->has('test2'));
  856. }
  857. /**
  858. * Test withCookieCollection()
  859. */
  860. public function testWithCookieCollection(): void
  861. {
  862. $response = new Response();
  863. $collection = new CookieCollection([new Cookie('foo', 'bar')]);
  864. $newResponse = $response->withCookieCollection($collection);
  865. $this->assertNotSame($response, $newResponse);
  866. $this->assertNotSame($response->getCookieCollection(), $newResponse->getCookieCollection());
  867. $this->assertSame($newResponse->getCookie('foo')['value'], 'bar');
  868. }
  869. /**
  870. * Test that cors() returns a builder.
  871. */
  872. public function testCors(): void
  873. {
  874. $request = new ServerRequest([
  875. 'environment' => ['HTTP_ORIGIN' => 'http://example.com'],
  876. ]);
  877. $response = new Response();
  878. $builder = $response->cors($request);
  879. $this->assertInstanceOf(CorsBuilder::class, $builder);
  880. $this->assertSame($response, $builder->build(), 'Empty builder returns same object');
  881. }
  882. /**
  883. * test withFile() not found
  884. */
  885. public function testWithFileNotFound(): void
  886. {
  887. $this->expectException(NotFoundException::class);
  888. $this->expectExceptionMessage('The requested file /some/missing/folder/file.jpg was not found');
  889. $response = new Response();
  890. $response->withFile('/some/missing/folder/file.jpg');
  891. }
  892. /**
  893. * test withFile() not found
  894. */
  895. public function testWithFileNotFoundNoDebug(): void
  896. {
  897. Configure::write('debug', 0);
  898. $this->expectException(NotFoundException::class);
  899. $this->expectExceptionMessage('The requested file was not found');
  900. $response = new Response();
  901. $response->withFile('/some/missing/folder/file.jpg');
  902. }
  903. /**
  904. * Provider for various kinds of unacceptable files.
  905. *
  906. * @return array
  907. */
  908. public function invalidFileProvider(): array
  909. {
  910. return [
  911. ['my/../cat.gif', 'The requested file contains `..` and will not be read.'],
  912. ['my\..\cat.gif', 'The requested file contains `..` and will not be read.'],
  913. ['my/ca..t.gif', 'my/ca..t.gif was not found or not readable'],
  914. ['my/ca..t/image.gif', 'my/ca..t/image.gif was not found or not readable'],
  915. ];
  916. }
  917. /**
  918. * test withFile and invalid paths
  919. *
  920. * @dataProvider invalidFileProvider
  921. */
  922. public function testWithFileInvalidPath(string $path, string $expectedMessage): void
  923. {
  924. $this->expectException(NotFoundException::class);
  925. $this->expectExceptionMessage($expectedMessage);
  926. $response = new Response();
  927. $response->withFile($path);
  928. }
  929. /**
  930. * test withFile() + download & name
  931. */
  932. public function testWithFileDownloadAndName(): void
  933. {
  934. $response = new Response();
  935. $new = $response->withFile(
  936. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  937. [
  938. 'name' => 'something_special.css',
  939. 'download' => true,
  940. ]
  941. );
  942. $this->assertSame(
  943. 'text/html; charset=UTF-8',
  944. $response->getHeaderLine('Content-Type'),
  945. 'No mutation'
  946. );
  947. $this->assertSame(
  948. 'text/css; charset=UTF-8',
  949. $new->getHeaderLine('Content-Type')
  950. );
  951. $this->assertSame(
  952. 'attachment; filename="something_special.css"',
  953. $new->getHeaderLine('Content-Disposition')
  954. );
  955. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  956. $this->assertSame('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  957. $body = $new->getBody();
  958. $this->assertInstanceOf('Laminas\Diactoros\Stream', $body);
  959. $expected = '/* this is the test asset css file */';
  960. $this->assertSame($expected, trim($body->getContents()));
  961. $file = $new->getFile()->openFile();
  962. $this->assertSame($expected, trim($file->fread(100)));
  963. }
  964. /**
  965. * test withFile() + a generic agent
  966. */
  967. public function testWithFileUnknownFileTypeGeneric(): void
  968. {
  969. $response = new Response();
  970. $new = $response->withFile(CONFIG . 'no_section.ini');
  971. $this->assertSame('text/html; charset=UTF-8', $new->getHeaderLine('Content-Type'));
  972. $this->assertSame(
  973. 'attachment; filename="no_section.ini"',
  974. $new->getHeaderLine('Content-Disposition')
  975. );
  976. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  977. $body = $new->getBody();
  978. $expected = "some_key = some_value\nbool_key = 1\n";
  979. $this->assertSame($expected, $body->getContents());
  980. }
  981. /**
  982. * test withFile() + opera
  983. */
  984. public function testWithFileUnknownFileTypeOpera(): void
  985. {
  986. $_SERVER['HTTP_USER_AGENT'] = 'Opera/9.80 (Windows NT 6.0; U; en) Presto/2.8.99 Version/11.10';
  987. $response = new Response();
  988. $new = $response->withFile(CONFIG . 'no_section.ini');
  989. $this->assertSame('application/octet-stream', $new->getHeaderLine('Content-Type'));
  990. $this->assertSame(
  991. 'attachment; filename="no_section.ini"',
  992. $new->getHeaderLine('Content-Disposition')
  993. );
  994. }
  995. /**
  996. * test withFile() + old IE
  997. */
  998. public function testWithFileUnknownFileTypeOldIe(): void
  999. {
  1000. $_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)';
  1001. $response = new Response();
  1002. $new = $response->withFile(CONFIG . 'no_section.ini');
  1003. $this->assertSame('application/force-download', $new->getHeaderLine('Content-Type'));
  1004. }
  1005. /**
  1006. * test withFile() + no download
  1007. */
  1008. public function testWithFileNoDownload(): void
  1009. {
  1010. $response = new Response();
  1011. $new = $response->withFile(CONFIG . 'no_section.ini', [
  1012. 'download' => false,
  1013. ]);
  1014. $this->assertSame(
  1015. 'text/html; charset=UTF-8',
  1016. $new->getHeaderLine('Content-Type')
  1017. );
  1018. $this->assertFalse($new->hasHeader('Content-Disposition'));
  1019. $this->assertFalse($new->hasHeader('Content-Transfer-Encoding'));
  1020. }
  1021. /**
  1022. * Test that uppercase extensions result in correct content-types
  1023. */
  1024. public function testWithFileUpperExtension(): void
  1025. {
  1026. $response = new Response();
  1027. $new = $response->withFile(TEST_APP . 'vendor/img/test_2.JPG');
  1028. $this->assertSame('image/jpeg', $new->getHeaderLine('Content-Type'));
  1029. }
  1030. /**
  1031. * A data provider for testing various ranges
  1032. *
  1033. * @return array
  1034. */
  1035. public static function rangeProvider(): array
  1036. {
  1037. return [
  1038. // suffix-byte-range
  1039. [
  1040. 'bytes=-25', 25, 'bytes 13-37/38',
  1041. ],
  1042. [
  1043. 'bytes=0-', 38, 'bytes 0-37/38',
  1044. ],
  1045. [
  1046. 'bytes=10-', 28, 'bytes 10-37/38',
  1047. ],
  1048. [
  1049. 'bytes=10-20', 11, 'bytes 10-20/38',
  1050. ],
  1051. // Spaced out
  1052. [
  1053. 'bytes = 10 - 20', 11, 'bytes 10-20/38',
  1054. ],
  1055. ];
  1056. }
  1057. /**
  1058. * Test withFile() & the various range offset types.
  1059. *
  1060. * @dataProvider rangeProvider
  1061. */
  1062. public function testWithFileRangeOffsets(string $range, int $length, string $offsetResponse): void
  1063. {
  1064. $_SERVER['HTTP_RANGE'] = $range;
  1065. $response = new Response();
  1066. $new = $response->withFile(
  1067. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1068. ['download' => true]
  1069. );
  1070. $this->assertSame(
  1071. 'attachment; filename="test_asset.css"',
  1072. $new->getHeaderLine('Content-Disposition')
  1073. );
  1074. $this->assertSame('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  1075. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  1076. $this->assertEquals($length, $new->getHeaderLine('Content-Length'));
  1077. $this->assertEquals($offsetResponse, $new->getHeaderLine('Content-Range'));
  1078. }
  1079. /**
  1080. * Test withFile() fetching ranges from a file.
  1081. */
  1082. public function testWithFileRange(): void
  1083. {
  1084. $_SERVER['HTTP_RANGE'] = 'bytes=8-25';
  1085. $response = new Response();
  1086. $new = $response->withFile(
  1087. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1088. ['download' => true]
  1089. );
  1090. $this->assertSame(
  1091. 'attachment; filename="test_asset.css"',
  1092. $new->getHeaderLine('Content-Disposition')
  1093. );
  1094. $this->assertSame('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  1095. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  1096. $this->assertSame('18', $new->getHeaderLine('Content-Length'));
  1097. $this->assertSame('bytes 8-25/38', $new->getHeaderLine('Content-Range'));
  1098. $this->assertSame(206, $new->getStatusCode());
  1099. }
  1100. /**
  1101. * Provider for invalid range header values.
  1102. *
  1103. * @return array
  1104. */
  1105. public function invalidFileRangeProvider(): array
  1106. {
  1107. return [
  1108. // malformed range
  1109. [
  1110. 'bytes=0,38',
  1111. ],
  1112. // malformed punctuation
  1113. [
  1114. 'bytes: 0 - 38',
  1115. ],
  1116. ];
  1117. }
  1118. /**
  1119. * Test withFile() and invalid ranges
  1120. *
  1121. * @dataProvider invalidFileRangeProvider
  1122. */
  1123. public function testWithFileInvalidRange(string $range): void
  1124. {
  1125. $_SERVER['HTTP_RANGE'] = $range;
  1126. $response = new Response();
  1127. $new = $response->withFile(
  1128. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1129. ['download' => true]
  1130. );
  1131. $this->assertSame(
  1132. 'attachment; filename="test_asset.css"',
  1133. $new->getHeaderLine('Content-Disposition')
  1134. );
  1135. $this->assertSame('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  1136. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  1137. $this->assertSame('38', $new->getHeaderLine('Content-Length'));
  1138. $this->assertSame('bytes 0-37/38', $new->getHeaderLine('Content-Range'));
  1139. $this->assertSame(206, $new->getStatusCode());
  1140. }
  1141. /**
  1142. * Test withFile() and a reversed range
  1143. */
  1144. public function testWithFileReversedRange(): void
  1145. {
  1146. $_SERVER['HTTP_RANGE'] = 'bytes=30-2';
  1147. $response = new Response();
  1148. $new = $response->withFile(
  1149. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1150. ['download' => true]
  1151. );
  1152. $this->assertSame(
  1153. 'attachment; filename="test_asset.css"',
  1154. $new->getHeaderLine('Content-Disposition')
  1155. );
  1156. $this->assertSame('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  1157. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  1158. $this->assertSame('bytes 0-37/38', $new->getHeaderLine('Content-Range'));
  1159. $this->assertSame(416, $new->getStatusCode());
  1160. }
  1161. /**
  1162. * Test the withLocation method.
  1163. */
  1164. public function testWithLocation(): void
  1165. {
  1166. $response = new Response();
  1167. $this->assertSame('', $response->getHeaderLine('Location'), 'No header should be set.');
  1168. $new = $response->withLocation('http://example.org');
  1169. $this->assertNotSame($new, $response);
  1170. $this->assertSame('', $response->getHeaderLine('Location'), 'No header should be set');
  1171. $this->assertSame('http://example.org', $new->getHeaderLine('Location'), 'Header should be set');
  1172. $this->assertSame(302, $new->getStatusCode(), 'Status should be updated');
  1173. }
  1174. /**
  1175. * Test get protocol version.
  1176. */
  1177. public function getProtocolVersion(): void
  1178. {
  1179. $response = new Response();
  1180. $version = $response->getProtocolVersion();
  1181. $this->assertSame('1.1', $version);
  1182. }
  1183. /**
  1184. * Test with protocol.
  1185. */
  1186. public function testWithProtocol(): void
  1187. {
  1188. $response = new Response();
  1189. $version = $response->getProtocolVersion();
  1190. $this->assertSame('1.1', $version);
  1191. $response2 = $response->withProtocolVersion('1.0');
  1192. $version = $response2->getProtocolVersion();
  1193. $this->assertSame('1.0', $version);
  1194. $version = $response->getProtocolVersion();
  1195. $this->assertSame('1.1', $version);
  1196. $this->assertNotEquals($response, $response2);
  1197. }
  1198. /**
  1199. * Test with status code.
  1200. */
  1201. public function testWithStatusCode(): void
  1202. {
  1203. $response = new Response();
  1204. $statusCode = $response->getStatusCode();
  1205. $this->assertSame(200, $statusCode);
  1206. $response2 = $response->withStatus(404);
  1207. $statusCode = $response2->getStatusCode();
  1208. $this->assertSame(404, $statusCode);
  1209. $statusCode = $response->getStatusCode();
  1210. $this->assertSame(200, $statusCode);
  1211. $this->assertNotEquals($response, $response2);
  1212. $response3 = $response->withStatus(111);
  1213. $this->assertSame(111, $response3->getStatusCode());
  1214. $this->assertSame('', $response3->getReasonPhrase());
  1215. }
  1216. /**
  1217. * Test invalid status codes
  1218. */
  1219. public function testWithStatusInvalid(): void
  1220. {
  1221. $this->expectException(InvalidArgumentException::class);
  1222. $this->expectExceptionMessage('Invalid status code: 1001. Use a valid HTTP status code in range 1xx - 5xx.');
  1223. $response = new Response();
  1224. $response->withStatus(1001);
  1225. }
  1226. /**
  1227. * Test get reason phrase.
  1228. */
  1229. public function testGetReasonPhrase(): void
  1230. {
  1231. $response = new Response();
  1232. $this->assertSame('OK', $response->getReasonPhrase());
  1233. $response = $response->withStatus(404);
  1234. $reasonPhrase = $response->getReasonPhrase();
  1235. $this->assertSame('Not Found', $reasonPhrase);
  1236. }
  1237. /**
  1238. * Test with body.
  1239. */
  1240. public function testWithBody(): void
  1241. {
  1242. $response = new Response();
  1243. $body = $response->getBody();
  1244. $body->rewind();
  1245. $result = $body->getContents();
  1246. $this->assertSame('', $result);
  1247. $stream = new Stream('php://memory', 'wb+');
  1248. $stream->write('test1');
  1249. $response2 = $response->withBody($stream);
  1250. $body = $response2->getBody();
  1251. $body->rewind();
  1252. $result = $body->getContents();
  1253. $this->assertSame('test1', $result);
  1254. $body = $response->getBody();
  1255. $body->rewind();
  1256. $result = $body->getContents();
  1257. $this->assertSame('', $result);
  1258. }
  1259. /**
  1260. * Test with string body.
  1261. */
  1262. public function testWithStringBody(): void
  1263. {
  1264. $response = new Response();
  1265. $newResponse = $response->withStringBody('Foo');
  1266. $body = $newResponse->getBody();
  1267. $this->assertSame('Foo', (string)$body);
  1268. $this->assertNotSame($response, $newResponse);
  1269. $response = new Response();
  1270. $newResponse = $response->withStringBody('');
  1271. $body = $newResponse->getBody();
  1272. $this->assertSame('', (string)$body);
  1273. $this->assertNotSame($response, $newResponse);
  1274. $response = new Response();
  1275. $newResponse = $response->withStringBody(null);
  1276. $body = $newResponse->getBody();
  1277. $this->assertSame('', (string)$body);
  1278. $this->assertNotSame($response, $newResponse);
  1279. $response = new Response();
  1280. $newResponse = $response->withStringBody('1337');
  1281. $body = $newResponse->getBody();
  1282. $this->assertSame('1337', (string)$body);
  1283. $this->assertNotSame($response, $newResponse);
  1284. }
  1285. /**
  1286. * Test get Body.
  1287. */
  1288. public function testGetBody(): void
  1289. {
  1290. $response = new Response();
  1291. $stream = $response->getBody();
  1292. $this->assertInstanceOf('Psr\Http\Message\StreamInterface', $stream);
  1293. }
  1294. /**
  1295. * Test with header.
  1296. */
  1297. public function testWithHeader(): void
  1298. {
  1299. $response = new Response();
  1300. $response2 = $response->withHeader('Accept', 'application/json');
  1301. $result = $response2->getHeaders();
  1302. $expected = [
  1303. 'Content-Type' => ['text/html; charset=UTF-8'],
  1304. 'Accept' => ['application/json'],
  1305. ];
  1306. $this->assertEquals($expected, $result);
  1307. $this->assertFalse($response->hasHeader('Accept'));
  1308. }
  1309. /**
  1310. * Test get headers.
  1311. */
  1312. public function testGetHeaders(): void
  1313. {
  1314. $response = new Response();
  1315. $headers = $response->getHeaders();
  1316. $response = $response->withAddedHeader('Location', 'localhost');
  1317. $response = $response->withAddedHeader('Accept', 'application/json');
  1318. $headers = $response->getHeaders();
  1319. $expected = [
  1320. 'Content-Type' => ['text/html; charset=UTF-8'],
  1321. 'Location' => ['localhost'],
  1322. 'Accept' => ['application/json'],
  1323. ];
  1324. $this->assertEquals($expected, $headers);
  1325. }
  1326. /**
  1327. * Test without header.
  1328. */
  1329. public function testWithoutHeader(): void
  1330. {
  1331. $response = new Response();
  1332. $response = $response->withAddedHeader('Location', 'localhost');
  1333. $response = $response->withAddedHeader('Accept', 'application/json');
  1334. $response2 = $response->withoutHeader('Location');
  1335. $headers = $response2->getHeaders();
  1336. $expected = [
  1337. 'Content-Type' => ['text/html; charset=UTF-8'],
  1338. 'Accept' => ['application/json'],
  1339. ];
  1340. $this->assertEquals($expected, $headers);
  1341. }
  1342. /**
  1343. * Test get header.
  1344. */
  1345. public function testGetHeader(): void
  1346. {
  1347. $response = new Response();
  1348. $response = $response->withAddedHeader('Location', 'localhost');
  1349. $result = $response->getHeader('Location');
  1350. $this->assertEquals(['localhost'], $result);
  1351. $result = $response->getHeader('location');
  1352. $this->assertEquals(['localhost'], $result);
  1353. $result = $response->getHeader('does-not-exist');
  1354. $this->assertEquals([], $result);
  1355. }
  1356. /**
  1357. * Test get header line.
  1358. */
  1359. public function testGetHeaderLine(): void
  1360. {
  1361. $response = new Response();
  1362. $headers = $response->getHeaderLine('Accept');
  1363. $this->assertSame('', $headers);
  1364. $response = $response->withAddedHeader('Accept', 'application/json');
  1365. $response = $response->withAddedHeader('Accept', 'application/xml');
  1366. $result = $response->getHeaderLine('Accept');
  1367. $expected = 'application/json,application/xml';
  1368. $this->assertSame($expected, $result);
  1369. $result = $response->getHeaderLine('accept');
  1370. $this->assertSame($expected, $result);
  1371. }
  1372. /**
  1373. * Test has header.
  1374. */
  1375. public function testHasHeader(): void
  1376. {
  1377. $response = new Response();
  1378. $response = $response->withAddedHeader('Location', 'localhost');
  1379. $this->assertTrue($response->hasHeader('Location'));
  1380. $this->assertTrue($response->hasHeader('location'));
  1381. $this->assertTrue($response->hasHeader('locATIon'));
  1382. $this->assertFalse($response->hasHeader('Accept'));
  1383. $this->assertFalse($response->hasHeader('accept'));
  1384. }
  1385. /**
  1386. * Tests __debugInfo
  1387. */
  1388. public function testDebugInfo(): void
  1389. {
  1390. $response = new Response();
  1391. $response = $response->withStringBody('Foo');
  1392. $result = $response->__debugInfo();
  1393. $expected = [
  1394. 'status' => 200,
  1395. 'contentType' => 'text/html',
  1396. 'headers' => [
  1397. 'Content-Type' => ['text/html; charset=UTF-8'],
  1398. ],
  1399. 'file' => null,
  1400. 'fileRange' => [],
  1401. 'cookies' => new CookieCollection(),
  1402. 'cacheDirectives' => [],
  1403. 'body' => 'Foo',
  1404. ];
  1405. $this->assertEquals($expected, $result);
  1406. }
  1407. }