ResponseTest.php 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562
  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->assertEquals(false, $new->getCookie('testing')['value']);
  638. $new = $response->withCookie(new Cookie('testing', true));
  639. $this->assertEquals(true, $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. /**
  735. * Test getCookies() and array data.
  736. */
  737. public function testGetCookies(): void
  738. {
  739. $response = new Response();
  740. $new = $response->withCookie(new Cookie('testing', 'a'))
  741. ->withCookie(new Cookie('test2', 'b', null, '/test', '', true));
  742. $expected = [
  743. 'testing' => [
  744. 'name' => 'testing',
  745. 'value' => 'a',
  746. 'expires' => 0,
  747. 'path' => '/',
  748. 'domain' => '',
  749. 'secure' => false,
  750. 'httponly' => false,
  751. ],
  752. 'test2' => [
  753. 'name' => 'test2',
  754. 'value' => 'b',
  755. 'expires' => 0,
  756. 'path' => '/test',
  757. 'domain' => '',
  758. 'secure' => true,
  759. 'httponly' => false,
  760. ],
  761. ];
  762. $this->assertEquals($expected, $new->getCookies());
  763. }
  764. /**
  765. * Test getCookies() and array data.
  766. */
  767. public function testGetCookiesArrayValue(): void
  768. {
  769. $response = new Response();
  770. $cookie = (new Cookie('urmc'))
  771. ->withValue(['user_id' => 1, 'token' => 'abc123'])
  772. ->withHttpOnly(true);
  773. $new = $response->withCookie($cookie);
  774. $expected = [
  775. 'urmc' => [
  776. 'name' => 'urmc',
  777. 'value' => '{"user_id":1,"token":"abc123"}',
  778. 'expires' => 0,
  779. 'path' => '/',
  780. 'domain' => '',
  781. 'secure' => false,
  782. 'httponly' => true,
  783. ],
  784. ];
  785. $this->assertEquals($expected, $new->getCookies());
  786. }
  787. /**
  788. * Test getCookieCollection() as array data
  789. */
  790. public function testGetCookieCollection(): void
  791. {
  792. $response = new Response();
  793. $new = $response->withCookie(new Cookie('testing', 'a'))
  794. ->withCookie(new Cookie('test2', 'b', null, '/test', '', true));
  795. $cookies = $response->getCookieCollection();
  796. $this->assertInstanceOf(CookieCollection::class, $cookies);
  797. $this->assertCount(0, $cookies, 'Original response not mutated');
  798. $cookies = $new->getCookieCollection();
  799. $this->assertInstanceOf(CookieCollection::class, $cookies);
  800. $this->assertCount(2, $cookies);
  801. $this->assertTrue($cookies->has('testing'));
  802. $this->assertTrue($cookies->has('test2'));
  803. }
  804. /**
  805. * Test withCookieCollection()
  806. */
  807. public function testWithCookieCollection(): void
  808. {
  809. $response = new Response();
  810. $collection = new CookieCollection([new Cookie('foo', 'bar')]);
  811. $newResponse = $response->withCookieCollection($collection);
  812. $this->assertNotSame($response, $newResponse);
  813. $this->assertNotSame($response->getCookieCollection(), $newResponse->getCookieCollection());
  814. $this->assertSame($newResponse->getCookie('foo')['value'], 'bar');
  815. }
  816. /**
  817. * Test that cors() returns a builder.
  818. */
  819. public function testCors(): void
  820. {
  821. $request = new ServerRequest([
  822. 'environment' => ['HTTP_ORIGIN' => 'http://example.com'],
  823. ]);
  824. $response = new Response();
  825. $builder = $response->cors($request);
  826. $this->assertInstanceOf(CorsBuilder::class, $builder);
  827. $this->assertSame($response, $builder->build(), 'Empty builder returns same object');
  828. }
  829. /**
  830. * test withFile() not found
  831. */
  832. public function testWithFileNotFound(): void
  833. {
  834. $this->expectException(NotFoundException::class);
  835. $this->expectExceptionMessage('The requested file /some/missing/folder/file.jpg was not found');
  836. $response = new Response();
  837. $response->withFile('/some/missing/folder/file.jpg');
  838. }
  839. /**
  840. * test withFile() not found
  841. */
  842. public function testWithFileNotFoundNoDebug(): void
  843. {
  844. Configure::write('debug', 0);
  845. $this->expectException(NotFoundException::class);
  846. $this->expectExceptionMessage('The requested file was not found');
  847. $response = new Response();
  848. $response->withFile('/some/missing/folder/file.jpg');
  849. }
  850. /**
  851. * Provider for various kinds of unacceptable files.
  852. *
  853. * @return array
  854. */
  855. public function invalidFileProvider(): array
  856. {
  857. return [
  858. ['my/../cat.gif', 'The requested file contains `..` and will not be read.'],
  859. ['my\..\cat.gif', 'The requested file contains `..` and will not be read.'],
  860. ['my/ca..t.gif', 'my/ca..t.gif was not found or not readable'],
  861. ['my/ca..t/image.gif', 'my/ca..t/image.gif was not found or not readable'],
  862. ];
  863. }
  864. /**
  865. * test withFile and invalid paths
  866. *
  867. * @dataProvider invalidFileProvider
  868. */
  869. public function testWithFileInvalidPath(string $path, string $expectedMessage): void
  870. {
  871. $this->expectException(NotFoundException::class);
  872. $this->expectExceptionMessage($expectedMessage);
  873. $response = new Response();
  874. $response->withFile($path);
  875. }
  876. /**
  877. * test withFile() + download & name
  878. */
  879. public function testWithFileDownloadAndName(): void
  880. {
  881. $response = new Response();
  882. $new = $response->withFile(
  883. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  884. [
  885. 'name' => 'something_special.css',
  886. 'download' => true,
  887. ]
  888. );
  889. $this->assertSame(
  890. 'text/html; charset=UTF-8',
  891. $response->getHeaderLine('Content-Type'),
  892. 'No mutation'
  893. );
  894. $this->assertSame(
  895. 'text/css; charset=UTF-8',
  896. $new->getHeaderLine('Content-Type')
  897. );
  898. $this->assertSame(
  899. 'attachment; filename="something_special.css"',
  900. $new->getHeaderLine('Content-Disposition')
  901. );
  902. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  903. $this->assertSame('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  904. $body = $new->getBody();
  905. $this->assertInstanceOf('Laminas\Diactoros\Stream', $body);
  906. $expected = '/* this is the test asset css file */';
  907. $this->assertSame($expected, trim($body->getContents()));
  908. $file = $new->getFile()->openFile();
  909. $this->assertSame($expected, trim($file->fread(100)));
  910. }
  911. /**
  912. * test withFile() + a generic agent
  913. */
  914. public function testWithFileUnknownFileTypeGeneric(): void
  915. {
  916. $response = new Response();
  917. $new = $response->withFile(CONFIG . 'no_section.ini');
  918. $this->assertSame('text/html; charset=UTF-8', $new->getHeaderLine('Content-Type'));
  919. $this->assertSame(
  920. 'attachment; filename="no_section.ini"',
  921. $new->getHeaderLine('Content-Disposition')
  922. );
  923. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  924. $body = $new->getBody();
  925. $expected = "some_key = some_value\nbool_key = 1\n";
  926. $this->assertSame($expected, $body->getContents());
  927. }
  928. /**
  929. * test withFile() + opera
  930. */
  931. public function testWithFileUnknownFileTypeOpera(): void
  932. {
  933. $_SERVER['HTTP_USER_AGENT'] = 'Opera/9.80 (Windows NT 6.0; U; en) Presto/2.8.99 Version/11.10';
  934. $response = new Response();
  935. $new = $response->withFile(CONFIG . 'no_section.ini');
  936. $this->assertSame('application/octet-stream', $new->getHeaderLine('Content-Type'));
  937. $this->assertSame(
  938. 'attachment; filename="no_section.ini"',
  939. $new->getHeaderLine('Content-Disposition')
  940. );
  941. }
  942. /**
  943. * test withFile() + old IE
  944. */
  945. public function testWithFileUnknownFileTypeOldIe(): void
  946. {
  947. $_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)';
  948. $response = new Response();
  949. $new = $response->withFile(CONFIG . 'no_section.ini');
  950. $this->assertSame('application/force-download', $new->getHeaderLine('Content-Type'));
  951. }
  952. /**
  953. * test withFile() + no download
  954. */
  955. public function testWithFileNoDownload(): void
  956. {
  957. $response = new Response();
  958. $new = $response->withFile(CONFIG . 'no_section.ini', [
  959. 'download' => false,
  960. ]);
  961. $this->assertSame(
  962. 'text/html; charset=UTF-8',
  963. $new->getHeaderLine('Content-Type')
  964. );
  965. $this->assertFalse($new->hasHeader('Content-Disposition'));
  966. $this->assertFalse($new->hasHeader('Content-Transfer-Encoding'));
  967. }
  968. /**
  969. * Test that uppercase extensions result in correct content-types
  970. */
  971. public function testWithFileUpperExtension(): void
  972. {
  973. $response = new Response();
  974. $new = $response->withFile(TEST_APP . 'vendor/img/test_2.JPG');
  975. $this->assertSame('image/jpeg', $new->getHeaderLine('Content-Type'));
  976. }
  977. /**
  978. * A data provider for testing various ranges
  979. *
  980. * @return array
  981. */
  982. public static function rangeProvider(): array
  983. {
  984. return [
  985. // suffix-byte-range
  986. [
  987. 'bytes=-25', 25, 'bytes 13-37/38',
  988. ],
  989. [
  990. 'bytes=0-', 38, 'bytes 0-37/38',
  991. ],
  992. [
  993. 'bytes=10-', 28, 'bytes 10-37/38',
  994. ],
  995. [
  996. 'bytes=10-20', 11, 'bytes 10-20/38',
  997. ],
  998. // Spaced out
  999. [
  1000. 'bytes = 10 - 20', 11, 'bytes 10-20/38',
  1001. ],
  1002. ];
  1003. }
  1004. /**
  1005. * Test withFile() & the various range offset types.
  1006. *
  1007. * @dataProvider rangeProvider
  1008. */
  1009. public function testWithFileRangeOffsets(string $range, int $length, string $offsetResponse): void
  1010. {
  1011. $_SERVER['HTTP_RANGE'] = $range;
  1012. $response = new Response();
  1013. $new = $response->withFile(
  1014. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1015. ['download' => true]
  1016. );
  1017. $this->assertSame(
  1018. 'attachment; filename="test_asset.css"',
  1019. $new->getHeaderLine('Content-Disposition')
  1020. );
  1021. $this->assertSame('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  1022. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  1023. $this->assertEquals($length, $new->getHeaderLine('Content-Length'));
  1024. $this->assertEquals($offsetResponse, $new->getHeaderLine('Content-Range'));
  1025. }
  1026. /**
  1027. * Test withFile() fetching ranges from a file.
  1028. */
  1029. public function testWithFileRange(): void
  1030. {
  1031. $_SERVER['HTTP_RANGE'] = 'bytes=8-25';
  1032. $response = new Response();
  1033. $new = $response->withFile(
  1034. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1035. ['download' => true]
  1036. );
  1037. $this->assertSame(
  1038. 'attachment; filename="test_asset.css"',
  1039. $new->getHeaderLine('Content-Disposition')
  1040. );
  1041. $this->assertSame('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  1042. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  1043. $this->assertSame('18', $new->getHeaderLine('Content-Length'));
  1044. $this->assertSame('bytes 8-25/38', $new->getHeaderLine('Content-Range'));
  1045. $this->assertSame(206, $new->getStatusCode());
  1046. }
  1047. /**
  1048. * Provider for invalid range header values.
  1049. *
  1050. * @return array
  1051. */
  1052. public function invalidFileRangeProvider(): array
  1053. {
  1054. return [
  1055. // malformed range
  1056. [
  1057. 'bytes=0,38',
  1058. ],
  1059. // malformed punctuation
  1060. [
  1061. 'bytes: 0 - 38',
  1062. ],
  1063. ];
  1064. }
  1065. /**
  1066. * Test withFile() and invalid ranges
  1067. *
  1068. * @dataProvider invalidFileRangeProvider
  1069. */
  1070. public function testWithFileInvalidRange(string $range): void
  1071. {
  1072. $_SERVER['HTTP_RANGE'] = $range;
  1073. $response = new Response();
  1074. $new = $response->withFile(
  1075. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1076. ['download' => true]
  1077. );
  1078. $this->assertSame(
  1079. 'attachment; filename="test_asset.css"',
  1080. $new->getHeaderLine('Content-Disposition')
  1081. );
  1082. $this->assertSame('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  1083. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  1084. $this->assertSame('38', $new->getHeaderLine('Content-Length'));
  1085. $this->assertSame('bytes 0-37/38', $new->getHeaderLine('Content-Range'));
  1086. $this->assertSame(206, $new->getStatusCode());
  1087. }
  1088. /**
  1089. * Test withFile() and a reversed range
  1090. */
  1091. public function testWithFileReversedRange(): void
  1092. {
  1093. $_SERVER['HTTP_RANGE'] = 'bytes=30-2';
  1094. $response = new Response();
  1095. $new = $response->withFile(
  1096. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1097. ['download' => true]
  1098. );
  1099. $this->assertSame(
  1100. 'attachment; filename="test_asset.css"',
  1101. $new->getHeaderLine('Content-Disposition')
  1102. );
  1103. $this->assertSame('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  1104. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  1105. $this->assertSame('bytes 0-37/38', $new->getHeaderLine('Content-Range'));
  1106. $this->assertSame(416, $new->getStatusCode());
  1107. }
  1108. /**
  1109. * Test the withLocation method.
  1110. */
  1111. public function testWithLocation(): void
  1112. {
  1113. $response = new Response();
  1114. $this->assertSame('', $response->getHeaderLine('Location'), 'No header should be set.');
  1115. $new = $response->withLocation('http://example.org');
  1116. $this->assertNotSame($new, $response);
  1117. $this->assertSame('', $response->getHeaderLine('Location'), 'No header should be set');
  1118. $this->assertSame('http://example.org', $new->getHeaderLine('Location'), 'Header should be set');
  1119. $this->assertSame(302, $new->getStatusCode(), 'Status should be updated');
  1120. }
  1121. /**
  1122. * Test get protocol version.
  1123. */
  1124. public function getProtocolVersion(): void
  1125. {
  1126. $response = new Response();
  1127. $version = $response->getProtocolVersion();
  1128. $this->assertSame('1.1', $version);
  1129. }
  1130. /**
  1131. * Test with protocol.
  1132. */
  1133. public function testWithProtocol(): void
  1134. {
  1135. $response = new Response();
  1136. $version = $response->getProtocolVersion();
  1137. $this->assertSame('1.1', $version);
  1138. $response2 = $response->withProtocolVersion('1.0');
  1139. $version = $response2->getProtocolVersion();
  1140. $this->assertSame('1.0', $version);
  1141. $version = $response->getProtocolVersion();
  1142. $this->assertSame('1.1', $version);
  1143. $this->assertNotEquals($response, $response2);
  1144. }
  1145. /**
  1146. * Test with status code.
  1147. */
  1148. public function testWithStatusCode(): void
  1149. {
  1150. $response = new Response();
  1151. $statusCode = $response->getStatusCode();
  1152. $this->assertSame(200, $statusCode);
  1153. $response2 = $response->withStatus(404);
  1154. $statusCode = $response2->getStatusCode();
  1155. $this->assertSame(404, $statusCode);
  1156. $statusCode = $response->getStatusCode();
  1157. $this->assertSame(200, $statusCode);
  1158. $this->assertNotEquals($response, $response2);
  1159. $response3 = $response->withStatus(111);
  1160. $this->assertSame(111, $response3->getStatusCode());
  1161. $this->assertSame('', $response3->getReasonPhrase());
  1162. }
  1163. /**
  1164. * Test invalid status codes
  1165. */
  1166. public function testWithStatusInvalid(): void
  1167. {
  1168. $this->expectException(InvalidArgumentException::class);
  1169. $this->expectExceptionMessage('Invalid status code: 1001. Use a valid HTTP status code in range 1xx - 5xx.');
  1170. $response = new Response();
  1171. $response->withStatus(1001);
  1172. }
  1173. /**
  1174. * Test get reason phrase.
  1175. */
  1176. public function testGetReasonPhrase(): void
  1177. {
  1178. $response = new Response();
  1179. $this->assertSame('OK', $response->getReasonPhrase());
  1180. $response = $response->withStatus(404);
  1181. $reasonPhrase = $response->getReasonPhrase();
  1182. $this->assertSame('Not Found', $reasonPhrase);
  1183. }
  1184. /**
  1185. * Test with body.
  1186. */
  1187. public function testWithBody(): void
  1188. {
  1189. $response = new Response();
  1190. $body = $response->getBody();
  1191. $body->rewind();
  1192. $result = $body->getContents();
  1193. $this->assertSame('', $result);
  1194. $stream = new Stream('php://memory', 'wb+');
  1195. $stream->write('test1');
  1196. $response2 = $response->withBody($stream);
  1197. $body = $response2->getBody();
  1198. $body->rewind();
  1199. $result = $body->getContents();
  1200. $this->assertSame('test1', $result);
  1201. $body = $response->getBody();
  1202. $body->rewind();
  1203. $result = $body->getContents();
  1204. $this->assertSame('', $result);
  1205. }
  1206. /**
  1207. * Test with string body.
  1208. */
  1209. public function testWithStringBody(): void
  1210. {
  1211. $response = new Response();
  1212. $newResponse = $response->withStringBody('Foo');
  1213. $body = $newResponse->getBody();
  1214. $this->assertSame('Foo', (string)$body);
  1215. $this->assertNotSame($response, $newResponse);
  1216. $response = new Response();
  1217. $newResponse = $response->withStringBody('');
  1218. $body = $newResponse->getBody();
  1219. $this->assertSame('', (string)$body);
  1220. $this->assertNotSame($response, $newResponse);
  1221. $response = new Response();
  1222. $newResponse = $response->withStringBody(null);
  1223. $body = $newResponse->getBody();
  1224. $this->assertSame('', (string)$body);
  1225. $this->assertNotSame($response, $newResponse);
  1226. $response = new Response();
  1227. $newResponse = $response->withStringBody('1337');
  1228. $body = $newResponse->getBody();
  1229. $this->assertSame('1337', (string)$body);
  1230. $this->assertNotSame($response, $newResponse);
  1231. }
  1232. /**
  1233. * Test get Body.
  1234. */
  1235. public function testGetBody(): void
  1236. {
  1237. $response = new Response();
  1238. $stream = $response->getBody();
  1239. $this->assertInstanceOf('Psr\Http\Message\StreamInterface', $stream);
  1240. }
  1241. /**
  1242. * Test with header.
  1243. */
  1244. public function testWithHeader(): void
  1245. {
  1246. $response = new Response();
  1247. $response2 = $response->withHeader('Accept', 'application/json');
  1248. $result = $response2->getHeaders();
  1249. $expected = [
  1250. 'Content-Type' => ['text/html; charset=UTF-8'],
  1251. 'Accept' => ['application/json'],
  1252. ];
  1253. $this->assertEquals($expected, $result);
  1254. $this->assertFalse($response->hasHeader('Accept'));
  1255. }
  1256. /**
  1257. * Test get headers.
  1258. */
  1259. public function testGetHeaders(): void
  1260. {
  1261. $response = new Response();
  1262. $headers = $response->getHeaders();
  1263. $response = $response->withAddedHeader('Location', 'localhost');
  1264. $response = $response->withAddedHeader('Accept', 'application/json');
  1265. $headers = $response->getHeaders();
  1266. $expected = [
  1267. 'Content-Type' => ['text/html; charset=UTF-8'],
  1268. 'Location' => ['localhost'],
  1269. 'Accept' => ['application/json'],
  1270. ];
  1271. $this->assertEquals($expected, $headers);
  1272. }
  1273. /**
  1274. * Test without header.
  1275. */
  1276. public function testWithoutHeader(): void
  1277. {
  1278. $response = new Response();
  1279. $response = $response->withAddedHeader('Location', 'localhost');
  1280. $response = $response->withAddedHeader('Accept', 'application/json');
  1281. $response2 = $response->withoutHeader('Location');
  1282. $headers = $response2->getHeaders();
  1283. $expected = [
  1284. 'Content-Type' => ['text/html; charset=UTF-8'],
  1285. 'Accept' => ['application/json'],
  1286. ];
  1287. $this->assertEquals($expected, $headers);
  1288. }
  1289. /**
  1290. * Test get header.
  1291. */
  1292. public function testGetHeader(): void
  1293. {
  1294. $response = new Response();
  1295. $response = $response->withAddedHeader('Location', 'localhost');
  1296. $result = $response->getHeader('Location');
  1297. $this->assertEquals(['localhost'], $result);
  1298. $result = $response->getHeader('location');
  1299. $this->assertEquals(['localhost'], $result);
  1300. $result = $response->getHeader('does-not-exist');
  1301. $this->assertEquals([], $result);
  1302. }
  1303. /**
  1304. * Test get header line.
  1305. */
  1306. public function testGetHeaderLine(): void
  1307. {
  1308. $response = new Response();
  1309. $headers = $response->getHeaderLine('Accept');
  1310. $this->assertSame('', $headers);
  1311. $response = $response->withAddedHeader('Accept', 'application/json');
  1312. $response = $response->withAddedHeader('Accept', 'application/xml');
  1313. $result = $response->getHeaderLine('Accept');
  1314. $expected = 'application/json,application/xml';
  1315. $this->assertSame($expected, $result);
  1316. $result = $response->getHeaderLine('accept');
  1317. $this->assertSame($expected, $result);
  1318. }
  1319. /**
  1320. * Test has header.
  1321. */
  1322. public function testHasHeader(): void
  1323. {
  1324. $response = new Response();
  1325. $response = $response->withAddedHeader('Location', 'localhost');
  1326. $this->assertTrue($response->hasHeader('Location'));
  1327. $this->assertTrue($response->hasHeader('location'));
  1328. $this->assertTrue($response->hasHeader('locATIon'));
  1329. $this->assertFalse($response->hasHeader('Accept'));
  1330. $this->assertFalse($response->hasHeader('accept'));
  1331. }
  1332. /**
  1333. * Tests __debugInfo
  1334. */
  1335. public function testDebugInfo(): void
  1336. {
  1337. $response = new Response();
  1338. $response = $response->withStringBody('Foo');
  1339. $result = $response->__debugInfo();
  1340. $expected = [
  1341. 'status' => 200,
  1342. 'contentType' => 'text/html',
  1343. 'headers' => [
  1344. 'Content-Type' => ['text/html; charset=UTF-8'],
  1345. ],
  1346. 'file' => null,
  1347. 'fileRange' => [],
  1348. 'cookies' => new CookieCollection(),
  1349. 'cacheDirectives' => [],
  1350. 'body' => 'Foo',
  1351. ];
  1352. $this->assertEquals($expected, $result);
  1353. }
  1354. }