ResponseTest.php 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574
  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\DateTime;
  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 withNotModified()
  493. */
  494. public function testWithNotModified(): void
  495. {
  496. $response = new Response(['body' => 'something']);
  497. $response = $response->withLength(100)
  498. ->withStatus(200)
  499. ->withHeader('Last-Modified', 'value')
  500. ->withHeader('Content-Language', 'en-EN')
  501. ->withHeader('X-things', 'things')
  502. ->withType('application/json');
  503. $new = $response->withNotModified();
  504. $this->assertTrue($response->hasHeader('Content-Language'), 'old instance not changed');
  505. $this->assertTrue($response->hasHeader('Content-Length'), 'old instance not changed');
  506. $this->assertFalse($new->hasHeader('Content-Type'));
  507. $this->assertFalse($new->hasHeader('Content-Length'));
  508. $this->assertFalse($new->hasHeader('Content-Language'));
  509. $this->assertFalse($new->hasHeader('Last-Modified'));
  510. $this->assertSame('things', $new->getHeaderLine('X-things'), 'Other headers are retained');
  511. $this->assertSame(304, $new->getStatusCode());
  512. $this->assertSame('', $new->getBody()->getContents());
  513. }
  514. /**
  515. * Test checkNotModified method
  516. */
  517. public function testCheckNotModifiedByEtagStar(): void
  518. {
  519. $request = new ServerRequest();
  520. $request = $request->withHeader('If-None-Match', '*');
  521. $response = new Response();
  522. $response = $response->withEtag('something')
  523. ->withHeader('Content-Length', 99);
  524. $this->assertTrue($response->isNotModified($request));
  525. }
  526. /**
  527. * Test checkNotModified method
  528. */
  529. public function testCheckNotModifiedByEtagExact(): void
  530. {
  531. $request = new ServerRequest();
  532. $request = $request->withHeader('If-None-Match', 'W/"something", "other"');
  533. $response = new Response();
  534. $response = $response->withEtag('something', true)
  535. ->withHeader('Content-Length', 99);
  536. $this->assertTrue($response->isNotModified($request));
  537. }
  538. /**
  539. * Test checkNotModified method
  540. */
  541. public function testCheckNotModifiedByEtagAndTime(): void
  542. {
  543. $request = new ServerRequest();
  544. $request = $request->withHeader('If-Modified-Since', '2012-01-01 00:00:00')
  545. ->withHeader('If-None-Match', 'W/"something", "other"');
  546. $response = new Response();
  547. $response = $response->withModified('2012-01-01 00:00:00')
  548. ->withEtag('something', true)
  549. ->withHeader('Content-Length', 99);
  550. $this->assertTrue($response->isNotModified($request));
  551. }
  552. /**
  553. * Test checkNotModified method
  554. */
  555. public function testCheckNotModifiedByEtagAndTimeMismatch(): void
  556. {
  557. $request = new ServerRequest();
  558. $request = $request->withHeader('If-Modified-Since', '2012-01-01 00:00:00')
  559. ->withHeader('If-None-Match', 'W/"something", "other"');
  560. $response = new Response();
  561. $response = $response->withModified('2012-01-01 00:00:01')
  562. ->withEtag('something', true)
  563. ->withHeader('Content-Length', 99);
  564. $this->assertFalse($response->isNotModified($request));
  565. }
  566. /**
  567. * Test checkNotModified method
  568. */
  569. public function testCheckNotModifiedByEtagMismatch(): void
  570. {
  571. $request = new ServerRequest();
  572. $request = $request->withHeader('If-Modified-Since', '2012-01-01 00:00:00')
  573. ->withHeader('If-None-Match', 'W/"something-else", "other"');
  574. $response = new Response();
  575. $response = $response->withModified('2012-01-01 00:00:00')
  576. ->withEtag('something', true)
  577. ->withHeader('Content-Length', 99);
  578. $this->assertFalse($response->isNotModified($request));
  579. }
  580. /**
  581. * Test checkNotModified method
  582. */
  583. public function testCheckNotModifiedByTime(): void
  584. {
  585. $request = new ServerRequest();
  586. $request = $request->withHeader('If-Modified-Since', '2012-01-01 00:00:00');
  587. $response = new Response();
  588. $response = $response->withModified('2012-01-01 00:00:00')
  589. ->withHeader('Content-Length', 99);
  590. $this->assertTrue($response->isNotModified($request));
  591. }
  592. /**
  593. * Test checkNotModified method
  594. */
  595. public function testCheckNotModifiedNoHints(): void
  596. {
  597. $request = new ServerRequest();
  598. $request = $request->withHeader('If-None-Match', 'W/"something", "other"')
  599. ->withHeader('If-Modified-Since', '2012-01-01 00:00:00');
  600. $response = new Response();
  601. $this->assertFalse($response->isNotModified($request));
  602. }
  603. /**
  604. * Test setting cookies with no value
  605. */
  606. public function testWithCookieEmpty(): void
  607. {
  608. $response = new Response();
  609. $new = $response->withCookie(new Cookie('testing'));
  610. $this->assertNull($response->getCookie('testing'), 'withCookie does not mutate');
  611. $expected = [
  612. 'name' => 'testing',
  613. 'value' => '',
  614. 'expires' => 0,
  615. 'path' => '/',
  616. 'domain' => '',
  617. 'secure' => false,
  618. 'httponly' => false,
  619. ];
  620. $result = $new->getCookie('testing');
  621. $this->assertEquals($expected, $result);
  622. }
  623. /**
  624. * Test setting cookies with scalar values
  625. */
  626. public function testWithCookieScalar(): void
  627. {
  628. $response = new Response();
  629. $new = $response->withCookie(new Cookie('testing', 'abc123'));
  630. $this->assertNull($response->getCookie('testing'), 'withCookie does not mutate');
  631. $this->assertSame('abc123', $new->getCookie('testing')['value']);
  632. $new = $response->withCookie(new Cookie('testing', 0.99));
  633. $this->assertEquals(0.99, $new->getCookie('testing')['value']);
  634. $new = $response->withCookie(new Cookie('testing', 99));
  635. $this->assertEquals(99, $new->getCookie('testing')['value']);
  636. $new = $response->withCookie(new Cookie('testing', false));
  637. $this->assertSame('', $new->getCookie('testing')['value']);
  638. $new = $response->withCookie(new Cookie('testing', true));
  639. $this->assertSame('1', $new->getCookie('testing')['value']);
  640. }
  641. /**
  642. * Test withCookie() and duplicate data
  643. *
  644. * @throws \Exception
  645. */
  646. public function testWithDuplicateCookie(): void
  647. {
  648. $expiry = new DateTimeImmutable('+24 hours');
  649. $response = new Response();
  650. $cookie = new Cookie(
  651. 'testing',
  652. '[a,b,c]',
  653. $expiry,
  654. '/test',
  655. '',
  656. true
  657. );
  658. $new = $response->withCookie($cookie);
  659. $this->assertNull($response->getCookie('testing'), 'withCookie does not mutate');
  660. $expected = [
  661. 'name' => 'testing',
  662. 'value' => '[a,b,c]',
  663. 'expires' => $expiry,
  664. 'path' => '/test',
  665. 'domain' => '',
  666. 'secure' => true,
  667. 'httponly' => false,
  668. ];
  669. // Match the date time formatting to Response::convertCookieToArray
  670. $expected['expires'] = $expiry->format('U');
  671. $this->assertEquals($expected, $new->getCookie('testing'));
  672. }
  673. /**
  674. * Test withCookie() and a cookie instance
  675. */
  676. public function testWithCookieObject(): void
  677. {
  678. $response = new Response();
  679. $cookie = new Cookie('yay', 'a value');
  680. $new = $response->withCookie($cookie);
  681. $this->assertNull($response->getCookie('yay'), 'withCookie does not mutate');
  682. $this->assertNotEmpty($new->getCookie('yay'));
  683. $this->assertSame($cookie, $new->getCookieCollection()->get('yay'));
  684. }
  685. public function testWithExpiredCookieScalar(): void
  686. {
  687. $response = new Response();
  688. $response = $response->withCookie(new Cookie('testing', 'abc123'));
  689. $this->assertSame('abc123', $response->getCookie('testing')['value']);
  690. $new = $response->withExpiredCookie(new Cookie('testing'));
  691. $this->assertSame(0, $response->getCookie('testing')['expires']);
  692. $this->assertLessThan(DateTime::createFromTimestamp(1), (string)$new->getCookie('testing')['expires']);
  693. }
  694. /**
  695. * @throws \Exception If DateImmutable emits an error.
  696. */
  697. public function testWithExpiredCookieOptions(): void
  698. {
  699. $options = [
  700. 'name' => 'testing',
  701. 'value' => 'abc123',
  702. 'options' => [
  703. 'domain' => 'cakephp.org',
  704. 'path' => '/custompath/',
  705. 'secure' => true,
  706. 'httponly' => true,
  707. 'expires' => new DateTimeImmutable('+14 days'),
  708. ],
  709. ];
  710. $cookie = Cookie::create(
  711. $options['name'],
  712. $options['value'],
  713. $options['options']
  714. );
  715. $response = new Response();
  716. $response = $response->withCookie($cookie);
  717. $options['options']['expires'] = $options['options']['expires']->format('U');
  718. $expected = ['name' => $options['name'], 'value' => $options['value']] + $options['options'];
  719. $this->assertEquals($expected, $response->getCookie('testing'));
  720. $expiredCookie = $response->withExpiredCookie($cookie);
  721. $this->assertSame($expected['expires'], (string)$response->getCookie('testing')['expires']);
  722. $this->assertLessThan(DateTime::createFromTimestamp(1), (string)$expiredCookie->getCookie('testing')['expires']);
  723. }
  724. public function testWithExpiredCookieObject(): void
  725. {
  726. $response = new Response();
  727. $cookie = new Cookie('yay', 'a value');
  728. $response = $response->withCookie($cookie);
  729. $this->assertSame('a value', $response->getCookie('yay')['value']);
  730. $new = $response->withExpiredCookie($cookie);
  731. $this->assertSame(0, $response->getCookie('yay')['expires']);
  732. $this->assertSame(1, $new->getCookie('yay')['expires']);
  733. }
  734. public function testWithExpiredCookieNotUtc()
  735. {
  736. date_default_timezone_set('Europe/Paris');
  737. $response = new Response();
  738. $cookie = new Cookie('yay', 'a value');
  739. $response = $response->withExpiredCookie($cookie);
  740. date_default_timezone_set('UTC');
  741. $this->assertSame(1, $response->getCookie('yay')['expires']);
  742. }
  743. /**
  744. * Test getCookies() and array data.
  745. */
  746. public function testGetCookies(): void
  747. {
  748. $response = new Response();
  749. $new = $response->withCookie(new Cookie('testing', 'a'))
  750. ->withCookie(new Cookie('test2', 'b', null, '/test', '', true));
  751. $expected = [
  752. 'testing' => [
  753. 'name' => 'testing',
  754. 'value' => 'a',
  755. 'expires' => 0,
  756. 'path' => '/',
  757. 'domain' => '',
  758. 'secure' => false,
  759. 'httponly' => false,
  760. ],
  761. 'test2' => [
  762. 'name' => 'test2',
  763. 'value' => 'b',
  764. 'expires' => 0,
  765. 'path' => '/test',
  766. 'domain' => '',
  767. 'secure' => true,
  768. 'httponly' => false,
  769. ],
  770. ];
  771. $this->assertEquals($expected, $new->getCookies());
  772. }
  773. /**
  774. * Test getCookies() and array data.
  775. */
  776. public function testGetCookiesArrayValue(): void
  777. {
  778. $response = new Response();
  779. $cookie = (new Cookie('urmc'))
  780. ->withValue(['user_id' => 1, 'token' => 'abc123'])
  781. ->withHttpOnly(true);
  782. $new = $response->withCookie($cookie);
  783. $expected = [
  784. 'urmc' => [
  785. 'name' => 'urmc',
  786. 'value' => '{"user_id":1,"token":"abc123"}',
  787. 'expires' => 0,
  788. 'path' => '/',
  789. 'domain' => '',
  790. 'secure' => false,
  791. 'httponly' => true,
  792. ],
  793. ];
  794. $this->assertEquals($expected, $new->getCookies());
  795. }
  796. /**
  797. * Test getCookieCollection() as array data
  798. */
  799. public function testGetCookieCollection(): void
  800. {
  801. $response = new Response();
  802. $new = $response->withCookie(new Cookie('testing', 'a'))
  803. ->withCookie(new Cookie('test2', 'b', null, '/test', '', true));
  804. $cookies = $response->getCookieCollection();
  805. $this->assertInstanceOf(CookieCollection::class, $cookies);
  806. $this->assertCount(0, $cookies, 'Original response not mutated');
  807. $cookies = $new->getCookieCollection();
  808. $this->assertInstanceOf(CookieCollection::class, $cookies);
  809. $this->assertCount(2, $cookies);
  810. $this->assertTrue($cookies->has('testing'));
  811. $this->assertTrue($cookies->has('test2'));
  812. }
  813. /**
  814. * Test withCookieCollection()
  815. */
  816. public function testWithCookieCollection(): void
  817. {
  818. $response = new Response();
  819. $collection = new CookieCollection([new Cookie('foo', 'bar')]);
  820. $newResponse = $response->withCookieCollection($collection);
  821. $this->assertNotSame($response, $newResponse);
  822. $this->assertNotSame($response->getCookieCollection(), $newResponse->getCookieCollection());
  823. $this->assertSame($newResponse->getCookie('foo')['value'], 'bar');
  824. }
  825. /**
  826. * Test that cors() returns a builder.
  827. */
  828. public function testCors(): void
  829. {
  830. $request = new ServerRequest([
  831. 'environment' => ['HTTP_ORIGIN' => 'http://example.com'],
  832. ]);
  833. $response = new Response();
  834. $builder = $response->cors($request);
  835. $this->assertInstanceOf(CorsBuilder::class, $builder);
  836. $this->assertSame($response, $builder->build(), 'Empty builder returns same object');
  837. }
  838. /**
  839. * test withFile() not found
  840. */
  841. public function testWithFileNotFound(): void
  842. {
  843. $this->expectException(NotFoundException::class);
  844. $this->expectExceptionMessage('The requested file /some/missing/folder/file.jpg was not found');
  845. $response = new Response();
  846. $response->withFile('/some/missing/folder/file.jpg');
  847. }
  848. /**
  849. * test withFile() not found
  850. */
  851. public function testWithFileNotFoundNoDebug(): void
  852. {
  853. Configure::write('debug', 0);
  854. $this->expectException(NotFoundException::class);
  855. $this->expectExceptionMessage('The requested file was not found');
  856. $response = new Response();
  857. $response->withFile('/some/missing/folder/file.jpg');
  858. }
  859. /**
  860. * Provider for various kinds of unacceptable files.
  861. *
  862. * @return array
  863. */
  864. public static function invalidFileProvider(): array
  865. {
  866. return [
  867. ['my/../cat.gif', 'The requested file contains `..` and will not be read.'],
  868. ['my\..\cat.gif', 'The requested file contains `..` and will not be read.'],
  869. ['my/ca..t.gif', 'my/ca..t.gif was not found or not readable'],
  870. ['my/ca..t/image.gif', 'my/ca..t/image.gif was not found or not readable'],
  871. ];
  872. }
  873. /**
  874. * test withFile and invalid paths
  875. *
  876. * @dataProvider invalidFileProvider
  877. */
  878. public function testWithFileInvalidPath(string $path, string $expectedMessage): void
  879. {
  880. $this->expectException(NotFoundException::class);
  881. $this->expectExceptionMessage($expectedMessage);
  882. $response = new Response();
  883. $response->withFile($path);
  884. }
  885. /**
  886. * test withFile() + download & name
  887. */
  888. public function testWithFileDownloadAndName(): void
  889. {
  890. $response = new Response();
  891. $new = $response->withFile(
  892. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  893. [
  894. 'name' => 'something_special.css',
  895. 'download' => true,
  896. ]
  897. );
  898. $this->assertSame(
  899. 'text/html; charset=UTF-8',
  900. $response->getHeaderLine('Content-Type'),
  901. 'No mutation'
  902. );
  903. $this->assertSame(
  904. 'text/css; charset=UTF-8',
  905. $new->getHeaderLine('Content-Type')
  906. );
  907. $this->assertSame(
  908. 'attachment; filename="something_special.css"',
  909. $new->getHeaderLine('Content-Disposition')
  910. );
  911. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  912. $this->assertSame('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  913. $body = $new->getBody();
  914. $this->assertInstanceOf('Laminas\Diactoros\Stream', $body);
  915. $expected = '/* this is the test asset css file */';
  916. $this->assertSame($expected, trim($body->getContents()));
  917. $file = $new->getFile()->openFile();
  918. $this->assertSame($expected, trim($file->fread(100)));
  919. }
  920. /**
  921. * test withFile() + a generic agent
  922. */
  923. public function testWithFileUnknownFileTypeGeneric(): void
  924. {
  925. $response = new Response();
  926. $new = $response->withFile(CONFIG . 'no_section.ini');
  927. $this->assertSame('text/html; charset=UTF-8', $new->getHeaderLine('Content-Type'));
  928. $this->assertSame(
  929. 'attachment; filename="no_section.ini"',
  930. $new->getHeaderLine('Content-Disposition')
  931. );
  932. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  933. $body = $new->getBody();
  934. $expected = "some_key = some_value\nbool_key = 1\n";
  935. $this->assertSame($expected, $body->getContents());
  936. }
  937. /**
  938. * test withFile() + opera
  939. */
  940. public function testWithFileUnknownFileTypeOpera(): void
  941. {
  942. $_SERVER['HTTP_USER_AGENT'] = 'Opera/9.80 (Windows NT 6.0; U; en) Presto/2.8.99 Version/11.10';
  943. $response = new Response();
  944. $new = $response->withFile(CONFIG . 'no_section.ini');
  945. $this->assertSame('application/octet-stream', $new->getHeaderLine('Content-Type'));
  946. $this->assertSame(
  947. 'attachment; filename="no_section.ini"',
  948. $new->getHeaderLine('Content-Disposition')
  949. );
  950. }
  951. /**
  952. * test withFile() + old IE
  953. */
  954. public function testWithFileUnknownFileTypeOldIe(): void
  955. {
  956. $_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)';
  957. $response = new Response();
  958. $new = $response->withFile(CONFIG . 'no_section.ini');
  959. $this->assertSame('application/force-download', $new->getHeaderLine('Content-Type'));
  960. }
  961. /**
  962. * test withFile() + no download
  963. */
  964. public function testWithFileNoDownload(): void
  965. {
  966. $response = new Response();
  967. $new = $response->withFile(CONFIG . 'no_section.ini', [
  968. 'download' => false,
  969. ]);
  970. $this->assertSame(
  971. 'text/html; charset=UTF-8',
  972. $new->getHeaderLine('Content-Type')
  973. );
  974. $this->assertFalse($new->hasHeader('Content-Disposition'));
  975. $this->assertFalse($new->hasHeader('Content-Transfer-Encoding'));
  976. }
  977. /**
  978. * Test that uppercase extensions result in correct content-types
  979. */
  980. public function testWithFileUpperExtension(): void
  981. {
  982. $response = new Response();
  983. $new = $response->withFile(TEST_APP . 'vendor/img/test_2.JPG');
  984. $this->assertSame('image/jpeg', $new->getHeaderLine('Content-Type'));
  985. }
  986. /**
  987. * A data provider for testing various ranges
  988. *
  989. * @return array
  990. */
  991. public static function rangeProvider(): array
  992. {
  993. return [
  994. // suffix-byte-range
  995. [
  996. 'bytes=-25', 25, 'bytes 13-37/38',
  997. ],
  998. [
  999. 'bytes=0-', 38, 'bytes 0-37/38',
  1000. ],
  1001. [
  1002. 'bytes=10-', 28, 'bytes 10-37/38',
  1003. ],
  1004. [
  1005. 'bytes=10-20', 11, 'bytes 10-20/38',
  1006. ],
  1007. // Spaced out
  1008. [
  1009. 'bytes = 10 - 20', 11, 'bytes 10-20/38',
  1010. ],
  1011. ];
  1012. }
  1013. /**
  1014. * Test withFile() & the various range offset types.
  1015. *
  1016. * @dataProvider rangeProvider
  1017. */
  1018. public function testWithFileRangeOffsets(string $range, int $length, string $offsetResponse): void
  1019. {
  1020. $_SERVER['HTTP_RANGE'] = $range;
  1021. $response = new Response();
  1022. $new = $response->withFile(
  1023. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1024. ['download' => true]
  1025. );
  1026. $this->assertSame(
  1027. 'attachment; filename="test_asset.css"',
  1028. $new->getHeaderLine('Content-Disposition')
  1029. );
  1030. $this->assertSame('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  1031. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  1032. $this->assertEquals($length, $new->getHeaderLine('Content-Length'));
  1033. $this->assertEquals($offsetResponse, $new->getHeaderLine('Content-Range'));
  1034. }
  1035. /**
  1036. * Test withFile() fetching ranges from a file.
  1037. */
  1038. public function testWithFileRange(): void
  1039. {
  1040. $_SERVER['HTTP_RANGE'] = 'bytes=8-25';
  1041. $response = new Response();
  1042. $new = $response->withFile(
  1043. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1044. ['download' => true]
  1045. );
  1046. $this->assertSame(
  1047. 'attachment; filename="test_asset.css"',
  1048. $new->getHeaderLine('Content-Disposition')
  1049. );
  1050. $this->assertSame('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  1051. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  1052. $this->assertSame('18', $new->getHeaderLine('Content-Length'));
  1053. $this->assertSame('bytes 8-25/38', $new->getHeaderLine('Content-Range'));
  1054. $this->assertSame(206, $new->getStatusCode());
  1055. }
  1056. /**
  1057. * Provider for invalid range header values.
  1058. *
  1059. * @return array
  1060. */
  1061. public static function invalidFileRangeProvider(): array
  1062. {
  1063. return [
  1064. // malformed range
  1065. [
  1066. 'bytes=0,38',
  1067. ],
  1068. // malformed punctuation
  1069. [
  1070. 'bytes: 0 - 38',
  1071. ],
  1072. ];
  1073. }
  1074. /**
  1075. * Test withFile() and invalid ranges
  1076. *
  1077. * @dataProvider invalidFileRangeProvider
  1078. */
  1079. public function testWithFileInvalidRange(string $range): void
  1080. {
  1081. $_SERVER['HTTP_RANGE'] = $range;
  1082. $response = new Response();
  1083. $new = $response->withFile(
  1084. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1085. ['download' => true]
  1086. );
  1087. $this->assertSame(
  1088. 'attachment; filename="test_asset.css"',
  1089. $new->getHeaderLine('Content-Disposition')
  1090. );
  1091. $this->assertSame('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  1092. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  1093. $this->assertSame('38', $new->getHeaderLine('Content-Length'));
  1094. $this->assertSame('bytes 0-37/38', $new->getHeaderLine('Content-Range'));
  1095. $this->assertSame(206, $new->getStatusCode());
  1096. }
  1097. /**
  1098. * Test withFile() and a reversed range
  1099. */
  1100. public function testWithFileReversedRange(): void
  1101. {
  1102. $_SERVER['HTTP_RANGE'] = 'bytes=30-2';
  1103. $response = new Response();
  1104. $new = $response->withFile(
  1105. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1106. ['download' => true]
  1107. );
  1108. $this->assertSame(
  1109. 'attachment; filename="test_asset.css"',
  1110. $new->getHeaderLine('Content-Disposition')
  1111. );
  1112. $this->assertSame('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  1113. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  1114. $this->assertSame('bytes 0-37/38', $new->getHeaderLine('Content-Range'));
  1115. $this->assertSame(416, $new->getStatusCode());
  1116. }
  1117. /**
  1118. * Test the withLocation method.
  1119. */
  1120. public function testWithLocation(): void
  1121. {
  1122. $response = new Response();
  1123. $this->assertSame('', $response->getHeaderLine('Location'), 'No header should be set.');
  1124. $new = $response->withLocation('http://example.org');
  1125. $this->assertNotSame($new, $response);
  1126. $this->assertSame('', $response->getHeaderLine('Location'), 'No header should be set');
  1127. $this->assertSame('http://example.org', $new->getHeaderLine('Location'), 'Header should be set');
  1128. $this->assertSame(302, $new->getStatusCode(), 'Status should be updated');
  1129. }
  1130. /**
  1131. * Test get protocol version.
  1132. */
  1133. public function getProtocolVersion(): void
  1134. {
  1135. $response = new Response();
  1136. $version = $response->getProtocolVersion();
  1137. $this->assertSame('1.1', $version);
  1138. }
  1139. /**
  1140. * Test with protocol.
  1141. */
  1142. public function testWithProtocol(): void
  1143. {
  1144. $response = new Response();
  1145. $version = $response->getProtocolVersion();
  1146. $this->assertSame('1.1', $version);
  1147. $response2 = $response->withProtocolVersion('1.0');
  1148. $version = $response2->getProtocolVersion();
  1149. $this->assertSame('1.0', $version);
  1150. $version = $response->getProtocolVersion();
  1151. $this->assertSame('1.1', $version);
  1152. $this->assertNotEquals($response, $response2);
  1153. }
  1154. /**
  1155. * Test with status code.
  1156. */
  1157. public function testWithStatusCode(): void
  1158. {
  1159. $response = new Response();
  1160. $statusCode = $response->getStatusCode();
  1161. $this->assertSame(200, $statusCode);
  1162. $response2 = $response->withStatus(404);
  1163. $statusCode = $response2->getStatusCode();
  1164. $this->assertSame(404, $statusCode);
  1165. $statusCode = $response->getStatusCode();
  1166. $this->assertSame(200, $statusCode);
  1167. $this->assertNotEquals($response, $response2);
  1168. $response3 = $response->withStatus(111);
  1169. $this->assertSame(111, $response3->getStatusCode());
  1170. $this->assertSame('', $response3->getReasonPhrase());
  1171. }
  1172. /**
  1173. * Test invalid status codes
  1174. */
  1175. public function testWithStatusInvalid(): void
  1176. {
  1177. $this->expectException(InvalidArgumentException::class);
  1178. $this->expectExceptionMessage('Invalid status code: 1001. Use a valid HTTP status code in range 1xx - 5xx.');
  1179. $response = new Response();
  1180. $response->withStatus(1001);
  1181. }
  1182. /**
  1183. * Test get reason phrase.
  1184. */
  1185. public function testGetReasonPhrase(): void
  1186. {
  1187. $response = new Response();
  1188. $this->assertSame('OK', $response->getReasonPhrase());
  1189. $response = $response->withStatus(404);
  1190. $reasonPhrase = $response->getReasonPhrase();
  1191. $this->assertSame('Not Found', $reasonPhrase);
  1192. }
  1193. /**
  1194. * Test with body.
  1195. */
  1196. public function testWithBody(): void
  1197. {
  1198. $response = new Response();
  1199. $body = $response->getBody();
  1200. $body->rewind();
  1201. $result = $body->getContents();
  1202. $this->assertSame('', $result);
  1203. $stream = new Stream('php://memory', 'wb+');
  1204. $stream->write('test1');
  1205. $response2 = $response->withBody($stream);
  1206. $body = $response2->getBody();
  1207. $body->rewind();
  1208. $result = $body->getContents();
  1209. $this->assertSame('test1', $result);
  1210. $body = $response->getBody();
  1211. $body->rewind();
  1212. $result = $body->getContents();
  1213. $this->assertSame('', $result);
  1214. }
  1215. /**
  1216. * Test with string body.
  1217. */
  1218. public function testWithStringBody(): void
  1219. {
  1220. $response = new Response();
  1221. $newResponse = $response->withStringBody('Foo');
  1222. $body = $newResponse->getBody();
  1223. $this->assertSame('Foo', (string)$body);
  1224. $this->assertNotSame($response, $newResponse);
  1225. $response = new Response();
  1226. $newResponse = $response->withStringBody('');
  1227. $body = $newResponse->getBody();
  1228. $this->assertSame('', (string)$body);
  1229. $this->assertNotSame($response, $newResponse);
  1230. $response = new Response();
  1231. $newResponse = $response->withStringBody(null);
  1232. $body = $newResponse->getBody();
  1233. $this->assertSame('', (string)$body);
  1234. $this->assertNotSame($response, $newResponse);
  1235. $response = new Response();
  1236. $newResponse = $response->withStringBody('1337');
  1237. $body = $newResponse->getBody();
  1238. $this->assertSame('1337', (string)$body);
  1239. $this->assertNotSame($response, $newResponse);
  1240. }
  1241. /**
  1242. * Test get Body.
  1243. */
  1244. public function testGetBody(): void
  1245. {
  1246. $response = new Response();
  1247. $stream = $response->getBody();
  1248. $this->assertInstanceOf('Psr\Http\Message\StreamInterface', $stream);
  1249. }
  1250. /**
  1251. * Test with header.
  1252. */
  1253. public function testWithHeader(): void
  1254. {
  1255. $response = new Response();
  1256. $response2 = $response->withHeader('Accept', 'application/json');
  1257. $result = $response2->getHeaders();
  1258. $expected = [
  1259. 'Content-Type' => ['text/html; charset=UTF-8'],
  1260. 'Accept' => ['application/json'],
  1261. ];
  1262. $this->assertEquals($expected, $result);
  1263. $this->assertFalse($response->hasHeader('Accept'));
  1264. }
  1265. /**
  1266. * Test get headers.
  1267. */
  1268. public function testGetHeaders(): void
  1269. {
  1270. $response = new Response();
  1271. $headers = $response->getHeaders();
  1272. $response = $response->withAddedHeader('Location', 'localhost');
  1273. $response = $response->withAddedHeader('Accept', 'application/json');
  1274. $headers = $response->getHeaders();
  1275. $expected = [
  1276. 'Content-Type' => ['text/html; charset=UTF-8'],
  1277. 'Location' => ['localhost'],
  1278. 'Accept' => ['application/json'],
  1279. ];
  1280. $this->assertEquals($expected, $headers);
  1281. }
  1282. /**
  1283. * Test without header.
  1284. */
  1285. public function testWithoutHeader(): void
  1286. {
  1287. $response = new Response();
  1288. $response = $response->withAddedHeader('Location', 'localhost');
  1289. $response = $response->withAddedHeader('Accept', 'application/json');
  1290. $response2 = $response->withoutHeader('Location');
  1291. $headers = $response2->getHeaders();
  1292. $expected = [
  1293. 'Content-Type' => ['text/html; charset=UTF-8'],
  1294. 'Accept' => ['application/json'],
  1295. ];
  1296. $this->assertEquals($expected, $headers);
  1297. }
  1298. /**
  1299. * Test get header.
  1300. */
  1301. public function testGetHeader(): void
  1302. {
  1303. $response = new Response();
  1304. $response = $response->withAddedHeader('Location', 'localhost');
  1305. $result = $response->getHeader('Location');
  1306. $this->assertEquals(['localhost'], $result);
  1307. $result = $response->getHeader('location');
  1308. $this->assertEquals(['localhost'], $result);
  1309. $result = $response->getHeader('does-not-exist');
  1310. $this->assertEquals([], $result);
  1311. }
  1312. /**
  1313. * Test get header line.
  1314. */
  1315. public function testGetHeaderLine(): void
  1316. {
  1317. $response = new Response();
  1318. $headers = $response->getHeaderLine('Accept');
  1319. $this->assertSame('', $headers);
  1320. $response = $response->withAddedHeader('Accept', 'application/json');
  1321. $response = $response->withAddedHeader('Accept', 'application/xml');
  1322. $result = $response->getHeaderLine('Accept');
  1323. $expected = 'application/json,application/xml';
  1324. $this->assertSame($expected, $result);
  1325. $result = $response->getHeaderLine('accept');
  1326. $this->assertSame($expected, $result);
  1327. }
  1328. /**
  1329. * Test has header.
  1330. */
  1331. public function testHasHeader(): void
  1332. {
  1333. $response = new Response();
  1334. $response = $response->withAddedHeader('Location', 'localhost');
  1335. $this->assertTrue($response->hasHeader('Location'));
  1336. $this->assertTrue($response->hasHeader('location'));
  1337. $this->assertTrue($response->hasHeader('locATIon'));
  1338. $this->assertFalse($response->hasHeader('Accept'));
  1339. $this->assertFalse($response->hasHeader('accept'));
  1340. }
  1341. /**
  1342. * Tests __debugInfo
  1343. */
  1344. public function testDebugInfo(): void
  1345. {
  1346. $response = new Response();
  1347. $response = $response->withStringBody('Foo');
  1348. $result = $response->__debugInfo();
  1349. $expected = [
  1350. 'status' => 200,
  1351. 'contentType' => 'text/html',
  1352. 'headers' => [
  1353. 'Content-Type' => ['text/html; charset=UTF-8'],
  1354. ],
  1355. 'file' => null,
  1356. 'fileRange' => [],
  1357. 'cookies' => new CookieCollection(),
  1358. 'cacheDirectives' => [],
  1359. 'body' => 'Foo',
  1360. ];
  1361. $this->assertEquals($expected, $result);
  1362. }
  1363. }