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. use PHPUnit\Framework\Attributes\DataProvider;
  33. use Psr\Http\Message\StreamInterface;
  34. /**
  35. * ResponseTest
  36. */
  37. class ResponseTest extends TestCase
  38. {
  39. /**
  40. * SERVER variable backup.
  41. *
  42. * @var array
  43. */
  44. protected $server = [];
  45. /**
  46. * setup
  47. */
  48. public function setUp(): void
  49. {
  50. parent::setUp();
  51. $this->server = $_SERVER;
  52. }
  53. /**
  54. * teardown
  55. */
  56. public function tearDown(): void
  57. {
  58. parent::tearDown();
  59. $_SERVER = $this->server;
  60. unset($GLOBALS['mockedHeadersSent']);
  61. }
  62. /**
  63. * Tests the request object constructor
  64. */
  65. public function testConstruct(): void
  66. {
  67. $response = new Response();
  68. $this->assertSame('', (string)$response->getBody());
  69. $this->assertSame('UTF-8', $response->getCharset());
  70. $this->assertSame('text/html', $response->getType());
  71. $this->assertSame('text/html; charset=UTF-8', $response->getHeaderLine('Content-Type'));
  72. $this->assertSame(200, $response->getStatusCode());
  73. $options = [
  74. 'body' => 'This is the body',
  75. 'charset' => 'my-custom-charset',
  76. 'type' => 'mp3',
  77. 'status' => 203,
  78. ];
  79. $response = new Response($options);
  80. $this->assertSame('This is the body', (string)$response->getBody());
  81. $this->assertSame('my-custom-charset', $response->getCharset());
  82. $this->assertSame('audio/mpeg', $response->getType());
  83. $this->assertSame('audio/mpeg', $response->getHeaderLine('Content-Type'));
  84. $this->assertSame(203, $response->getStatusCode());
  85. }
  86. /**
  87. * Tests the getCharset/withCharset methods
  88. */
  89. public function testWithCharset(): void
  90. {
  91. $response = new Response();
  92. $this->assertSame('text/html; charset=UTF-8', $response->getHeaderLine('Content-Type'));
  93. $new = $response->withCharset('iso-8859-1');
  94. $this->assertStringNotContainsString('iso', $response->getHeaderLine('Content-Type'), 'Old instance not changed');
  95. $this->assertSame('iso-8859-1', $new->getCharset());
  96. $this->assertSame('text/html; charset=iso-8859-1', $new->getHeaderLine('Content-Type'));
  97. }
  98. /**
  99. * Tests the getType method
  100. */
  101. public function testGetType(): void
  102. {
  103. $response = new Response();
  104. $this->assertSame('text/html', $response->getType());
  105. $this->assertSame(
  106. 'application/pdf',
  107. $response->withType('pdf')->getType()
  108. );
  109. $this->assertSame(
  110. 'custom/stuff',
  111. $response->withType('custom/stuff')->getType()
  112. );
  113. $this->assertSame(
  114. 'application/json',
  115. $response->withType('json')->getType()
  116. );
  117. }
  118. public function testSetTypeMap(): void
  119. {
  120. $response = new Response();
  121. $response->setTypeMap('ical', 'text/calendar');
  122. $response = $response->withType('ical')->getType();
  123. $this->assertSame('text/calendar', $response);
  124. }
  125. public function testSetTypeMapAsArray(): void
  126. {
  127. $response = new Response();
  128. $response->setTypeMap('ical', ['text/calendar']);
  129. $response = $response->withType('ical')->getType();
  130. $this->assertSame('text/calendar', $response);
  131. }
  132. /**
  133. * Tests the withType method
  134. */
  135. public function testWithTypeAlias(): void
  136. {
  137. $response = new Response();
  138. $this->assertSame(
  139. 'text/html; charset=UTF-8',
  140. $response->getHeaderLine('Content-Type'),
  141. 'Default content-type should match'
  142. );
  143. $new = $response->withType('pdf');
  144. $this->assertNotSame($new, $response, 'Should be a new instance');
  145. $this->assertSame(
  146. 'text/html; charset=UTF-8',
  147. $response->getHeaderLine('Content-Type'),
  148. 'Original object should not be modified'
  149. );
  150. $this->assertSame('application/pdf', $new->getHeaderLine('Content-Type'));
  151. $json = $new->withType('json');
  152. $this->assertSame('application/json', $json->getHeaderLine('Content-Type'));
  153. $this->assertSame('application/json', $json->getType());
  154. }
  155. /**
  156. * test withType() and full mime-types
  157. */
  158. public function withTypeFull(): void
  159. {
  160. $response = new Response();
  161. $this->assertSame(
  162. 'application/json',
  163. $response->withType('application/json')->getHeaderLine('Content-Type'),
  164. 'Should not add charset to explicit type'
  165. );
  166. $this->assertSame(
  167. 'custom/stuff',
  168. $response->withType('custom/stuff')->getHeaderLine('Content-Type'),
  169. 'Should allow arbitrary types'
  170. );
  171. $this->assertSame(
  172. 'text/html; charset=UTF-8',
  173. $response->withType('text/html; charset=UTF-8')->getHeaderLine('Content-Type'),
  174. 'Should allow charset types'
  175. );
  176. }
  177. /**
  178. * Test that an invalid type raises an exception
  179. */
  180. public function testWithTypeInvalidType(): void
  181. {
  182. $this->expectException(InvalidArgumentException::class);
  183. $this->expectExceptionMessage('`beans` is an invalid content type');
  184. $response = new Response();
  185. $response->withType('beans');
  186. }
  187. /**
  188. * Data provider for content type tests.
  189. *
  190. * @return array
  191. */
  192. public static function charsetTypeProvider(): array
  193. {
  194. return [
  195. ['mp3', 'audio/mpeg'],
  196. ['js', 'application/javascript; charset=UTF-8'],
  197. ['xml', 'application/xml; charset=UTF-8'],
  198. ['txt', 'text/plain; charset=UTF-8'],
  199. ];
  200. }
  201. /**
  202. * Test that setting certain status codes clears the status code.
  203. */
  204. public function testWithStatusClearsContentType(): void
  205. {
  206. $response = new Response();
  207. $new = $response->withType('pdf')
  208. ->withStatus(204);
  209. $this->assertFalse($new->hasHeader('Content-Type'));
  210. $this->assertSame('', $new->getType());
  211. $this->assertSame(204, $new->getStatusCode(), 'Status code should clear content-type');
  212. $response = new Response();
  213. $new = $response->withStatus(304)
  214. ->withType('pdf');
  215. $this->assertSame('', $new->getType());
  216. $this->assertFalse(
  217. $new->hasHeader('Content-Type'),
  218. 'Type should not be retained because of status code.'
  219. );
  220. $response = new Response();
  221. $new = $response
  222. ->withHeader('Content-Type', 'application/json')
  223. ->withStatus(204);
  224. $this->assertFalse($new->hasHeader('Content-Type'), 'Should clear direct header');
  225. $this->assertSame('', $new->getType());
  226. }
  227. /**
  228. * Test that setting status codes doesn't overwrite content-type
  229. */
  230. public function testWithStatusDoesNotChangeContentType(): void
  231. {
  232. $response = new Response();
  233. $new = $response->withHeader('Content-Type', 'application/json')
  234. ->withStatus(403);
  235. $this->assertSame('application/json', $new->getHeaderLine('Content-Type'));
  236. $this->assertSame(403, $new->getStatusCode());
  237. $response = new Response();
  238. $new = $response->withStatus(403)
  239. ->withHeader('Content-Type', 'application/json');
  240. $this->assertSame('application/json', $new->getHeaderLine('Content-Type'));
  241. $this->assertSame(403, $new->getStatusCode());
  242. $this->assertSame('application/json', $new->getType());
  243. }
  244. /**
  245. * Tests the withDisabledCache method
  246. */
  247. public function testWithDisabledCache(): void
  248. {
  249. $response = new Response();
  250. $expected = [
  251. 'Expires' => ['Mon, 26 Jul 1997 05:00:00 GMT'],
  252. 'Last-Modified' => [gmdate(DATE_RFC7231)],
  253. 'Cache-Control' => ['no-store, no-cache, must-revalidate, post-check=0, pre-check=0'],
  254. 'Content-Type' => ['text/html; charset=UTF-8'],
  255. ];
  256. $new = $response->withDisabledCache();
  257. $this->assertFalse($response->hasHeader('Expires'), 'Old instance not mutated.');
  258. $this->assertEquals($expected, $new->getHeaders());
  259. }
  260. /**
  261. * Tests the withCache method
  262. */
  263. public function testWithCache(): void
  264. {
  265. $response = new Response();
  266. $since = time();
  267. $time = $since;
  268. $new = $response->withCache($since, $time);
  269. $this->assertFalse($response->hasHeader('Date'));
  270. $this->assertFalse($response->hasHeader('Last-Modified'));
  271. $this->assertSame(gmdate(DATE_RFC7231, $since), $new->getHeaderLine('Date'));
  272. $this->assertSame(gmdate(DATE_RFC7231, $since), $new->getHeaderLine('Last-Modified'));
  273. $this->assertSame(gmdate(DATE_RFC7231, $time), $new->getHeaderLine('Expires'));
  274. $this->assertSame('public, max-age=0', $new->getHeaderLine('Cache-Control'));
  275. }
  276. /**
  277. * Tests the compress method
  278. */
  279. public function testCompress(): void
  280. {
  281. $response = new Response();
  282. if (ini_get('zlib.output_compression') === '1' || !extension_loaded('zlib')) {
  283. $this->assertFalse($response->compress());
  284. $this->markTestSkipped('Is not possible to test output compression');
  285. }
  286. $_SERVER['HTTP_ACCEPT_ENCODING'] = '';
  287. $result = $response->compress();
  288. $this->assertFalse($result);
  289. $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip';
  290. $result = $response->compress();
  291. $this->assertTrue($result);
  292. $this->assertContains('ob_gzhandler', ob_list_handlers());
  293. ob_get_clean();
  294. }
  295. /**
  296. * Tests the withDownload method
  297. */
  298. public function testWithDownload(): void
  299. {
  300. $response = new Response();
  301. $new = $response->withDownload('myfile.mp3');
  302. $this->assertFalse($response->hasHeader('Content-Disposition'), 'No mutation');
  303. $expected = 'attachment; filename="myfile.mp3"';
  304. $this->assertSame($expected, $new->getHeaderLine('Content-Disposition'));
  305. }
  306. /**
  307. * Tests the mapType method
  308. */
  309. public function testMapType(): void
  310. {
  311. $response = new Response();
  312. $this->assertSame('wav', $response->mapType('audio/x-wav'));
  313. $this->assertSame('pdf', $response->mapType('application/pdf'));
  314. $this->assertSame('xml', $response->mapType('text/xml'));
  315. $this->assertSame('html', $response->mapType('*/*'));
  316. $this->assertSame('csv', $response->mapType('application/vnd.ms-excel'));
  317. $expected = ['json', 'xhtml', 'css'];
  318. $result = $response->mapType(['application/json', 'application/xhtml+xml', 'text/css']);
  319. $this->assertEquals($expected, $result);
  320. }
  321. /**
  322. * Tests the outputCompressed method
  323. */
  324. public function testOutputCompressed(): void
  325. {
  326. $response = new Response();
  327. $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip';
  328. $result = $response->outputCompressed();
  329. $this->assertFalse($result);
  330. $_SERVER['HTTP_ACCEPT_ENCODING'] = '';
  331. $result = $response->outputCompressed();
  332. $this->assertFalse($result);
  333. if (!extension_loaded('zlib')) {
  334. $this->markTestSkipped('Skipping further tests for outputCompressed as zlib extension is not loaded');
  335. }
  336. if (ini_get('zlib.output_compression') !== '1') {
  337. ob_start('ob_gzhandler');
  338. }
  339. $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip';
  340. $result = $response->outputCompressed();
  341. $this->assertTrue($result);
  342. $_SERVER['HTTP_ACCEPT_ENCODING'] = '';
  343. $result = $response->outputCompressed();
  344. $this->assertFalse($result);
  345. if (ini_get('zlib.output_compression') !== '1') {
  346. ob_get_clean();
  347. }
  348. }
  349. /**
  350. * Tests settings the content length
  351. */
  352. public function testWithLength(): void
  353. {
  354. $response = new Response();
  355. $this->assertFalse($response->hasHeader('Content-Length'));
  356. $new = $response->withLength(100);
  357. $this->assertFalse($response->hasHeader('Content-Length'), 'Old instance not modified');
  358. $this->assertSame('100', $new->getHeaderLine('Content-Length'));
  359. }
  360. /**
  361. * Tests settings the link
  362. */
  363. public function testWithAddedLink(): void
  364. {
  365. $response = new Response();
  366. $this->assertFalse($response->hasHeader('Link'));
  367. $new = $response->withAddedLink('http://example.com', ['rel' => 'prev']);
  368. $this->assertFalse($response->hasHeader('Link'), 'Old instance not modified');
  369. $this->assertSame('<http://example.com>; rel="prev"', $new->getHeaderLine('Link'));
  370. $new = $response->withAddedLink('http://example.com');
  371. $this->assertSame('<http://example.com>', $new->getHeaderLine('Link'));
  372. $new = $response->withAddedLink('http://example.com?p=1', ['rel' => 'prev'])
  373. ->withAddedLink('http://example.com?p=2', ['rel' => 'next', 'foo' => 'bar']);
  374. $this->assertSame('<http://example.com?p=1>; rel="prev",<http://example.com?p=2>; rel="next"; foo="bar"', $new->getHeaderLine('Link'));
  375. }
  376. /**
  377. * Tests the withExpires method
  378. */
  379. public function testWithExpires(): void
  380. {
  381. $response = new Response();
  382. $now = new NativeDateTime('now', new DateTimeZone('America/Los_Angeles'));
  383. $new = $response->withExpires($now);
  384. $this->assertFalse($response->hasHeader('Expires'));
  385. $now->setTimeZone(new DateTimeZone('UTC'));
  386. $this->assertSame($now->format(DATE_RFC7231), $new->getHeaderLine('Expires'));
  387. $now = time();
  388. $new = $response->withExpires($now);
  389. $this->assertSame(gmdate(DATE_RFC7231), $new->getHeaderLine('Expires'));
  390. $time = new NativeDateTime('+1 day', new DateTimeZone('UTC'));
  391. $new = $response->withExpires('+1 day');
  392. $this->assertSame($time->format(DATE_RFC7231), $new->getHeaderLine('Expires'));
  393. }
  394. /**
  395. * Tests the withModified method
  396. */
  397. public function testWithModified(): void
  398. {
  399. $response = new Response();
  400. $now = new NativeDateTime('now', new DateTimeZone('America/Los_Angeles'));
  401. $new = $response->withModified($now);
  402. $this->assertFalse($response->hasHeader('Last-Modified'));
  403. $now->setTimeZone(new DateTimeZone('UTC'));
  404. $this->assertSame($now->format(DATE_RFC7231), $new->getHeaderLine('Last-Modified'));
  405. $now = time();
  406. $new = $response->withModified($now);
  407. $this->assertSame(gmdate(DATE_RFC7231, $now), $new->getHeaderLine('Last-Modified'));
  408. $now = new DateTimeImmutable();
  409. $new = $response->withModified($now);
  410. $this->assertSame(gmdate(DATE_RFC7231, $now->getTimestamp()), $new->getHeaderLine('Last-Modified'));
  411. $time = new NativeDateTime('+1 day', new DateTimeZone('UTC'));
  412. $new = $response->withModified('+1 day');
  413. $this->assertSame($time->format(DATE_RFC7231), $new->getHeaderLine('Last-Modified'));
  414. }
  415. /**
  416. * Tests withSharable()
  417. */
  418. public function testWithSharable(): void
  419. {
  420. $response = new Response();
  421. $new = $response->withSharable(true);
  422. $this->assertFalse($response->hasHeader('Cache-Control'), 'old instance unchanged');
  423. $this->assertSame('public', $new->getHeaderLine('Cache-Control'));
  424. $new = $response->withSharable(false);
  425. $this->assertSame('private', $new->getHeaderLine('Cache-Control'));
  426. $new = $response->withSharable(true, 3600);
  427. $this->assertSame('public, max-age=3600', $new->getHeaderLine('Cache-Control'));
  428. $new = $response->withSharable(false, 3600);
  429. $this->assertSame('private, max-age=3600', $new->getHeaderLine('Cache-Control'));
  430. }
  431. /**
  432. * Tests withMaxAge()
  433. */
  434. public function testWithMaxAge(): void
  435. {
  436. $response = new Response();
  437. $this->assertFalse($response->hasHeader('Cache-Control'));
  438. $new = $response->withMaxAge(3600);
  439. $this->assertSame('max-age=3600', $new->getHeaderLine('Cache-Control'));
  440. $new = $response->withMaxAge(3600)
  441. ->withSharable(false);
  442. $this->assertSame('max-age=3600, private', $new->getHeaderLine('Cache-Control'));
  443. }
  444. /**
  445. * Tests setting of s-maxage Cache-Control directive
  446. */
  447. public function testWithSharedMaxAge(): void
  448. {
  449. $response = new Response();
  450. $new = $response->withSharedMaxAge(3600);
  451. $this->assertFalse($response->hasHeader('Cache-Control'));
  452. $this->assertSame('s-maxage=3600', $new->getHeaderLine('Cache-Control'));
  453. $new = $response->withSharedMaxAge(3600)->withSharable(true);
  454. $this->assertSame('s-maxage=3600, public', $new->getHeaderLine('Cache-Control'));
  455. }
  456. /**
  457. * Tests setting of must-revalidate Cache-Control directive
  458. */
  459. public function testWithMustRevalidate(): void
  460. {
  461. $response = new Response();
  462. $this->assertFalse($response->hasHeader('Cache-Control'));
  463. $new = $response->withMustRevalidate(true);
  464. $this->assertFalse($response->hasHeader('Cache-Control'));
  465. $this->assertSame('must-revalidate', $new->getHeaderLine('Cache-Control'));
  466. $new = $new->withMustRevalidate(false);
  467. $this->assertEmpty($new->getHeaderLine('Cache-Control'));
  468. }
  469. /**
  470. * Tests withVary()
  471. */
  472. public function testWithVary(): void
  473. {
  474. $response = new Response();
  475. $new = $response->withVary('Accept-encoding');
  476. $this->assertFalse($response->hasHeader('Vary'));
  477. $this->assertSame('Accept-encoding', $new->getHeaderLine('Vary'));
  478. $new = $response->withVary(['Accept-encoding', 'Accept-language']);
  479. $this->assertFalse($response->hasHeader('Vary'));
  480. $this->assertSame('Accept-encoding,Accept-language', $new->getHeaderLine('Vary'));
  481. }
  482. /**
  483. * Tests withEtag()
  484. */
  485. public function testWithEtag(): void
  486. {
  487. $response = new Response();
  488. $new = $response->withEtag('something');
  489. $this->assertFalse($response->hasHeader('Etag'));
  490. $this->assertSame('"something"', $new->getHeaderLine('Etag'));
  491. $new = $response->withEtag('something', true);
  492. $this->assertSame('W/"something"', $new->getHeaderLine('Etag'));
  493. }
  494. /**
  495. * Tests withNotModified()
  496. */
  497. public function testWithNotModified(): void
  498. {
  499. $response = new Response(['body' => 'something']);
  500. $response = $response->withLength(100)
  501. ->withStatus(200)
  502. ->withHeader('Last-Modified', 'value')
  503. ->withHeader('Content-Language', 'en-EN')
  504. ->withHeader('X-things', 'things')
  505. ->withType('application/json');
  506. $new = $response->withNotModified();
  507. $this->assertTrue($response->hasHeader('Content-Language'), 'old instance not changed');
  508. $this->assertTrue($response->hasHeader('Content-Length'), 'old instance not changed');
  509. $this->assertFalse($new->hasHeader('Content-Type'));
  510. $this->assertFalse($new->hasHeader('Content-Length'));
  511. $this->assertFalse($new->hasHeader('Content-Language'));
  512. $this->assertFalse($new->hasHeader('Last-Modified'));
  513. $this->assertSame('things', $new->getHeaderLine('X-things'), 'Other headers are retained');
  514. $this->assertSame(304, $new->getStatusCode());
  515. $this->assertSame('', $new->getBody()->getContents());
  516. }
  517. /**
  518. * Test checkNotModified method
  519. */
  520. public function testCheckNotModifiedByEtagStar(): void
  521. {
  522. $request = new ServerRequest();
  523. $request = $request->withHeader('If-None-Match', '*');
  524. $response = new Response();
  525. $response = $response->withEtag('something')
  526. ->withHeader('Content-Length', 99);
  527. $this->assertTrue($response->isNotModified($request));
  528. }
  529. /**
  530. * Test checkNotModified method
  531. */
  532. public function testCheckNotModifiedByEtagExact(): void
  533. {
  534. $request = new ServerRequest();
  535. $request = $request->withHeader('If-None-Match', 'W/"something", "other"');
  536. $response = new Response();
  537. $response = $response->withEtag('something', true)
  538. ->withHeader('Content-Length', 99);
  539. $this->assertTrue($response->isNotModified($request));
  540. }
  541. /**
  542. * Test checkNotModified method
  543. */
  544. public function testCheckNotModifiedByEtagAndTime(): void
  545. {
  546. $request = new ServerRequest();
  547. $request = $request->withHeader('If-Modified-Since', '2012-01-01 00:00:00')
  548. ->withHeader('If-None-Match', 'W/"something", "other"');
  549. $response = new Response();
  550. $response = $response->withModified('2012-01-01 00:00:00')
  551. ->withEtag('something', true)
  552. ->withHeader('Content-Length', 99);
  553. $this->assertTrue($response->isNotModified($request));
  554. }
  555. /**
  556. * Test checkNotModified method
  557. */
  558. public function testCheckNotModifiedByEtagAndTimeMismatch(): void
  559. {
  560. $request = new ServerRequest();
  561. $request = $request->withHeader('If-Modified-Since', '2012-01-01 00:00:00')
  562. ->withHeader('If-None-Match', 'W/"something", "other"');
  563. $response = new Response();
  564. $response = $response->withModified('2012-01-01 00:00:01')
  565. ->withEtag('something', true)
  566. ->withHeader('Content-Length', 99);
  567. $this->assertFalse($response->isNotModified($request));
  568. }
  569. /**
  570. * Test checkNotModified method
  571. */
  572. public function testCheckNotModifiedByEtagMismatch(): void
  573. {
  574. $request = new ServerRequest();
  575. $request = $request->withHeader('If-Modified-Since', '2012-01-01 00:00:00')
  576. ->withHeader('If-None-Match', 'W/"something-else", "other"');
  577. $response = new Response();
  578. $response = $response->withModified('2012-01-01 00:00:00')
  579. ->withEtag('something', true)
  580. ->withHeader('Content-Length', 99);
  581. $this->assertFalse($response->isNotModified($request));
  582. }
  583. /**
  584. * Test checkNotModified method
  585. */
  586. public function testCheckNotModifiedByTime(): void
  587. {
  588. $request = new ServerRequest();
  589. $request = $request->withHeader('If-Modified-Since', '2012-01-01 00:00:00');
  590. $response = new Response();
  591. $response = $response->withModified('2012-01-01 00:00:00')
  592. ->withHeader('Content-Length', 99);
  593. $this->assertTrue($response->isNotModified($request));
  594. }
  595. /**
  596. * Test checkNotModified method
  597. */
  598. public function testCheckNotModifiedNoHints(): void
  599. {
  600. $request = new ServerRequest();
  601. $request = $request->withHeader('If-None-Match', 'W/"something", "other"')
  602. ->withHeader('If-Modified-Since', '2012-01-01 00:00:00');
  603. $response = new Response();
  604. $this->assertFalse($response->isNotModified($request));
  605. }
  606. /**
  607. * Test setting cookies with no value
  608. */
  609. public function testWithCookieEmpty(): void
  610. {
  611. $response = new Response();
  612. $new = $response->withCookie(new Cookie('testing'));
  613. $this->assertNull($response->getCookie('testing'), 'withCookie does not mutate');
  614. $expected = [
  615. 'name' => 'testing',
  616. 'value' => '',
  617. 'expires' => 0,
  618. 'path' => '/',
  619. 'domain' => '',
  620. 'secure' => false,
  621. 'httponly' => false,
  622. ];
  623. $result = $new->getCookie('testing');
  624. $this->assertEquals($expected, $result);
  625. }
  626. /**
  627. * Test setting cookies with scalar values
  628. */
  629. public function testWithCookieScalar(): void
  630. {
  631. $response = new Response();
  632. $new = $response->withCookie(new Cookie('testing', 'abc123'));
  633. $this->assertNull($response->getCookie('testing'), 'withCookie does not mutate');
  634. $this->assertSame('abc123', $new->getCookie('testing')['value']);
  635. $new = $response->withCookie(new Cookie('testing', 0.99));
  636. $this->assertEquals(0.99, $new->getCookie('testing')['value']);
  637. $new = $response->withCookie(new Cookie('testing', 99));
  638. $this->assertEquals(99, $new->getCookie('testing')['value']);
  639. $new = $response->withCookie(new Cookie('testing', false));
  640. $this->assertSame('', $new->getCookie('testing')['value']);
  641. $new = $response->withCookie(new Cookie('testing', true));
  642. $this->assertSame('1', $new->getCookie('testing')['value']);
  643. }
  644. /**
  645. * Test withCookie() and duplicate data
  646. *
  647. * @throws \Exception
  648. */
  649. public function testWithDuplicateCookie(): void
  650. {
  651. $expiry = new DateTimeImmutable('+24 hours');
  652. $response = new Response();
  653. $cookie = new Cookie(
  654. 'testing',
  655. '[a,b,c]',
  656. $expiry,
  657. '/test',
  658. '',
  659. true
  660. );
  661. $new = $response->withCookie($cookie);
  662. $this->assertNull($response->getCookie('testing'), 'withCookie does not mutate');
  663. $expected = [
  664. 'name' => 'testing',
  665. 'value' => '[a,b,c]',
  666. 'expires' => $expiry,
  667. 'path' => '/test',
  668. 'domain' => '',
  669. 'secure' => true,
  670. 'httponly' => false,
  671. ];
  672. // Match the date time formatting to Response::convertCookieToArray
  673. $expected['expires'] = $expiry->format('U');
  674. $this->assertEquals($expected, $new->getCookie('testing'));
  675. }
  676. /**
  677. * Test withCookie() and a cookie instance
  678. */
  679. public function testWithCookieObject(): void
  680. {
  681. $response = new Response();
  682. $cookie = new Cookie('yay', 'a value');
  683. $new = $response->withCookie($cookie);
  684. $this->assertNull($response->getCookie('yay'), 'withCookie does not mutate');
  685. $this->assertNotEmpty($new->getCookie('yay'));
  686. $this->assertSame($cookie, $new->getCookieCollection()->get('yay'));
  687. }
  688. public function testWithExpiredCookieScalar(): void
  689. {
  690. $response = new Response();
  691. $response = $response->withCookie(new Cookie('testing', 'abc123'));
  692. $this->assertSame('abc123', $response->getCookie('testing')['value']);
  693. $new = $response->withExpiredCookie(new Cookie('testing'));
  694. $this->assertSame(0, $response->getCookie('testing')['expires']);
  695. $this->assertLessThan(DateTime::createFromTimestamp(1), (string)$new->getCookie('testing')['expires']);
  696. }
  697. /**
  698. * @throws \Exception If DateImmutable emits an error.
  699. */
  700. public function testWithExpiredCookieOptions(): void
  701. {
  702. $options = [
  703. 'name' => 'testing',
  704. 'value' => 'abc123',
  705. 'options' => [
  706. 'domain' => 'cakephp.org',
  707. 'path' => '/custompath/',
  708. 'secure' => true,
  709. 'httponly' => true,
  710. 'expires' => new DateTimeImmutable('+14 days'),
  711. ],
  712. ];
  713. $cookie = Cookie::create(
  714. $options['name'],
  715. $options['value'],
  716. $options['options']
  717. );
  718. $response = new Response();
  719. $response = $response->withCookie($cookie);
  720. $options['options']['expires'] = $options['options']['expires']->format('U');
  721. $expected = ['name' => $options['name'], 'value' => $options['value']] + $options['options'];
  722. $this->assertEquals($expected, $response->getCookie('testing'));
  723. $expiredCookie = $response->withExpiredCookie($cookie);
  724. $this->assertSame($expected['expires'], (string)$response->getCookie('testing')['expires']);
  725. $this->assertLessThan(DateTime::createFromTimestamp(1), (string)$expiredCookie->getCookie('testing')['expires']);
  726. }
  727. public function testWithExpiredCookieObject(): void
  728. {
  729. $response = new Response();
  730. $cookie = new Cookie('yay', 'a value');
  731. $response = $response->withCookie($cookie);
  732. $this->assertSame('a value', $response->getCookie('yay')['value']);
  733. $new = $response->withExpiredCookie($cookie);
  734. $this->assertSame(0, $response->getCookie('yay')['expires']);
  735. $this->assertSame(1, $new->getCookie('yay')['expires']);
  736. }
  737. public function testWithExpiredCookieNotUtc(): void
  738. {
  739. date_default_timezone_set('Europe/Paris');
  740. $response = new Response();
  741. $cookie = new Cookie('yay', 'a value');
  742. $response = $response->withExpiredCookie($cookie);
  743. date_default_timezone_set('UTC');
  744. $this->assertSame(1, $response->getCookie('yay')['expires']);
  745. }
  746. /**
  747. * Test getCookies() and array data.
  748. */
  749. public function testGetCookies(): void
  750. {
  751. $response = new Response();
  752. $new = $response->withCookie(new Cookie('testing', 'a'))
  753. ->withCookie(new Cookie('test2', 'b', null, '/test', '', true));
  754. $expected = [
  755. 'testing' => [
  756. 'name' => 'testing',
  757. 'value' => 'a',
  758. 'expires' => 0,
  759. 'path' => '/',
  760. 'domain' => '',
  761. 'secure' => false,
  762. 'httponly' => false,
  763. ],
  764. 'test2' => [
  765. 'name' => 'test2',
  766. 'value' => 'b',
  767. 'expires' => 0,
  768. 'path' => '/test',
  769. 'domain' => '',
  770. 'secure' => true,
  771. 'httponly' => false,
  772. ],
  773. ];
  774. $this->assertEquals($expected, $new->getCookies());
  775. }
  776. /**
  777. * Test getCookies() and array data.
  778. */
  779. public function testGetCookiesArrayValue(): void
  780. {
  781. $response = new Response();
  782. $cookie = (new Cookie('urmc'))
  783. ->withValue(['user_id' => 1, 'token' => 'abc123'])
  784. ->withHttpOnly(true);
  785. $new = $response->withCookie($cookie);
  786. $expected = [
  787. 'urmc' => [
  788. 'name' => 'urmc',
  789. 'value' => '{"user_id":1,"token":"abc123"}',
  790. 'expires' => 0,
  791. 'path' => '/',
  792. 'domain' => '',
  793. 'secure' => false,
  794. 'httponly' => true,
  795. ],
  796. ];
  797. $this->assertEquals($expected, $new->getCookies());
  798. }
  799. /**
  800. * Test getCookieCollection() as array data
  801. */
  802. public function testGetCookieCollection(): void
  803. {
  804. $response = new Response();
  805. $new = $response->withCookie(new Cookie('testing', 'a'))
  806. ->withCookie(new Cookie('test2', 'b', null, '/test', '', true));
  807. $cookies = $response->getCookieCollection();
  808. $this->assertInstanceOf(CookieCollection::class, $cookies);
  809. $this->assertCount(0, $cookies, 'Original response not mutated');
  810. $cookies = $new->getCookieCollection();
  811. $this->assertInstanceOf(CookieCollection::class, $cookies);
  812. $this->assertCount(2, $cookies);
  813. $this->assertTrue($cookies->has('testing'));
  814. $this->assertTrue($cookies->has('test2'));
  815. }
  816. /**
  817. * Test withCookieCollection()
  818. */
  819. public function testWithCookieCollection(): void
  820. {
  821. $response = new Response();
  822. $collection = new CookieCollection([new Cookie('foo', 'bar')]);
  823. $newResponse = $response->withCookieCollection($collection);
  824. $this->assertNotSame($response, $newResponse);
  825. $this->assertNotSame($response->getCookieCollection(), $newResponse->getCookieCollection());
  826. $this->assertSame($newResponse->getCookie('foo')['value'], 'bar');
  827. }
  828. /**
  829. * Test that cors() returns a builder.
  830. */
  831. public function testCors(): void
  832. {
  833. $request = new ServerRequest([
  834. 'environment' => ['HTTP_ORIGIN' => 'http://example.com'],
  835. ]);
  836. $response = new Response();
  837. $builder = $response->cors($request);
  838. $this->assertInstanceOf(CorsBuilder::class, $builder);
  839. $this->assertSame($response, $builder->build(), 'Empty builder returns same object');
  840. }
  841. /**
  842. * test withFile() not found
  843. */
  844. public function testWithFileNotFound(): void
  845. {
  846. $this->expectException(NotFoundException::class);
  847. $this->expectExceptionMessage('The requested file /some/missing/folder/file.jpg was not found');
  848. $response = new Response();
  849. $response->withFile('/some/missing/folder/file.jpg');
  850. }
  851. /**
  852. * test withFile() not found
  853. */
  854. public function testWithFileNotFoundNoDebug(): void
  855. {
  856. Configure::write('debug', 0);
  857. $this->expectException(NotFoundException::class);
  858. $this->expectExceptionMessage('The requested file was not found');
  859. $response = new Response();
  860. $response->withFile('/some/missing/folder/file.jpg');
  861. }
  862. /**
  863. * Provider for various kinds of unacceptable files.
  864. *
  865. * @return array
  866. */
  867. public static function invalidFileProvider(): array
  868. {
  869. return [
  870. ['my/../cat.gif', 'The requested file contains `..` and will not be read.'],
  871. ['my\..\cat.gif', 'The requested file contains `..` and will not be read.'],
  872. ['my/ca..t.gif', 'my/ca..t.gif was not found or not readable'],
  873. ['my/ca..t/image.gif', 'my/ca..t/image.gif was not found or not readable'],
  874. ];
  875. }
  876. /**
  877. * test withFile and invalid paths
  878. */
  879. #[DataProvider('invalidFileProvider')]
  880. public function testWithFileInvalidPath(string $path, string $expectedMessage): void
  881. {
  882. $this->expectException(NotFoundException::class);
  883. $this->expectExceptionMessage($expectedMessage);
  884. $response = new Response();
  885. $response->withFile($path);
  886. }
  887. /**
  888. * test withFile() + download & name
  889. */
  890. public function testWithFileDownloadAndName(): void
  891. {
  892. $response = new Response();
  893. $new = $response->withFile(
  894. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  895. [
  896. 'name' => 'something_special.css',
  897. 'download' => true,
  898. ]
  899. );
  900. $this->assertSame(
  901. 'text/html; charset=UTF-8',
  902. $response->getHeaderLine('Content-Type'),
  903. 'No mutation'
  904. );
  905. $this->assertSame(
  906. 'text/css; charset=UTF-8',
  907. $new->getHeaderLine('Content-Type')
  908. );
  909. $this->assertSame(
  910. 'attachment; filename="something_special.css"',
  911. $new->getHeaderLine('Content-Disposition')
  912. );
  913. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  914. $this->assertSame('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  915. $body = $new->getBody();
  916. $this->assertInstanceOf(Stream::class, $body);
  917. $expected = '/* this is the test asset css file */';
  918. $this->assertSame($expected, trim($body->getContents()));
  919. $file = $new->getFile()->openFile();
  920. $this->assertSame($expected, trim($file->fread(100)));
  921. }
  922. /**
  923. * test withFile() + a generic agent
  924. */
  925. public function testWithFileUnknownFileTypeGeneric(): void
  926. {
  927. $response = new Response();
  928. $new = $response->withFile(CONFIG . 'no_section.ini');
  929. $this->assertSame('text/html; charset=UTF-8', $new->getHeaderLine('Content-Type'));
  930. $this->assertSame(
  931. 'attachment; filename="no_section.ini"',
  932. $new->getHeaderLine('Content-Disposition')
  933. );
  934. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  935. $body = $new->getBody();
  936. $expected = "some_key = some_value\nbool_key = 1\n";
  937. $this->assertSame($expected, $body->getContents());
  938. }
  939. /**
  940. * test withFile() + opera
  941. */
  942. public function testWithFileUnknownFileTypeOpera(): void
  943. {
  944. $_SERVER['HTTP_USER_AGENT'] = 'Opera/9.80 (Windows NT 6.0; U; en) Presto/2.8.99 Version/11.10';
  945. $response = new Response();
  946. $new = $response->withFile(CONFIG . 'no_section.ini');
  947. $this->assertSame('application/octet-stream', $new->getHeaderLine('Content-Type'));
  948. $this->assertSame(
  949. 'attachment; filename="no_section.ini"',
  950. $new->getHeaderLine('Content-Disposition')
  951. );
  952. }
  953. /**
  954. * test withFile() + old IE
  955. */
  956. public function testWithFileUnknownFileTypeOldIe(): void
  957. {
  958. $_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)';
  959. $response = new Response();
  960. $new = $response->withFile(CONFIG . 'no_section.ini');
  961. $this->assertSame('application/force-download', $new->getHeaderLine('Content-Type'));
  962. }
  963. /**
  964. * test withFile() + no download
  965. */
  966. public function testWithFileNoDownload(): void
  967. {
  968. $response = new Response();
  969. $new = $response->withFile(CONFIG . 'no_section.ini', [
  970. 'download' => false,
  971. ]);
  972. $this->assertSame(
  973. 'text/html; charset=UTF-8',
  974. $new->getHeaderLine('Content-Type')
  975. );
  976. $this->assertFalse($new->hasHeader('Content-Disposition'));
  977. $this->assertFalse($new->hasHeader('Content-Transfer-Encoding'));
  978. }
  979. /**
  980. * Test that uppercase extensions result in correct content-types
  981. */
  982. public function testWithFileUpperExtension(): void
  983. {
  984. $response = new Response();
  985. $new = $response->withFile(TEST_APP . 'vendor/img/test_2.JPG');
  986. $this->assertSame('image/jpeg', $new->getHeaderLine('Content-Type'));
  987. }
  988. /**
  989. * A data provider for testing various ranges
  990. *
  991. * @return array
  992. */
  993. public static function rangeProvider(): array
  994. {
  995. return [
  996. // suffix-byte-range
  997. [
  998. 'bytes=-25', 25, 'bytes 13-37/38',
  999. ],
  1000. [
  1001. 'bytes=0-', 38, 'bytes 0-37/38',
  1002. ],
  1003. [
  1004. 'bytes=10-', 28, 'bytes 10-37/38',
  1005. ],
  1006. [
  1007. 'bytes=10-20', 11, 'bytes 10-20/38',
  1008. ],
  1009. // Spaced out
  1010. [
  1011. 'bytes = 10 - 20', 11, 'bytes 10-20/38',
  1012. ],
  1013. ];
  1014. }
  1015. /**
  1016. * Test withFile() & the various range offset types.
  1017. */
  1018. #[DataProvider('rangeProvider')]
  1019. public function testWithFileRangeOffsets(string $range, int $length, string $offsetResponse): void
  1020. {
  1021. $_SERVER['HTTP_RANGE'] = $range;
  1022. $response = new Response();
  1023. $new = $response->withFile(
  1024. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1025. ['download' => true]
  1026. );
  1027. $this->assertSame(
  1028. 'attachment; filename="test_asset.css"',
  1029. $new->getHeaderLine('Content-Disposition')
  1030. );
  1031. $this->assertSame('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  1032. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  1033. $this->assertEquals($length, $new->getHeaderLine('Content-Length'));
  1034. $this->assertEquals($offsetResponse, $new->getHeaderLine('Content-Range'));
  1035. }
  1036. /**
  1037. * Test withFile() fetching ranges from a file.
  1038. */
  1039. public function testWithFileRange(): void
  1040. {
  1041. $_SERVER['HTTP_RANGE'] = 'bytes=8-25';
  1042. $response = new Response();
  1043. $new = $response->withFile(
  1044. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1045. ['download' => true]
  1046. );
  1047. $this->assertSame(
  1048. 'attachment; filename="test_asset.css"',
  1049. $new->getHeaderLine('Content-Disposition')
  1050. );
  1051. $this->assertSame('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  1052. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  1053. $this->assertSame('18', $new->getHeaderLine('Content-Length'));
  1054. $this->assertSame('bytes 8-25/38', $new->getHeaderLine('Content-Range'));
  1055. $this->assertSame(206, $new->getStatusCode());
  1056. }
  1057. /**
  1058. * Provider for invalid range header values.
  1059. *
  1060. * @return array
  1061. */
  1062. public static function invalidFileRangeProvider(): array
  1063. {
  1064. return [
  1065. // malformed range
  1066. [
  1067. 'bytes=0,38',
  1068. ],
  1069. // malformed punctuation
  1070. [
  1071. 'bytes: 0 - 38',
  1072. ],
  1073. ];
  1074. }
  1075. /**
  1076. * Test withFile() and invalid ranges
  1077. */
  1078. #[DataProvider('invalidFileRangeProvider')]
  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(StreamInterface::class, $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. }