ResponseTest.php 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpFoundation\Tests;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\Response;
  13. /**
  14. * @group time-sensitive
  15. */
  16. class ResponseTest extends ResponseTestCase
  17. {
  18. public function testCreate()
  19. {
  20. $response = Response::create('foo', 301, array('Foo' => 'bar'));
  21. $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response);
  22. $this->assertEquals(301, $response->getStatusCode());
  23. $this->assertEquals('bar', $response->headers->get('foo'));
  24. }
  25. public function testToString()
  26. {
  27. $response = new Response();
  28. $response = explode("\r\n", $response);
  29. $this->assertEquals('HTTP/1.0 200 OK', $response[0]);
  30. $this->assertEquals('Cache-Control: no-cache, private', $response[1]);
  31. }
  32. public function testClone()
  33. {
  34. $response = new Response();
  35. $responseClone = clone $response;
  36. $this->assertEquals($response, $responseClone);
  37. }
  38. public function testSendHeaders()
  39. {
  40. $response = new Response();
  41. $headers = $response->sendHeaders();
  42. $this->assertObjectHasAttribute('headers', $headers);
  43. $this->assertObjectHasAttribute('content', $headers);
  44. $this->assertObjectHasAttribute('version', $headers);
  45. $this->assertObjectHasAttribute('statusCode', $headers);
  46. $this->assertObjectHasAttribute('statusText', $headers);
  47. $this->assertObjectHasAttribute('charset', $headers);
  48. }
  49. public function testSend()
  50. {
  51. $response = new Response();
  52. $responseSend = $response->send();
  53. $this->assertObjectHasAttribute('headers', $responseSend);
  54. $this->assertObjectHasAttribute('content', $responseSend);
  55. $this->assertObjectHasAttribute('version', $responseSend);
  56. $this->assertObjectHasAttribute('statusCode', $responseSend);
  57. $this->assertObjectHasAttribute('statusText', $responseSend);
  58. $this->assertObjectHasAttribute('charset', $responseSend);
  59. }
  60. public function testGetCharset()
  61. {
  62. $response = new Response();
  63. $charsetOrigin = 'UTF-8';
  64. $response->setCharset($charsetOrigin);
  65. $charset = $response->getCharset();
  66. $this->assertEquals($charsetOrigin, $charset);
  67. }
  68. public function testIsCacheable()
  69. {
  70. $response = new Response();
  71. $this->assertFalse($response->isCacheable());
  72. }
  73. public function testIsCacheableWithErrorCode()
  74. {
  75. $response = new Response('', 500);
  76. $this->assertFalse($response->isCacheable());
  77. }
  78. public function testIsCacheableWithNoStoreDirective()
  79. {
  80. $response = new Response();
  81. $response->headers->set('cache-control', 'private');
  82. $this->assertFalse($response->isCacheable());
  83. }
  84. public function testIsCacheableWithSetTtl()
  85. {
  86. $response = new Response();
  87. $response->setTtl(10);
  88. $this->assertTrue($response->isCacheable());
  89. }
  90. public function testMustRevalidate()
  91. {
  92. $response = new Response();
  93. $this->assertFalse($response->mustRevalidate());
  94. }
  95. public function testMustRevalidateWithMustRevalidateCacheControlHeader()
  96. {
  97. $response = new Response();
  98. $response->headers->set('cache-control', 'must-revalidate');
  99. $this->assertTrue($response->mustRevalidate());
  100. }
  101. public function testMustRevalidateWithProxyRevalidateCacheControlHeader()
  102. {
  103. $response = new Response();
  104. $response->headers->set('cache-control', 'proxy-revalidate');
  105. $this->assertTrue($response->mustRevalidate());
  106. }
  107. public function testSetNotModified()
  108. {
  109. $response = new Response('foo');
  110. $modified = $response->setNotModified();
  111. $this->assertObjectHasAttribute('headers', $modified);
  112. $this->assertObjectHasAttribute('content', $modified);
  113. $this->assertObjectHasAttribute('version', $modified);
  114. $this->assertObjectHasAttribute('statusCode', $modified);
  115. $this->assertObjectHasAttribute('statusText', $modified);
  116. $this->assertObjectHasAttribute('charset', $modified);
  117. $this->assertEquals(304, $modified->getStatusCode());
  118. ob_start();
  119. $modified->sendContent();
  120. $string = ob_get_clean();
  121. $this->assertEmpty($string);
  122. }
  123. public function testIsSuccessful()
  124. {
  125. $response = new Response();
  126. $this->assertTrue($response->isSuccessful());
  127. }
  128. public function testIsNotModified()
  129. {
  130. $response = new Response();
  131. $modified = $response->isNotModified(new Request());
  132. $this->assertFalse($modified);
  133. }
  134. public function testIsNotModifiedNotSafe()
  135. {
  136. $request = Request::create('/homepage', 'POST');
  137. $response = new Response();
  138. $this->assertFalse($response->isNotModified($request));
  139. }
  140. public function testIsNotModifiedLastModified()
  141. {
  142. $before = 'Sun, 25 Aug 2013 18:32:31 GMT';
  143. $modified = 'Sun, 25 Aug 2013 18:33:31 GMT';
  144. $after = 'Sun, 25 Aug 2013 19:33:31 GMT';
  145. $request = new Request();
  146. $request->headers->set('If-Modified-Since', $modified);
  147. $response = new Response();
  148. $response->headers->set('Last-Modified', $modified);
  149. $this->assertTrue($response->isNotModified($request));
  150. $response->headers->set('Last-Modified', $before);
  151. $this->assertTrue($response->isNotModified($request));
  152. $response->headers->set('Last-Modified', $after);
  153. $this->assertFalse($response->isNotModified($request));
  154. $response->headers->set('Last-Modified', '');
  155. $this->assertFalse($response->isNotModified($request));
  156. }
  157. public function testIsNotModifiedEtag()
  158. {
  159. $etagOne = 'randomly_generated_etag';
  160. $etagTwo = 'randomly_generated_etag_2';
  161. $request = new Request();
  162. $request->headers->set('if_none_match', sprintf('%s, %s, %s', $etagOne, $etagTwo, 'etagThree'));
  163. $response = new Response();
  164. $response->headers->set('ETag', $etagOne);
  165. $this->assertTrue($response->isNotModified($request));
  166. $response->headers->set('ETag', $etagTwo);
  167. $this->assertTrue($response->isNotModified($request));
  168. $response->headers->set('ETag', '');
  169. $this->assertFalse($response->isNotModified($request));
  170. }
  171. public function testIsNotModifiedLastModifiedAndEtag()
  172. {
  173. $before = 'Sun, 25 Aug 2013 18:32:31 GMT';
  174. $modified = 'Sun, 25 Aug 2013 18:33:31 GMT';
  175. $after = 'Sun, 25 Aug 2013 19:33:31 GMT';
  176. $etag = 'randomly_generated_etag';
  177. $request = new Request();
  178. $request->headers->set('if_none_match', sprintf('%s, %s', $etag, 'etagThree'));
  179. $request->headers->set('If-Modified-Since', $modified);
  180. $response = new Response();
  181. $response->headers->set('ETag', $etag);
  182. $response->headers->set('Last-Modified', $after);
  183. $this->assertFalse($response->isNotModified($request));
  184. $response->headers->set('ETag', 'non-existent-etag');
  185. $response->headers->set('Last-Modified', $before);
  186. $this->assertFalse($response->isNotModified($request));
  187. $response->headers->set('ETag', $etag);
  188. $response->headers->set('Last-Modified', $modified);
  189. $this->assertTrue($response->isNotModified($request));
  190. }
  191. public function testIsNotModifiedIfModifiedSinceAndEtagWithoutLastModified()
  192. {
  193. $modified = 'Sun, 25 Aug 2013 18:33:31 GMT';
  194. $etag = 'randomly_generated_etag';
  195. $request = new Request();
  196. $request->headers->set('if_none_match', sprintf('%s, %s', $etag, 'etagThree'));
  197. $request->headers->set('If-Modified-Since', $modified);
  198. $response = new Response();
  199. $response->headers->set('ETag', $etag);
  200. $this->assertTrue($response->isNotModified($request));
  201. $response->headers->set('ETag', 'non-existent-etag');
  202. $this->assertFalse($response->isNotModified($request));
  203. }
  204. public function testIsValidateable()
  205. {
  206. $response = new Response('', 200, array('Last-Modified' => $this->createDateTimeOneHourAgo()->format(DATE_RFC2822)));
  207. $this->assertTrue($response->isValidateable(), '->isValidateable() returns true if Last-Modified is present');
  208. $response = new Response('', 200, array('ETag' => '"12345"'));
  209. $this->assertTrue($response->isValidateable(), '->isValidateable() returns true if ETag is present');
  210. $response = new Response();
  211. $this->assertFalse($response->isValidateable(), '->isValidateable() returns false when no validator is present');
  212. }
  213. public function testGetDate()
  214. {
  215. $oneHourAgo = $this->createDateTimeOneHourAgo();
  216. $response = new Response('', 200, array('Date' => $oneHourAgo->format(DATE_RFC2822)));
  217. $date = $response->getDate();
  218. $this->assertEquals($oneHourAgo->getTimestamp(), $date->getTimestamp(), '->getDate() returns the Date header if present');
  219. $response = new Response();
  220. $date = $response->getDate();
  221. $this->assertEquals(time(), $date->getTimestamp(), '->getDate() returns the current Date if no Date header present');
  222. $response = new Response('', 200, array('Date' => $this->createDateTimeOneHourAgo()->format(DATE_RFC2822)));
  223. $now = $this->createDateTimeNow();
  224. $response->headers->set('Date', $now->format(DATE_RFC2822));
  225. $date = $response->getDate();
  226. $this->assertEquals($now->getTimestamp(), $date->getTimestamp(), '->getDate() returns the date when the header has been modified');
  227. $response = new Response('', 200);
  228. $now = $this->createDateTimeNow();
  229. $response->headers->remove('Date');
  230. $date = $response->getDate();
  231. $this->assertEquals($now->getTimestamp(), $date->getTimestamp(), '->getDate() returns the current Date when the header has previously been removed');
  232. }
  233. public function testGetMaxAge()
  234. {
  235. $response = new Response();
  236. $response->headers->set('Cache-Control', 's-maxage=600, max-age=0');
  237. $this->assertEquals(600, $response->getMaxAge(), '->getMaxAge() uses s-maxage cache control directive when present');
  238. $response = new Response();
  239. $response->headers->set('Cache-Control', 'max-age=600');
  240. $this->assertEquals(600, $response->getMaxAge(), '->getMaxAge() falls back to max-age when no s-maxage directive present');
  241. $response = new Response();
  242. $response->headers->set('Cache-Control', 'must-revalidate');
  243. $response->headers->set('Expires', $this->createDateTimeOneHourLater()->format(DATE_RFC2822));
  244. $this->assertEquals(3600, $response->getMaxAge(), '->getMaxAge() falls back to Expires when no max-age or s-maxage directive present');
  245. $response = new Response();
  246. $response->headers->set('Cache-Control', 'must-revalidate');
  247. $response->headers->set('Expires', -1);
  248. $this->assertLessThanOrEqual(time() - 2 * 86400, $response->getExpires()->format('U'));
  249. $response = new Response();
  250. $this->assertNull($response->getMaxAge(), '->getMaxAge() returns null if no freshness information available');
  251. }
  252. public function testSetSharedMaxAge()
  253. {
  254. $response = new Response();
  255. $response->setSharedMaxAge(20);
  256. $cacheControl = $response->headers->get('Cache-Control');
  257. $this->assertEquals('public, s-maxage=20', $cacheControl);
  258. }
  259. public function testIsPrivate()
  260. {
  261. $response = new Response();
  262. $response->headers->set('Cache-Control', 'max-age=100');
  263. $response->setPrivate();
  264. $this->assertEquals(100, $response->headers->getCacheControlDirective('max-age'), '->isPrivate() adds the private Cache-Control directive when set to true');
  265. $this->assertTrue($response->headers->getCacheControlDirective('private'), '->isPrivate() adds the private Cache-Control directive when set to true');
  266. $response = new Response();
  267. $response->headers->set('Cache-Control', 'public, max-age=100');
  268. $response->setPrivate();
  269. $this->assertEquals(100, $response->headers->getCacheControlDirective('max-age'), '->isPrivate() adds the private Cache-Control directive when set to true');
  270. $this->assertTrue($response->headers->getCacheControlDirective('private'), '->isPrivate() adds the private Cache-Control directive when set to true');
  271. $this->assertFalse($response->headers->hasCacheControlDirective('public'), '->isPrivate() removes the public Cache-Control directive');
  272. }
  273. public function testExpire()
  274. {
  275. $response = new Response();
  276. $response->headers->set('Cache-Control', 'max-age=100');
  277. $response->expire();
  278. $this->assertEquals(100, $response->headers->get('Age'), '->expire() sets the Age to max-age when present');
  279. $response = new Response();
  280. $response->headers->set('Cache-Control', 'max-age=100, s-maxage=500');
  281. $response->expire();
  282. $this->assertEquals(500, $response->headers->get('Age'), '->expire() sets the Age to s-maxage when both max-age and s-maxage are present');
  283. $response = new Response();
  284. $response->headers->set('Cache-Control', 'max-age=5, s-maxage=500');
  285. $response->headers->set('Age', '1000');
  286. $response->expire();
  287. $this->assertEquals(1000, $response->headers->get('Age'), '->expire() does nothing when the response is already stale/expired');
  288. $response = new Response();
  289. $response->expire();
  290. $this->assertFalse($response->headers->has('Age'), '->expire() does nothing when the response does not include freshness information');
  291. $response = new Response();
  292. $response->headers->set('Expires', -1);
  293. $response->expire();
  294. $this->assertNull($response->headers->get('Age'), '->expire() does not set the Age when the response is expired');
  295. $response = new Response();
  296. $response->headers->set('Expires', date(DATE_RFC2822, time() + 600));
  297. $response->expire();
  298. $this->assertNull($response->headers->get('Expires'), '->expire() removes the Expires header when the response is fresh');
  299. }
  300. public function testGetTtl()
  301. {
  302. $response = new Response();
  303. $this->assertNull($response->getTtl(), '->getTtl() returns null when no Expires or Cache-Control headers are present');
  304. $response = new Response();
  305. $response->headers->set('Expires', $this->createDateTimeOneHourLater()->format(DATE_RFC2822));
  306. $this->assertEquals(3600, $response->getTtl(), '->getTtl() uses the Expires header when no max-age is present');
  307. $response = new Response();
  308. $response->headers->set('Expires', $this->createDateTimeOneHourAgo()->format(DATE_RFC2822));
  309. $this->assertLessThan(0, $response->getTtl(), '->getTtl() returns negative values when Expires is in past');
  310. $response = new Response();
  311. $response->headers->set('Expires', $response->getDate()->format(DATE_RFC2822));
  312. $response->headers->set('Age', 0);
  313. $this->assertSame(0, $response->getTtl(), '->getTtl() correctly handles zero');
  314. $response = new Response();
  315. $response->headers->set('Cache-Control', 'max-age=60');
  316. $this->assertEquals(60, $response->getTtl(), '->getTtl() uses Cache-Control max-age when present');
  317. }
  318. public function testSetClientTtl()
  319. {
  320. $response = new Response();
  321. $response->setClientTtl(10);
  322. $this->assertEquals($response->getMaxAge(), $response->getAge() + 10);
  323. }
  324. public function testGetSetProtocolVersion()
  325. {
  326. $response = new Response();
  327. $this->assertEquals('1.0', $response->getProtocolVersion());
  328. $response->setProtocolVersion('1.1');
  329. $this->assertEquals('1.1', $response->getProtocolVersion());
  330. }
  331. public function testGetVary()
  332. {
  333. $response = new Response();
  334. $this->assertEquals(array(), $response->getVary(), '->getVary() returns an empty array if no Vary header is present');
  335. $response = new Response();
  336. $response->headers->set('Vary', 'Accept-Language');
  337. $this->assertEquals(array('Accept-Language'), $response->getVary(), '->getVary() parses a single header name value');
  338. $response = new Response();
  339. $response->headers->set('Vary', 'Accept-Language User-Agent X-Foo');
  340. $this->assertEquals(array('Accept-Language', 'User-Agent', 'X-Foo'), $response->getVary(), '->getVary() parses multiple header name values separated by spaces');
  341. $response = new Response();
  342. $response->headers->set('Vary', 'Accept-Language,User-Agent, X-Foo');
  343. $this->assertEquals(array('Accept-Language', 'User-Agent', 'X-Foo'), $response->getVary(), '->getVary() parses multiple header name values separated by commas');
  344. $vary = array('Accept-Language', 'User-Agent', 'X-foo');
  345. $response = new Response();
  346. $response->headers->set('Vary', $vary);
  347. $this->assertEquals($vary, $response->getVary(), '->getVary() parses multiple header name values in arrays');
  348. $response = new Response();
  349. $response->headers->set('Vary', 'Accept-Language, User-Agent, X-foo');
  350. $this->assertEquals($vary, $response->getVary(), '->getVary() parses multiple header name values in arrays');
  351. }
  352. public function testSetVary()
  353. {
  354. $response = new Response();
  355. $response->setVary('Accept-Language');
  356. $this->assertEquals(array('Accept-Language'), $response->getVary());
  357. $response->setVary('Accept-Language, User-Agent');
  358. $this->assertEquals(array('Accept-Language', 'User-Agent'), $response->getVary(), '->setVary() replace the vary header by default');
  359. $response->setVary('X-Foo', false);
  360. $this->assertEquals(array('Accept-Language', 'User-Agent', 'X-Foo'), $response->getVary(), '->setVary() doesn\'t wipe out earlier Vary headers if replace is set to false');
  361. }
  362. public function testDefaultContentType()
  363. {
  364. $headerMock = $this->getMockBuilder('Symfony\Component\HttpFoundation\ResponseHeaderBag')->setMethods(array('set'))->getMock();
  365. $headerMock->expects($this->at(0))
  366. ->method('set')
  367. ->with('Content-Type', 'text/html');
  368. $headerMock->expects($this->at(1))
  369. ->method('set')
  370. ->with('Content-Type', 'text/html; charset=UTF-8');
  371. $response = new Response('foo');
  372. $response->headers = $headerMock;
  373. $response->prepare(new Request());
  374. }
  375. public function testContentTypeCharset()
  376. {
  377. $response = new Response();
  378. $response->headers->set('Content-Type', 'text/css');
  379. // force fixContentType() to be called
  380. $response->prepare(new Request());
  381. $this->assertEquals('text/css; charset=UTF-8', $response->headers->get('Content-Type'));
  382. }
  383. public function testPrepareDoesNothingIfContentTypeIsSet()
  384. {
  385. $response = new Response('foo');
  386. $response->headers->set('Content-Type', 'text/plain');
  387. $response->prepare(new Request());
  388. $this->assertEquals('text/plain; charset=UTF-8', $response->headers->get('content-type'));
  389. }
  390. public function testPrepareDoesNothingIfRequestFormatIsNotDefined()
  391. {
  392. $response = new Response('foo');
  393. $response->prepare(new Request());
  394. $this->assertEquals('text/html; charset=UTF-8', $response->headers->get('content-type'));
  395. }
  396. public function testPrepareSetContentType()
  397. {
  398. $response = new Response('foo');
  399. $request = Request::create('/');
  400. $request->setRequestFormat('json');
  401. $response->prepare($request);
  402. $this->assertEquals('application/json', $response->headers->get('content-type'));
  403. }
  404. public function testPrepareRemovesContentForHeadRequests()
  405. {
  406. $response = new Response('foo');
  407. $request = Request::create('/', 'HEAD');
  408. $length = 12345;
  409. $response->headers->set('Content-Length', $length);
  410. $response->prepare($request);
  411. $this->assertEquals('', $response->getContent());
  412. $this->assertEquals($length, $response->headers->get('Content-Length'), 'Content-Length should be as if it was GET; see RFC2616 14.13');
  413. }
  414. public function testPrepareRemovesContentForInformationalResponse()
  415. {
  416. $response = new Response('foo');
  417. $request = Request::create('/');
  418. $response->setContent('content');
  419. $response->setStatusCode(101);
  420. $response->prepare($request);
  421. $this->assertEquals('', $response->getContent());
  422. $this->assertFalse($response->headers->has('Content-Type'));
  423. $this->assertFalse($response->headers->has('Content-Type'));
  424. $response->setContent('content');
  425. $response->setStatusCode(304);
  426. $response->prepare($request);
  427. $this->assertEquals('', $response->getContent());
  428. $this->assertFalse($response->headers->has('Content-Type'));
  429. $this->assertFalse($response->headers->has('Content-Length'));
  430. }
  431. public function testPrepareRemovesContentLength()
  432. {
  433. $response = new Response('foo');
  434. $request = Request::create('/');
  435. $response->headers->set('Content-Length', 12345);
  436. $response->prepare($request);
  437. $this->assertEquals(12345, $response->headers->get('Content-Length'));
  438. $response->headers->set('Transfer-Encoding', 'chunked');
  439. $response->prepare($request);
  440. $this->assertFalse($response->headers->has('Content-Length'));
  441. }
  442. public function testPrepareSetsPragmaOnHttp10Only()
  443. {
  444. $request = Request::create('/', 'GET');
  445. $request->server->set('SERVER_PROTOCOL', 'HTTP/1.0');
  446. $response = new Response('foo');
  447. $response->prepare($request);
  448. $this->assertEquals('no-cache', $response->headers->get('pragma'));
  449. $this->assertEquals('-1', $response->headers->get('expires'));
  450. $request->server->set('SERVER_PROTOCOL', 'HTTP/1.1');
  451. $response = new Response('foo');
  452. $response->prepare($request);
  453. $this->assertFalse($response->headers->has('pragma'));
  454. $this->assertFalse($response->headers->has('expires'));
  455. }
  456. public function testSetCache()
  457. {
  458. $response = new Response();
  459. //array('etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public')
  460. try {
  461. $response->setCache(array('wrong option' => 'value'));
  462. $this->fail('->setCache() throws an InvalidArgumentException if an option is not supported');
  463. } catch (\Exception $e) {
  464. $this->assertInstanceOf('InvalidArgumentException', $e, '->setCache() throws an InvalidArgumentException if an option is not supported');
  465. $this->assertContains('"wrong option"', $e->getMessage());
  466. }
  467. $options = array('etag' => '"whatever"');
  468. $response->setCache($options);
  469. $this->assertEquals($response->getEtag(), '"whatever"');
  470. $now = $this->createDateTimeNow();
  471. $options = array('last_modified' => $now);
  472. $response->setCache($options);
  473. $this->assertEquals($response->getLastModified()->getTimestamp(), $now->getTimestamp());
  474. $options = array('max_age' => 100);
  475. $response->setCache($options);
  476. $this->assertEquals($response->getMaxAge(), 100);
  477. $options = array('s_maxage' => 200);
  478. $response->setCache($options);
  479. $this->assertEquals($response->getMaxAge(), 200);
  480. $this->assertTrue($response->headers->hasCacheControlDirective('public'));
  481. $this->assertFalse($response->headers->hasCacheControlDirective('private'));
  482. $response->setCache(array('public' => true));
  483. $this->assertTrue($response->headers->hasCacheControlDirective('public'));
  484. $this->assertFalse($response->headers->hasCacheControlDirective('private'));
  485. $response->setCache(array('public' => false));
  486. $this->assertFalse($response->headers->hasCacheControlDirective('public'));
  487. $this->assertTrue($response->headers->hasCacheControlDirective('private'));
  488. $response->setCache(array('private' => true));
  489. $this->assertFalse($response->headers->hasCacheControlDirective('public'));
  490. $this->assertTrue($response->headers->hasCacheControlDirective('private'));
  491. $response->setCache(array('private' => false));
  492. $this->assertTrue($response->headers->hasCacheControlDirective('public'));
  493. $this->assertFalse($response->headers->hasCacheControlDirective('private'));
  494. $response->setCache(array('immutable' => true));
  495. $this->assertTrue($response->headers->hasCacheControlDirective('immutable'));
  496. $response->setCache(array('immutable' => false));
  497. $this->assertFalse($response->headers->hasCacheControlDirective('immutable'));
  498. }
  499. public function testSendContent()
  500. {
  501. $response = new Response('test response rendering', 200);
  502. ob_start();
  503. $response->sendContent();
  504. $string = ob_get_clean();
  505. $this->assertContains('test response rendering', $string);
  506. }
  507. public function testSetPublic()
  508. {
  509. $response = new Response();
  510. $response->setPublic();
  511. $this->assertTrue($response->headers->hasCacheControlDirective('public'));
  512. $this->assertFalse($response->headers->hasCacheControlDirective('private'));
  513. }
  514. public function testSetImmutable()
  515. {
  516. $response = new Response();
  517. $response->setImmutable();
  518. $this->assertTrue($response->headers->hasCacheControlDirective('immutable'));
  519. }
  520. public function testIsImmutable()
  521. {
  522. $response = new Response();
  523. $response->setImmutable();
  524. $this->assertTrue($response->isImmutable());
  525. }
  526. public function testSetDate()
  527. {
  528. $response = new Response();
  529. $response->setDate(\DateTime::createFromFormat(\DateTime::ATOM, '2013-01-26T09:21:56+0100', new \DateTimeZone('Europe/Berlin')));
  530. $this->assertEquals('2013-01-26T08:21:56+00:00', $response->getDate()->format(\DateTime::ATOM));
  531. }
  532. public function testSetDateWithImmutable()
  533. {
  534. $response = new Response();
  535. $response->setDate(\DateTimeImmutable::createFromFormat(\DateTime::ATOM, '2013-01-26T09:21:56+0100', new \DateTimeZone('Europe/Berlin')));
  536. $this->assertEquals('2013-01-26T08:21:56+00:00', $response->getDate()->format(\DateTime::ATOM));
  537. }
  538. public function testSetExpires()
  539. {
  540. $response = new Response();
  541. $response->setExpires(null);
  542. $this->assertNull($response->getExpires(), '->setExpires() remove the header when passed null');
  543. $now = $this->createDateTimeNow();
  544. $response->setExpires($now);
  545. $this->assertEquals($response->getExpires()->getTimestamp(), $now->getTimestamp());
  546. }
  547. public function testSetExpiresWithImmutable()
  548. {
  549. $response = new Response();
  550. $now = $this->createDateTimeImmutableNow();
  551. $response->setExpires($now);
  552. $this->assertEquals($response->getExpires()->getTimestamp(), $now->getTimestamp());
  553. }
  554. public function testSetLastModified()
  555. {
  556. $response = new Response();
  557. $response->setLastModified($this->createDateTimeNow());
  558. $this->assertNotNull($response->getLastModified());
  559. $response->setLastModified(null);
  560. $this->assertNull($response->getLastModified());
  561. }
  562. public function testSetLastModifiedWithImmutable()
  563. {
  564. $response = new Response();
  565. $response->setLastModified($this->createDateTimeImmutableNow());
  566. $this->assertNotNull($response->getLastModified());
  567. $response->setLastModified(null);
  568. $this->assertNull($response->getLastModified());
  569. }
  570. public function testIsInvalid()
  571. {
  572. $response = new Response();
  573. try {
  574. $response->setStatusCode(99);
  575. $this->fail();
  576. } catch (\InvalidArgumentException $e) {
  577. $this->assertTrue($response->isInvalid());
  578. }
  579. try {
  580. $response->setStatusCode(650);
  581. $this->fail();
  582. } catch (\InvalidArgumentException $e) {
  583. $this->assertTrue($response->isInvalid());
  584. }
  585. $response = new Response('', 200);
  586. $this->assertFalse($response->isInvalid());
  587. }
  588. /**
  589. * @dataProvider getStatusCodeFixtures
  590. */
  591. public function testSetStatusCode($code, $text, $expectedText)
  592. {
  593. $response = new Response();
  594. $response->setStatusCode($code, $text);
  595. $statusText = new \ReflectionProperty($response, 'statusText');
  596. $statusText->setAccessible(true);
  597. $this->assertEquals($expectedText, $statusText->getValue($response));
  598. }
  599. public function getStatusCodeFixtures()
  600. {
  601. return array(
  602. array('200', null, 'OK'),
  603. array('200', false, ''),
  604. array('200', 'foo', 'foo'),
  605. array('199', null, 'unknown status'),
  606. array('199', false, ''),
  607. array('199', 'foo', 'foo'),
  608. );
  609. }
  610. public function testIsInformational()
  611. {
  612. $response = new Response('', 100);
  613. $this->assertTrue($response->isInformational());
  614. $response = new Response('', 200);
  615. $this->assertFalse($response->isInformational());
  616. }
  617. public function testIsRedirectRedirection()
  618. {
  619. foreach (array(301, 302, 303, 307) as $code) {
  620. $response = new Response('', $code);
  621. $this->assertTrue($response->isRedirection());
  622. $this->assertTrue($response->isRedirect());
  623. }
  624. $response = new Response('', 304);
  625. $this->assertTrue($response->isRedirection());
  626. $this->assertFalse($response->isRedirect());
  627. $response = new Response('', 200);
  628. $this->assertFalse($response->isRedirection());
  629. $this->assertFalse($response->isRedirect());
  630. $response = new Response('', 404);
  631. $this->assertFalse($response->isRedirection());
  632. $this->assertFalse($response->isRedirect());
  633. $response = new Response('', 301, array('Location' => '/good-uri'));
  634. $this->assertFalse($response->isRedirect('/bad-uri'));
  635. $this->assertTrue($response->isRedirect('/good-uri'));
  636. }
  637. public function testIsNotFound()
  638. {
  639. $response = new Response('', 404);
  640. $this->assertTrue($response->isNotFound());
  641. $response = new Response('', 200);
  642. $this->assertFalse($response->isNotFound());
  643. }
  644. public function testIsEmpty()
  645. {
  646. foreach (array(204, 304) as $code) {
  647. $response = new Response('', $code);
  648. $this->assertTrue($response->isEmpty());
  649. }
  650. $response = new Response('', 200);
  651. $this->assertFalse($response->isEmpty());
  652. }
  653. public function testIsForbidden()
  654. {
  655. $response = new Response('', 403);
  656. $this->assertTrue($response->isForbidden());
  657. $response = new Response('', 200);
  658. $this->assertFalse($response->isForbidden());
  659. }
  660. public function testIsOk()
  661. {
  662. $response = new Response('', 200);
  663. $this->assertTrue($response->isOk());
  664. $response = new Response('', 404);
  665. $this->assertFalse($response->isOk());
  666. }
  667. public function testIsServerOrClientError()
  668. {
  669. $response = new Response('', 404);
  670. $this->assertTrue($response->isClientError());
  671. $this->assertFalse($response->isServerError());
  672. $response = new Response('', 500);
  673. $this->assertFalse($response->isClientError());
  674. $this->assertTrue($response->isServerError());
  675. }
  676. public function testHasVary()
  677. {
  678. $response = new Response();
  679. $this->assertFalse($response->hasVary());
  680. $response->setVary('User-Agent');
  681. $this->assertTrue($response->hasVary());
  682. }
  683. public function testSetEtag()
  684. {
  685. $response = new Response('', 200, array('ETag' => '"12345"'));
  686. $response->setEtag();
  687. $this->assertNull($response->headers->get('Etag'), '->setEtag() removes Etags when call with null');
  688. }
  689. /**
  690. * @dataProvider validContentProvider
  691. */
  692. public function testSetContent($content)
  693. {
  694. $response = new Response();
  695. $response->setContent($content);
  696. $this->assertEquals((string) $content, $response->getContent());
  697. }
  698. /**
  699. * @expectedException \UnexpectedValueException
  700. * @dataProvider invalidContentProvider
  701. */
  702. public function testSetContentInvalid($content)
  703. {
  704. $response = new Response();
  705. $response->setContent($content);
  706. }
  707. public function testSettersAreChainable()
  708. {
  709. $response = new Response();
  710. $setters = array(
  711. 'setProtocolVersion' => '1.0',
  712. 'setCharset' => 'UTF-8',
  713. 'setPublic' => null,
  714. 'setPrivate' => null,
  715. 'setDate' => $this->createDateTimeNow(),
  716. 'expire' => null,
  717. 'setMaxAge' => 1,
  718. 'setSharedMaxAge' => 1,
  719. 'setTtl' => 1,
  720. 'setClientTtl' => 1,
  721. );
  722. foreach ($setters as $setter => $arg) {
  723. $this->assertEquals($response, $response->{$setter}($arg));
  724. }
  725. }
  726. public function testNoDeprecationsAreTriggered()
  727. {
  728. new DefaultResponse();
  729. $this->getMockBuilder(Response::class)->getMock();
  730. // we just need to ensure that subclasses of Response can be created without any deprecations
  731. // being triggered if the subclass does not override any final methods
  732. $this->addToAssertionCount(1);
  733. }
  734. public function validContentProvider()
  735. {
  736. return array(
  737. 'obj' => array(new StringableObject()),
  738. 'string' => array('Foo'),
  739. 'int' => array(2),
  740. );
  741. }
  742. public function invalidContentProvider()
  743. {
  744. return array(
  745. 'obj' => array(new \stdClass()),
  746. 'array' => array(array()),
  747. 'bool' => array(true, '1'),
  748. );
  749. }
  750. protected function createDateTimeOneHourAgo()
  751. {
  752. return $this->createDateTimeNow()->sub(new \DateInterval('PT1H'));
  753. }
  754. protected function createDateTimeOneHourLater()
  755. {
  756. return $this->createDateTimeNow()->add(new \DateInterval('PT1H'));
  757. }
  758. protected function createDateTimeNow()
  759. {
  760. $date = new \DateTime();
  761. return $date->setTimestamp(time());
  762. }
  763. protected function createDateTimeImmutableNow()
  764. {
  765. $date = new \DateTimeImmutable();
  766. return $date->setTimestamp(time());
  767. }
  768. protected function provideResponse()
  769. {
  770. return new Response();
  771. }
  772. /**
  773. * @see http://github.com/zendframework/zend-diactoros for the canonical source repository
  774. *
  775. * @author Fábio Pacheco
  776. * @copyright Copyright (c) 2015-2016 Zend Technologies USA Inc. (http://www.zend.com)
  777. * @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License
  778. */
  779. public function ianaCodesReasonPhrasesProvider()
  780. {
  781. if (!\in_array('https', stream_get_wrappers(), true)) {
  782. $this->markTestSkipped('The "https" wrapper is not available');
  783. }
  784. $ianaHttpStatusCodes = new \DOMDocument();
  785. libxml_set_streams_context(stream_context_create(array(
  786. 'http' => array(
  787. 'method' => 'GET',
  788. 'timeout' => 30,
  789. ),
  790. )));
  791. $ianaHttpStatusCodes->load('https://www.iana.org/assignments/http-status-codes/http-status-codes.xml');
  792. if (!$ianaHttpStatusCodes->relaxNGValidate(__DIR__.'/schema/http-status-codes.rng')) {
  793. self::fail('Invalid IANA\'s HTTP status code list.');
  794. }
  795. $ianaCodesReasonPhrases = array();
  796. $xpath = new \DOMXPath($ianaHttpStatusCodes);
  797. $xpath->registerNamespace('ns', 'http://www.iana.org/assignments');
  798. $records = $xpath->query('//ns:record');
  799. foreach ($records as $record) {
  800. $value = $xpath->query('.//ns:value', $record)->item(0)->nodeValue;
  801. $description = $xpath->query('.//ns:description', $record)->item(0)->nodeValue;
  802. if (\in_array($description, array('Unassigned', '(Unused)'), true)) {
  803. continue;
  804. }
  805. if (preg_match('/^([0-9]+)\s*\-\s*([0-9]+)$/', $value, $matches)) {
  806. for ($value = $matches[1]; $value <= $matches[2]; ++$value) {
  807. $ianaCodesReasonPhrases[] = array($value, $description);
  808. }
  809. } else {
  810. $ianaCodesReasonPhrases[] = array($value, $description);
  811. }
  812. }
  813. return $ianaCodesReasonPhrases;
  814. }
  815. /**
  816. * @dataProvider ianaCodesReasonPhrasesProvider
  817. */
  818. public function testReasonPhraseDefaultsAgainstIana($code, $reasonPhrase)
  819. {
  820. $this->assertEquals($reasonPhrase, Response::$statusTexts[$code]);
  821. }
  822. }
  823. class StringableObject
  824. {
  825. public function __toString()
  826. {
  827. return 'Foo';
  828. }
  829. }
  830. class DefaultResponse extends Response
  831. {
  832. }