RequestHandlerComponentTest.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946
  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 1.2.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Controller\Component;
  17. use Cake\Controller\Component\RequestHandlerComponent;
  18. use Cake\Controller\ComponentRegistry;
  19. use Cake\Controller\Controller;
  20. use Cake\Event\Event;
  21. use Cake\Http\Exception\NotFoundException;
  22. use Cake\Http\Response;
  23. use Cake\Http\ServerRequest;
  24. use Cake\Routing\RouteBuilder;
  25. use Cake\Routing\Router;
  26. use Cake\TestSuite\TestCase;
  27. use Cake\View\AjaxView;
  28. use Cake\View\JsonView;
  29. use Cake\View\XmlView;
  30. use TestApp\Controller\Component\RequestHandlerExtComponent;
  31. use TestApp\Controller\RequestHandlerTestController;
  32. use TestApp\View\AppView;
  33. /**
  34. * RequestHandlerComponentTest class
  35. */
  36. class RequestHandlerComponentTest extends TestCase
  37. {
  38. /**
  39. * @var \TestApp\Controller\RequestHandlerTestController
  40. */
  41. protected $Controller;
  42. /**
  43. * @var \TestApp\Controller\Component\RequestHandlerExtComponent
  44. */
  45. protected $RequestHandler;
  46. /**
  47. * @var \Cake\Http\ServerRequest
  48. */
  49. protected $request;
  50. /**
  51. * Backup of $_SERVER
  52. *
  53. * @var array
  54. */
  55. protected $server = [];
  56. /**
  57. * setUp method
  58. *
  59. * @return void
  60. */
  61. public function setUp(): void
  62. {
  63. parent::setUp();
  64. $this->server = $_SERVER;
  65. static::setAppNamespace();
  66. $this->_init();
  67. }
  68. /**
  69. * init method
  70. *
  71. * @return void
  72. */
  73. protected function _init(): void
  74. {
  75. $request = new ServerRequest(['url' => 'controller_posts/index']);
  76. $response = new Response();
  77. $this->Controller = new RequestHandlerTestController($request, $response);
  78. $this->RequestHandler = $this->Controller->components()->load(RequestHandlerExtComponent::class);
  79. $this->request = $request;
  80. Router::scope('/', function (RouteBuilder $routes): void {
  81. $routes->setExtensions('json');
  82. $routes->fallbacks('InflectedRoute');
  83. });
  84. }
  85. /**
  86. * tearDown method
  87. *
  88. * @return void
  89. */
  90. public function tearDown(): void
  91. {
  92. parent::tearDown();
  93. Router::reload();
  94. $_SERVER = $this->server;
  95. unset($this->RequestHandler, $this->Controller);
  96. }
  97. /**
  98. * Test that the constructor sets the config.
  99. *
  100. * @return void
  101. */
  102. public function testConstructorConfig(): void
  103. {
  104. $config = [
  105. 'viewClassMap' => ['json' => 'MyPlugin.MyJson'],
  106. ];
  107. /** @var \Cake\Controller\Controller|\PHPUnit\Framework\MockObject\MockObject $controller */
  108. $controller = $this->getMockBuilder(Controller::class)
  109. ->setMethods(['redirect'])
  110. ->getMock();
  111. $collection = new ComponentRegistry($controller);
  112. $requestHandler = new RequestHandlerComponent($collection, $config);
  113. $this->assertEquals(['json' => 'MyPlugin.MyJson'], $requestHandler->getConfig('viewClassMap'));
  114. }
  115. /**
  116. * testInitializeCallback method
  117. *
  118. * @return void
  119. */
  120. public function testInitializeCallback(): void
  121. {
  122. $this->assertNull($this->RequestHandler->ext);
  123. $this->Controller->setRequest($this->Controller->getRequest()->withParam('_ext', 'rss'));
  124. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  125. $this->assertSame('rss', $this->RequestHandler->ext);
  126. }
  127. /**
  128. * test that a mapped Accept-type header will set $this->ext correctly.
  129. *
  130. * @return void
  131. */
  132. public function testInitializeContentTypeSettingExt(): void
  133. {
  134. Router::reload();
  135. $this->Controller->setRequest($this->request->withHeader('Accept', 'application/json'));
  136. $this->RequestHandler->setExt(null);
  137. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  138. $this->assertSame('json', $this->RequestHandler->getExt());
  139. }
  140. /**
  141. * Test that RequestHandler sets $this->ext when jQuery sends its wonky-ish headers.
  142. *
  143. * @return void
  144. */
  145. public function testInitializeContentTypeWithjQueryAccept(): void
  146. {
  147. Router::reload();
  148. $this->Controller->setRequest($this->request
  149. ->withHeader('Accept', 'application/json, application/javascript, */*; q=0.01')
  150. ->withHeader('X-Requested-With', 'XMLHttpRequest'));
  151. $this->RequestHandler->setExt(null);
  152. Router::extensions('json', false);
  153. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  154. $this->assertSame('json', $this->RequestHandler->ext);
  155. }
  156. /**
  157. * Test that RequestHandler does not set extension to csv for text/plain mimetype
  158. *
  159. * @return void
  160. */
  161. public function testInitializeContentTypeWithjQueryTextPlainAccept(): void
  162. {
  163. Router::reload();
  164. $this->Controller->setRequest($this->request->withHeader('Accept', 'text/plain, */*; q=0.01'));
  165. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  166. $this->assertNull($this->RequestHandler->ext);
  167. }
  168. /**
  169. * Test that RequestHandler sets $this->ext when jQuery sends its wonky-ish headers
  170. * and the application is configured to handle multiple extensions
  171. *
  172. * @return void
  173. */
  174. public function testInitializeContentTypeWithjQueryAcceptAndMultiplesExtensions(): void
  175. {
  176. Router::reload();
  177. $this->Controller->setRequest($this->request->withHeader('Accept', 'application/json, application/javascript, */*; q=0.01'));
  178. $this->RequestHandler->setExt(null);
  179. Router::extensions(['rss', 'json'], false);
  180. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  181. $this->assertSame('json', $this->RequestHandler->ext);
  182. }
  183. /**
  184. * Test that RequestHandler does not set $this->ext when multiple accepts are sent.
  185. *
  186. * @return void
  187. */
  188. public function testInitializeNoContentTypeWithSingleAccept(): void
  189. {
  190. Router::reload();
  191. $_SERVER['HTTP_ACCEPT'] = 'application/json, text/html, */*; q=0.01';
  192. $this->assertNull($this->RequestHandler->ext);
  193. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  194. $this->assertNull($this->RequestHandler->ext);
  195. }
  196. /**
  197. * Test that ext is set to the first listed extension with multiple accepted
  198. * content types.
  199. * Having multiple types accepted with same weight, means the client lets the
  200. * server choose the returned content type.
  201. *
  202. * @return void
  203. */
  204. public function testInitializeNoContentTypeWithMultipleAcceptedTypes(): void
  205. {
  206. $this->Controller->setRequest($this->request->withHeader(
  207. 'Accept',
  208. 'application/json, application/javascript, application/xml, */*; q=0.01'
  209. ));
  210. $this->RequestHandler->setExt(null);
  211. Router::extensions(['xml', 'json'], false);
  212. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  213. $this->assertSame('xml', $this->RequestHandler->ext);
  214. $this->RequestHandler->setExt(null);
  215. Router::extensions(['json', 'xml'], false);
  216. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  217. $this->assertSame('json', $this->RequestHandler->ext);
  218. }
  219. /**
  220. * Test that ext is set to type with highest weight
  221. *
  222. * @return void
  223. */
  224. public function testInitializeContentTypeWithMultipleAcceptedTypes(): void
  225. {
  226. Router::reload();
  227. $this->Controller->setRequest($this->request->withHeader(
  228. 'Accept',
  229. 'text/csv;q=1.0, application/json;q=0.8, application/xml;q=0.7'
  230. ));
  231. $this->RequestHandler->setExt(null);
  232. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  233. $this->assertSame('json', $this->RequestHandler->ext);
  234. }
  235. /**
  236. * Test that ext is not set with confusing android accepts headers.
  237. *
  238. * @return void
  239. */
  240. public function testInitializeAmbiguousAndroidAccepts(): void
  241. {
  242. Router::reload();
  243. $this->request = $this->request->withEnv(
  244. 'HTTP_ACCEPT',
  245. 'application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'
  246. );
  247. $this->RequestHandler->setExt(null);
  248. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  249. $this->assertNull($this->RequestHandler->ext);
  250. }
  251. /**
  252. * Test that the headers sent by firefox are not treated as XML requests.
  253. *
  254. * @return void
  255. */
  256. public function testInititalizeFirefoxHeaderNotXml(): void
  257. {
  258. $_SERVER['HTTP_ACCEPT'] = 'text/html,application/xhtml+xml,application/xml;image/png,image/jpeg,image/*;q=0.9,*/*;q=0.8';
  259. Router::extensions(['xml', 'json'], false);
  260. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  261. $this->assertNull($this->RequestHandler->ext);
  262. }
  263. /**
  264. * Test that a type mismatch doesn't incorrectly set the ext
  265. *
  266. * @return void
  267. */
  268. public function testInitializeContentTypeAndExtensionMismatch(): void
  269. {
  270. $this->assertNull($this->RequestHandler->ext);
  271. $extensions = Router::extensions();
  272. Router::extensions('xml', false);
  273. $request = new ServerRequest([
  274. 'environment' => ['HTTP_ACCEPT' => 'text/plain'],
  275. ]);
  276. $this->Controller->setRequest($request);
  277. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  278. $this->assertNull($this->RequestHandler->ext);
  279. Router::extensions($extensions, false);
  280. }
  281. /**
  282. * Test that startup() throws deprecation warning if input data is available and request data is not populated.
  283. *
  284. * @return void
  285. */
  286. public function testInitializeInputNoWarningEmptyJsonObject()
  287. {
  288. $request = new ServerRequest([
  289. 'input' => json_encode([]),
  290. ]);
  291. $this->Controller->setRequest($request->withMethod('POST'));
  292. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  293. $this->assertSame([], $request->getParsedBody());
  294. }
  295. /**
  296. * testViewClassMap
  297. *
  298. * @return void
  299. */
  300. public function testViewClassMap(): void
  301. {
  302. $this->RequestHandler->setConfig(['viewClassMap' => ['json' => 'CustomJson']]);
  303. $result = $this->RequestHandler->getConfig('viewClassMap');
  304. $expected = [
  305. 'json' => 'CustomJson',
  306. 'xml' => 'Xml',
  307. 'ajax' => 'Ajax',
  308. ];
  309. $this->assertEquals($expected, $result);
  310. $this->RequestHandler->setConfig(['viewClassMap' => ['xls' => 'Excel.Excel']]);
  311. $result = $this->RequestHandler->getConfig('viewClassMap');
  312. $expected = [
  313. 'json' => 'CustomJson',
  314. 'xml' => 'Xml',
  315. 'ajax' => 'Ajax',
  316. 'xls' => 'Excel.Excel',
  317. ];
  318. $this->assertEquals($expected, $result);
  319. $this->RequestHandler->renderAs($this->Controller, 'json');
  320. $this->assertSame('TestApp\View\CustomJsonView', $this->Controller->viewBuilder()->getClassName());
  321. }
  322. /**
  323. * Verify that isAjax is set on the request params for ajax requests
  324. *
  325. * @return void
  326. * @triggers Controller.startup $this->Controller
  327. */
  328. public function testIsAjaxParams(): void
  329. {
  330. $this->Controller->setRequest($this->request->withHeader('X-Requested-With', 'XMLHttpRequest'));
  331. $event = new Event('Controller.startup', $this->Controller);
  332. $this->Controller->beforeFilter($event);
  333. $this->RequestHandler->startup($event);
  334. $this->assertTrue($this->Controller->getRequest()->getAttribute('isAjax'));
  335. }
  336. /**
  337. * testAutoAjaxLayout method
  338. *
  339. * @return void
  340. * @triggers Controller.startup $this->Controller
  341. */
  342. public function testAutoAjaxLayout(): void
  343. {
  344. $event = new Event('Controller.startup', $this->Controller);
  345. $this->Controller->setRequest($this->request->withHeader('X-Requested-With', 'XMLHttpRequest'));
  346. $this->RequestHandler->startup($event);
  347. $event = new Event('Controller.beforeRender', $this->Controller);
  348. $this->RequestHandler->beforeRender($event);
  349. $view = $this->Controller->createView();
  350. $this->assertInstanceOf(AjaxView::class, $view);
  351. $this->assertSame('ajax', $view->getLayout());
  352. $this->_init();
  353. $this->Controller->setRequest($this->Controller->getRequest()->withParam('_ext', 'js'));
  354. $this->RequestHandler->startup($event);
  355. $this->assertNotEquals(AjaxView::class, $this->Controller->viewBuilder()->getClassName());
  356. }
  357. /**
  358. * @return array
  359. */
  360. public function defaultExtensionsProvider()
  361. {
  362. return [['html'], ['htm']];
  363. }
  364. /**
  365. * Tests that the default extensions are using the default view.
  366. *
  367. * @param string $extension Extension to test.
  368. * @dataProvider defaultExtensionsProvider
  369. * @return void
  370. */
  371. public function testDefaultExtensions($extension)
  372. {
  373. Router::extensions([$extension], false);
  374. $this->Controller->setRequest($this->request->withParam('_ext', $extension));
  375. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  376. $this->RequestHandler->beforeRender(new Event('Controller.beforeRender', $this->Controller));
  377. $this->assertEquals($extension, $this->RequestHandler->ext);
  378. $this->assertSame('text/html', $this->Controller->getResponse()->getType());
  379. $view = $this->Controller->createView();
  380. $this->assertInstanceOf(AppView::class, $view);
  381. $this->assertEmpty($view->getLayoutPath());
  382. $this->assertEmpty($view->getSubDir());
  383. }
  384. /**
  385. * Tests that the default extensions can be overwritten by the accept header.
  386. *
  387. * @param string $extension Extension to test.
  388. * @dataProvider defaultExtensionsProvider
  389. * @return void
  390. */
  391. public function testDefaultExtensionsOverwrittenByAcceptHeader($extension)
  392. {
  393. Router::extensions([$extension], false);
  394. $request = $this->request->withHeader(
  395. 'Accept',
  396. 'application/xml'
  397. );
  398. $this->Controller->setRequest($request->withParam('_ext', $extension));
  399. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  400. $this->RequestHandler->beforeRender(new Event('Controller.beforeRender', $this->Controller));
  401. $this->assertSame('xml', $this->RequestHandler->ext);
  402. $this->assertSame('application/xml', $this->Controller->getResponse()->getType());
  403. $view = $this->Controller->createView();
  404. $this->assertInstanceOf(XmlView::class, $view);
  405. $this->assertSame('xml', $view->getLayoutPath());
  406. $this->assertSame('xml', $view->getSubDir());
  407. }
  408. /**
  409. * test custom JsonView class is loaded and correct.
  410. *
  411. * @return void
  412. * @triggers Controller.startup $this->Controller
  413. */
  414. public function testJsonViewLoaded(): void
  415. {
  416. Router::extensions(['json', 'xml', 'ajax'], false);
  417. $this->Controller->setRequest($this->Controller->getRequest()->withParam('_ext', 'json'));
  418. $event = new Event('Controller.startup', $this->Controller);
  419. $this->RequestHandler->startup($event);
  420. $event = new Event('Controller.beforeRender', $this->Controller);
  421. $this->RequestHandler->beforeRender($event);
  422. $view = $this->Controller->createView();
  423. $this->assertInstanceOf(JsonView::class, $view);
  424. $this->assertSame('json', $view->getLayoutPath());
  425. $this->assertSame('json', $view->getSubDir());
  426. }
  427. /**
  428. * test custom XmlView class is loaded and correct.
  429. *
  430. * @return void
  431. * @triggers Controller.startup $this->Controller
  432. */
  433. public function testXmlViewLoaded(): void
  434. {
  435. Router::extensions(['json', 'xml', 'ajax'], false);
  436. $this->Controller->setRequest($this->Controller->getRequest()->withParam('_ext', 'xml'));
  437. $event = new Event('Controller.startup', $this->Controller);
  438. $this->RequestHandler->startup($event);
  439. $event = new Event('Controller.beforeRender', $this->Controller);
  440. $this->RequestHandler->beforeRender($event);
  441. $view = $this->Controller->createView();
  442. $this->assertInstanceOf(XmlView::class, $view);
  443. $this->assertSame('xml', $view->getLayoutPath());
  444. $this->assertSame('xml', $view->getSubDir());
  445. }
  446. /**
  447. * test custom AjaxView class is loaded and correct.
  448. *
  449. * @return void
  450. * @triggers Controller.startup $this->Controller
  451. */
  452. public function testAjaxViewLoaded(): void
  453. {
  454. Router::extensions(['json', 'xml', 'ajax'], false);
  455. $this->Controller->setRequest($this->Controller->getRequest()->withParam('_ext', 'ajax'));
  456. $event = new Event('Controller.startup', $this->Controller);
  457. $this->RequestHandler->startup($event);
  458. $event = new Event('Controller.beforeRender', $this->Controller);
  459. $this->RequestHandler->beforeRender($event);
  460. $view = $this->Controller->createView();
  461. $this->assertInstanceOf(AjaxView::class, $view);
  462. $this->assertSame('ajax', $view->getLayout());
  463. }
  464. /**
  465. * test configured extension but no view class set.
  466. *
  467. * @return void
  468. * @triggers Controller.beforeRender $this->Controller
  469. */
  470. public function testNoViewClassExtension(): void
  471. {
  472. Router::extensions(['json', 'xml', 'ajax', 'csv'], false);
  473. $this->Controller->setRequest($this->Controller->getRequest()->withParam('_ext', 'csv'));
  474. $event = new Event('Controller.startup', $this->Controller);
  475. $this->RequestHandler->startup($event);
  476. $this->Controller->getEventManager()->on('Controller.beforeRender', function () {
  477. return $this->Controller->getResponse();
  478. });
  479. $this->Controller->render();
  480. $this->assertSame('RequestHandlerTest' . DS . 'csv', $this->Controller->viewBuilder()->getTemplatePath());
  481. $this->assertSame('csv', $this->Controller->viewBuilder()->getLayoutPath());
  482. }
  483. /**
  484. * Tests that configured extensions that have no configured mimetype do not silently fallback to HTML.
  485. *
  486. * @return void
  487. */
  488. public function testUnrecognizedExtensionFailure()
  489. {
  490. $this->expectException(NotFoundException::class);
  491. $this->expectExceptionMessage('Invoked extension not recognized/configured: foo');
  492. Router::extensions(['json', 'foo'], false);
  493. $this->Controller->setRequest($this->Controller->getRequest()->withParam('_ext', 'foo'));
  494. $event = new Event('Controller.startup', $this->Controller);
  495. $this->RequestHandler->startup($event);
  496. $this->Controller->getEventManager()->on('Controller.beforeRender', function () {
  497. return $this->Controller->getResponse();
  498. });
  499. $this->Controller->render();
  500. $this->assertSame('RequestHandlerTest' . DS . 'csv', $this->Controller->viewBuilder()->getTemplatePath());
  501. }
  502. /**
  503. * testRenderAs method
  504. *
  505. * @return void
  506. */
  507. public function testRenderAs(): void
  508. {
  509. $this->RequestHandler->renderAs($this->Controller, 'rss');
  510. $this->Controller->viewBuilder()->setTemplatePath('request_handler_test\\rss');
  511. $this->RequestHandler->renderAs($this->Controller, 'js');
  512. $this->assertSame('request_handler_test' . DS . 'js', $this->Controller->viewBuilder()->getTemplatePath());
  513. }
  514. /**
  515. * test that attachment headers work with renderAs
  516. *
  517. * @return void
  518. */
  519. public function testRenderAsWithAttachment(): void
  520. {
  521. $this->Controller->setRequest($this->request->withHeader('Accept', 'application/xml;q=1.0'));
  522. $this->RequestHandler->renderAs($this->Controller, 'xml', ['attachment' => 'myfile.xml']);
  523. $this->assertEquals(XmlView::class, $this->Controller->viewBuilder()->getClassName());
  524. $this->assertSame('application/xml', $this->Controller->getResponse()->getType());
  525. $this->assertSame('UTF-8', $this->Controller->getResponse()->getCharset());
  526. $this->assertStringContainsString('myfile.xml', $this->Controller->getResponse()->getHeaderLine('Content-Disposition'));
  527. }
  528. /**
  529. * test that respondAs works as expected.
  530. *
  531. * @return void
  532. */
  533. public function testRespondAs(): void
  534. {
  535. $result = $this->RequestHandler->respondAs('json');
  536. $this->assertTrue($result);
  537. $this->assertSame('application/json', $this->Controller->getResponse()->getType());
  538. $result = $this->RequestHandler->respondAs('text/xml');
  539. $this->assertTrue($result);
  540. $this->assertSame('text/xml', $this->Controller->getResponse()->getType());
  541. }
  542. /**
  543. * test that attachment headers work with respondAs
  544. *
  545. * @return void
  546. */
  547. public function testRespondAsWithAttachment(): void
  548. {
  549. $result = $this->RequestHandler->respondAs('xml', ['attachment' => 'myfile.xml']);
  550. $this->assertTrue($result);
  551. $response = $this->Controller->getResponse();
  552. $this->assertStringContainsString('myfile.xml', $response->getHeaderLine('Content-Disposition'));
  553. $this->assertStringContainsString('application/xml', $response->getType());
  554. }
  555. /**
  556. * test that calling renderAs() more than once continues to work.
  557. *
  558. * @link #6466
  559. * @return void
  560. */
  561. public function testRenderAsCalledTwice(): void
  562. {
  563. $this->Controller->getEventManager()->on('Controller.beforeRender', function (\Cake\Event\EventInterface $e) {
  564. return $e->getSubject()->getResponse();
  565. });
  566. $this->Controller->render();
  567. $this->RequestHandler->renderAs($this->Controller, 'print');
  568. $this->assertSame('RequestHandlerTest' . DS . 'print', $this->Controller->viewBuilder()->getTemplatePath());
  569. $this->assertSame('print', $this->Controller->viewBuilder()->getLayoutPath());
  570. $this->RequestHandler->renderAs($this->Controller, 'js');
  571. $this->assertSame('RequestHandlerTest' . DS . 'js', $this->Controller->viewBuilder()->getTemplatePath());
  572. $this->assertSame('js', $this->Controller->viewBuilder()->getLayoutPath());
  573. }
  574. /**
  575. * testRequestContentTypes method
  576. *
  577. * @return void
  578. */
  579. public function testRequestContentTypes(): void
  580. {
  581. $this->Controller->setRequest($this->request->withEnv('REQUEST_METHOD', 'GET'));
  582. $this->assertNull($this->RequestHandler->requestedWith());
  583. $this->Controller->setRequest($this->request->withEnv('REQUEST_METHOD', 'POST')
  584. ->withEnv('CONTENT_TYPE', 'application/json'));
  585. $this->assertSame('json', $this->RequestHandler->requestedWith());
  586. $result = $this->RequestHandler->requestedWith(['json', 'xml']);
  587. $this->assertSame('json', $result);
  588. $result = $this->RequestHandler->requestedWith(['rss', 'atom']);
  589. $this->assertFalse($result);
  590. $this->Controller->setRequest($this->request
  591. ->withEnv('REQUEST_METHOD', 'PATCH')
  592. ->withEnv('CONTENT_TYPE', 'application/json'));
  593. $this->assertSame('json', $this->RequestHandler->requestedWith());
  594. $this->Controller->setRequest($this->request
  595. ->withEnv('REQUEST_METHOD', 'DELETE')
  596. ->withEnv('CONTENT_TYPE', 'application/json'));
  597. $this->assertSame('json', $this->RequestHandler->requestedWith());
  598. $this->Controller->setRequest($this->request
  599. ->withEnv('REQUEST_METHOD', 'POST')
  600. ->withEnv('CONTENT_TYPE', 'application/json'));
  601. $result = $this->RequestHandler->requestedWith(['json', 'xml']);
  602. $this->assertSame('json', $result);
  603. $result = $this->RequestHandler->requestedWith(['rss', 'atom']);
  604. $this->assertFalse($result);
  605. $this->Controller->setRequest($this->request->withHeader(
  606. 'Accept',
  607. 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  608. ));
  609. $this->assertTrue($this->RequestHandler->prefers('xml'));
  610. $this->assertFalse($this->RequestHandler->prefers('atom'));
  611. $this->assertFalse($this->RequestHandler->prefers('rss'));
  612. $this->Controller->setRequest($this->request->withHeader(
  613. 'Accept',
  614. 'application/atom+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  615. ));
  616. $this->assertTrue($this->RequestHandler->prefers('atom'));
  617. $this->assertFalse($this->RequestHandler->prefers('rss'));
  618. $this->Controller->setRequest($this->request->withHeader(
  619. 'Accept',
  620. 'application/rss+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  621. ));
  622. $this->assertFalse($this->RequestHandler->prefers('atom'));
  623. $this->assertTrue($this->RequestHandler->prefers('rss'));
  624. }
  625. /**
  626. * test that map alias converts aliases to content types.
  627. *
  628. * @return void
  629. */
  630. public function testMapAlias(): void
  631. {
  632. $result = $this->RequestHandler->mapAlias('xml');
  633. $this->assertSame('application/xml', $result);
  634. $result = $this->RequestHandler->mapAlias('text/html');
  635. $this->assertNull($result);
  636. $result = $this->RequestHandler->mapAlias('wap');
  637. $this->assertSame('text/vnd.wap.wml', $result);
  638. $result = $this->RequestHandler->mapAlias(['xml', 'js', 'json']);
  639. $expected = ['application/xml', 'application/javascript', 'application/json'];
  640. $this->assertEquals($expected, $result);
  641. }
  642. /**
  643. * test accepts() on the component
  644. *
  645. * @return void
  646. */
  647. public function testAccepts(): void
  648. {
  649. $this->Controller->setRequest($this->request->withHeader(
  650. 'Accept',
  651. 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'
  652. ));
  653. $this->assertTrue($this->RequestHandler->accepts(['js', 'xml', 'html']));
  654. $this->assertFalse($this->RequestHandler->accepts(['gif', 'jpeg', 'foo']));
  655. $this->Controller->setRequest($this->request->withHeader('Accept', '*/*;q=0.5'));
  656. $this->assertFalse($this->RequestHandler->accepts('rss'));
  657. }
  658. /**
  659. * test accepts and prefers methods.
  660. *
  661. * @return void
  662. */
  663. public function testPrefers(): void
  664. {
  665. $this->Controller->setRequest($this->request->withHeader(
  666. 'Accept',
  667. 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  668. ));
  669. $this->assertNotEquals('rss', $this->RequestHandler->prefers());
  670. $this->RequestHandler->setExt('rss');
  671. $this->assertSame('rss', $this->RequestHandler->prefers());
  672. $this->assertFalse($this->RequestHandler->prefers('xml'));
  673. $this->assertSame('xml', $this->RequestHandler->prefers(['js', 'xml', 'xhtml']));
  674. $this->assertFalse($this->RequestHandler->prefers(['red', 'blue']));
  675. $this->assertSame('xhtml', $this->RequestHandler->prefers(['js', 'json', 'xhtml']));
  676. $this->assertTrue($this->RequestHandler->prefers(['rss']), 'Should return true if input matches ext.');
  677. $this->assertFalse($this->RequestHandler->prefers(['html']), 'No match with ext, return false.');
  678. $this->_init();
  679. $this->Controller->setRequest($this->request->withHeader(
  680. 'Accept',
  681. 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'
  682. ));
  683. $this->assertSame('xml', $this->RequestHandler->prefers());
  684. $this->Controller->setRequest($this->request->withHeader('Accept', '*/*;q=0.5'));
  685. $this->assertSame('html', $this->RequestHandler->prefers());
  686. $this->assertFalse($this->RequestHandler->prefers('rss'));
  687. $this->Controller->setRequest($this->request->withEnv('HTTP_ACCEPT', ''));
  688. $this->RequestHandler->setExt('json');
  689. $this->assertFalse($this->RequestHandler->prefers('xml'));
  690. }
  691. /**
  692. * Test checkNotModified method
  693. *
  694. * @return void
  695. * @triggers Controller.beforeRender $this->Controller
  696. */
  697. public function testCheckNotModifiedByEtagStar(): void
  698. {
  699. $response = new Response();
  700. $response = $response->withEtag('something')
  701. ->withHeader('Content-Type', 'text/plain')
  702. ->withStringBody('keeper');
  703. $this->Controller->setResponse($response);
  704. $this->Controller->setRequest($this->request->withHeader('If-None-Match', '*'));
  705. $event = new Event('Controller.beforeRender', $this->Controller);
  706. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  707. $this->assertNull($requestHandler->beforeRender($event));
  708. $this->assertTrue($event->isStopped());
  709. $this->assertEquals(304, $this->Controller->getResponse()->getStatusCode());
  710. $this->assertSame('', (string)$this->Controller->getResponse()->getBody());
  711. $this->assertFalse($this->Controller->getResponse()->hasHeader('Content-Type'), 'header should not be removed.');
  712. }
  713. /**
  714. * Test checkNotModified method
  715. *
  716. * @return void
  717. * @triggers Controller.beforeRender
  718. */
  719. public function testCheckNotModifiedByEtagExact(): void
  720. {
  721. $response = new Response();
  722. $response = $response->withEtag('something', true)
  723. ->withHeader('Content-Type', 'text/plain')
  724. ->withStringBody('keeper');
  725. $this->Controller->setResponse($response);
  726. $this->Controller->setRequest($this->request->withHeader('If-None-Match', 'W/"something", "other"'));
  727. $event = new Event('Controller.beforeRender', $this->Controller);
  728. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  729. $this->assertNull($requestHandler->beforeRender($event));
  730. $this->assertTrue($event->isStopped());
  731. $this->assertEquals(304, $this->Controller->getResponse()->getStatusCode());
  732. $this->assertSame('', (string)$this->Controller->getResponse()->getBody());
  733. $this->assertFalse($this->Controller->getResponse()->hasHeader('Content-Type'));
  734. }
  735. /**
  736. * Test checkNotModified method
  737. *
  738. * @return void
  739. * @triggers Controller.beforeRender $this->Controller
  740. */
  741. public function testCheckNotModifiedByEtagAndTime(): void
  742. {
  743. $this->Controller->setRequest($this->request
  744. ->withHeader('If-None-Match', 'W/"something", "other"')
  745. ->withHeader('If-Modified-Since', '2012-01-01 00:00:00'));
  746. $response = new Response();
  747. $response = $response->withEtag('something', true)
  748. ->withHeader('Content-type', 'text/plain')
  749. ->withStringBody('should be removed')
  750. ->withModified('2012-01-01 00:00:00');
  751. $this->Controller->setResponse($response);
  752. $event = new Event('Controller.beforeRender', $this->Controller);
  753. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  754. $this->assertNull($requestHandler->beforeRender($event));
  755. $this->assertTrue($event->isStopped());
  756. $this->assertEquals(304, $this->Controller->getResponse()->getStatusCode());
  757. $this->assertSame('', (string)$this->Controller->getResponse()->getBody());
  758. $this->assertFalse($this->Controller->getResponse()->hasHeader('Content-type'));
  759. }
  760. /**
  761. * Test checkNotModified method
  762. *
  763. * @return void
  764. * @triggers Controller.beforeRender $this->Controller
  765. */
  766. public function testCheckNotModifiedNoInfo(): void
  767. {
  768. $response = new Response();
  769. $this->Controller->setResponse($response);
  770. $event = new Event('Controller.beforeRender', $this->Controller);
  771. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  772. $this->assertNull($requestHandler->beforeRender($event));
  773. $this->assertSame(200, $response->getStatusCode());
  774. }
  775. /**
  776. * Test default options in construction
  777. *
  778. * @return void
  779. */
  780. public function testConstructDefaultOptions(): void
  781. {
  782. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  783. $viewClass = $requestHandler->getConfig('viewClassMap');
  784. $expected = [
  785. 'json' => 'Json',
  786. 'xml' => 'Xml',
  787. 'ajax' => 'Ajax',
  788. ];
  789. $this->assertEquals($expected, $viewClass);
  790. }
  791. /**
  792. * Test options in constructor replace defaults
  793. *
  794. * @return void
  795. */
  796. public function testConstructReplaceOptions(): void
  797. {
  798. $requestHandler = new RequestHandlerComponent(
  799. $this->Controller->components(),
  800. [
  801. 'viewClassMap' => ['json' => 'Json'],
  802. 'inputTypeMap' => ['json' => ['json_decode', true]],
  803. ]
  804. );
  805. $viewClass = $requestHandler->getConfig('viewClassMap');
  806. $expected = [
  807. 'json' => 'Json',
  808. ];
  809. $this->assertEquals($expected, $viewClass);
  810. $inputs = $requestHandler->getConfig('inputTypeMap');
  811. $this->assertArrayHasKey('json', $inputs);
  812. $this->assertCount(1, $inputs);
  813. }
  814. /**
  815. * test beforeRender() doesn't override response type set in controller action
  816. *
  817. * @return void
  818. */
  819. public function testBeforeRender(): void
  820. {
  821. $this->Controller->set_response_type();
  822. $event = new Event('Controller.beforeRender', $this->Controller);
  823. $this->RequestHandler->beforeRender($event);
  824. $this->assertSame('text/plain', $this->Controller->getResponse()->getType());
  825. }
  826. /**
  827. * tests beforeRender automatically uses renderAs when a supported extension is found
  828. *
  829. * @return void
  830. */
  831. public function testBeforeRenderAutoRenderAs(): void
  832. {
  833. $this->Controller->setRequest($this->request->withParam('_ext', 'csv'));
  834. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  835. $event = new Event('Controller.beforeRender', $this->Controller);
  836. $this->RequestHandler->beforeRender($event);
  837. $this->assertSame('text/csv', $this->Controller->getResponse()->getType());
  838. }
  839. }