RequestHandlerComponentTest.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  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. ->onlyMethods(['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->assertSame((new Response(['type' => 'ajax']))->getType(), $view->getResponse()->getType());
  353. $this->_init();
  354. $this->Controller->setRequest($this->Controller->getRequest()->withParam('_ext', 'js'));
  355. $this->RequestHandler->startup($event);
  356. $this->assertNotEquals(AjaxView::class, $this->Controller->viewBuilder()->getClassName());
  357. }
  358. /**
  359. * @return array
  360. */
  361. public function defaultExtensionsProvider()
  362. {
  363. return [['html'], ['htm']];
  364. }
  365. /**
  366. * Tests that the default extensions are using the default view.
  367. *
  368. * @param string $extension Extension to test.
  369. * @dataProvider defaultExtensionsProvider
  370. * @return void
  371. */
  372. public function testDefaultExtensions($extension)
  373. {
  374. Router::extensions([$extension], false);
  375. $this->Controller->setRequest($this->request->withParam('_ext', $extension));
  376. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  377. $this->RequestHandler->beforeRender(new Event('Controller.beforeRender', $this->Controller));
  378. $this->assertEquals($extension, $this->RequestHandler->ext);
  379. $this->assertSame('text/html', $this->Controller->getResponse()->getType());
  380. $view = $this->Controller->createView();
  381. $this->assertInstanceOf(AppView::class, $view);
  382. $this->assertEmpty($view->getLayoutPath());
  383. $this->assertEmpty($view->getSubDir());
  384. }
  385. /**
  386. * Tests that the default extensions can be overwritten by the accept header.
  387. *
  388. * @param string $extension Extension to test.
  389. * @dataProvider defaultExtensionsProvider
  390. * @return void
  391. */
  392. public function testDefaultExtensionsOverwrittenByAcceptHeader($extension)
  393. {
  394. Router::extensions([$extension], false);
  395. $request = $this->request->withHeader(
  396. 'Accept',
  397. 'application/xml'
  398. );
  399. $this->Controller->setRequest($request->withParam('_ext', $extension));
  400. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  401. $this->RequestHandler->beforeRender(new Event('Controller.beforeRender', $this->Controller));
  402. $this->assertSame('xml', $this->RequestHandler->ext);
  403. $this->assertSame('application/xml', $this->Controller->getResponse()->getType());
  404. $view = $this->Controller->createView();
  405. $this->assertInstanceOf(XmlView::class, $view);
  406. $this->assertSame('xml', $view->getLayoutPath());
  407. $this->assertSame('xml', $view->getSubDir());
  408. }
  409. /**
  410. * test custom JsonView class is loaded and correct.
  411. *
  412. * @return void
  413. * @triggers Controller.startup $this->Controller
  414. */
  415. public function testJsonViewLoaded(): void
  416. {
  417. Router::extensions(['json', 'xml', 'ajax'], false);
  418. $this->Controller->setRequest($this->Controller->getRequest()->withParam('_ext', 'json'));
  419. $event = new Event('Controller.startup', $this->Controller);
  420. $this->RequestHandler->startup($event);
  421. $event = new Event('Controller.beforeRender', $this->Controller);
  422. $this->RequestHandler->beforeRender($event);
  423. $view = $this->Controller->createView();
  424. $this->assertInstanceOf(JsonView::class, $view);
  425. $this->assertSame('json', $view->getLayoutPath());
  426. $this->assertSame('json', $view->getSubDir());
  427. }
  428. /**
  429. * test custom XmlView class is loaded and correct.
  430. *
  431. * @return void
  432. * @triggers Controller.startup $this->Controller
  433. */
  434. public function testXmlViewLoaded(): void
  435. {
  436. Router::extensions(['json', 'xml', 'ajax'], false);
  437. $this->Controller->setRequest($this->Controller->getRequest()->withParam('_ext', 'xml'));
  438. $event = new Event('Controller.startup', $this->Controller);
  439. $this->RequestHandler->startup($event);
  440. $event = new Event('Controller.beforeRender', $this->Controller);
  441. $this->RequestHandler->beforeRender($event);
  442. $view = $this->Controller->createView();
  443. $this->assertInstanceOf(XmlView::class, $view);
  444. $this->assertSame('xml', $view->getLayoutPath());
  445. $this->assertSame('xml', $view->getSubDir());
  446. }
  447. /**
  448. * test custom AjaxView class is loaded and correct.
  449. *
  450. * @return void
  451. * @triggers Controller.startup $this->Controller
  452. */
  453. public function testAjaxViewLoaded(): void
  454. {
  455. Router::extensions(['json', 'xml', 'ajax'], false);
  456. $this->Controller->setRequest($this->Controller->getRequest()->withParam('_ext', 'ajax'));
  457. $event = new Event('Controller.startup', $this->Controller);
  458. $this->RequestHandler->startup($event);
  459. $event = new Event('Controller.beforeRender', $this->Controller);
  460. $this->RequestHandler->beforeRender($event);
  461. $view = $this->Controller->createView();
  462. $this->assertInstanceOf(AjaxView::class, $view);
  463. $this->assertSame('ajax', $view->getLayout());
  464. }
  465. /**
  466. * test configured extension but no view class set.
  467. *
  468. * @return void
  469. * @triggers Controller.beforeRender $this->Controller
  470. */
  471. public function testNoViewClassExtension(): void
  472. {
  473. Router::extensions(['json', 'xml', 'ajax', 'csv'], false);
  474. $this->Controller->setRequest($this->Controller->getRequest()->withParam('_ext', 'csv'));
  475. $event = new Event('Controller.startup', $this->Controller);
  476. $this->RequestHandler->startup($event);
  477. $this->Controller->getEventManager()->on('Controller.beforeRender', function () {
  478. return $this->Controller->getResponse();
  479. });
  480. $this->Controller->render();
  481. $this->assertSame('RequestHandlerTest' . DS . 'csv', $this->Controller->viewBuilder()->getTemplatePath());
  482. $this->assertSame('csv', $this->Controller->viewBuilder()->getLayoutPath());
  483. }
  484. /**
  485. * Tests that configured extensions that have no configured mimetype do not silently fallback to HTML.
  486. *
  487. * @return void
  488. */
  489. public function testUnrecognizedExtensionFailure()
  490. {
  491. $this->expectException(NotFoundException::class);
  492. $this->expectExceptionMessage('Invoked extension not recognized/configured: foo');
  493. Router::extensions(['json', 'foo'], false);
  494. $this->Controller->setRequest($this->Controller->getRequest()->withParam('_ext', 'foo'));
  495. $event = new Event('Controller.startup', $this->Controller);
  496. $this->RequestHandler->startup($event);
  497. $this->Controller->getEventManager()->on('Controller.beforeRender', function () {
  498. return $this->Controller->getResponse();
  499. });
  500. $this->Controller->render();
  501. $this->assertSame('RequestHandlerTest' . DS . 'csv', $this->Controller->viewBuilder()->getTemplatePath());
  502. }
  503. /**
  504. * testRenderAs method
  505. *
  506. * @return void
  507. */
  508. public function testRenderAs(): void
  509. {
  510. $this->RequestHandler->renderAs($this->Controller, 'rss');
  511. $this->Controller->viewBuilder()->setTemplatePath('request_handler_test\\rss');
  512. $this->RequestHandler->renderAs($this->Controller, 'js');
  513. $this->assertSame('request_handler_test' . DS . 'js', $this->Controller->viewBuilder()->getTemplatePath());
  514. }
  515. /**
  516. * test that attachment headers work with renderAs
  517. *
  518. * @return void
  519. */
  520. public function testRenderAsWithAttachment(): void
  521. {
  522. $this->Controller->setRequest($this->request->withHeader('Accept', 'application/xml;q=1.0'));
  523. $this->RequestHandler->renderAs($this->Controller, 'xml', ['attachment' => 'myfile.xml']);
  524. $this->assertEquals(XmlView::class, $this->Controller->viewBuilder()->getClassName());
  525. $this->assertSame('application/xml', $this->Controller->getResponse()->getType());
  526. $this->assertSame('UTF-8', $this->Controller->getResponse()->getCharset());
  527. $this->assertStringContainsString('myfile.xml', $this->Controller->getResponse()->getHeaderLine('Content-Disposition'));
  528. }
  529. /**
  530. * test that respondAs works as expected.
  531. *
  532. * @return void
  533. */
  534. public function testRespondAs(): void
  535. {
  536. $result = $this->RequestHandler->respondAs('json');
  537. $this->assertTrue($result);
  538. $this->assertSame('application/json', $this->Controller->getResponse()->getType());
  539. $result = $this->RequestHandler->respondAs('text/xml');
  540. $this->assertTrue($result);
  541. $this->assertSame('text/xml', $this->Controller->getResponse()->getType());
  542. }
  543. /**
  544. * test that attachment headers work with respondAs
  545. *
  546. * @return void
  547. */
  548. public function testRespondAsWithAttachment(): void
  549. {
  550. $result = $this->RequestHandler->respondAs('xml', ['attachment' => 'myfile.xml']);
  551. $this->assertTrue($result);
  552. $response = $this->Controller->getResponse();
  553. $this->assertStringContainsString('myfile.xml', $response->getHeaderLine('Content-Disposition'));
  554. $this->assertStringContainsString('application/xml', $response->getType());
  555. }
  556. /**
  557. * test that calling renderAs() more than once continues to work.
  558. *
  559. * @link #6466
  560. * @return void
  561. */
  562. public function testRenderAsCalledTwice(): void
  563. {
  564. $this->Controller->getEventManager()->on('Controller.beforeRender', function (\Cake\Event\EventInterface $e) {
  565. return $e->getSubject()->getResponse();
  566. });
  567. $this->Controller->render();
  568. $this->RequestHandler->renderAs($this->Controller, 'print');
  569. $this->assertSame('RequestHandlerTest' . DS . 'print', $this->Controller->viewBuilder()->getTemplatePath());
  570. $this->assertSame('print', $this->Controller->viewBuilder()->getLayoutPath());
  571. $this->RequestHandler->renderAs($this->Controller, 'js');
  572. $this->assertSame('RequestHandlerTest' . DS . 'js', $this->Controller->viewBuilder()->getTemplatePath());
  573. $this->assertSame('js', $this->Controller->viewBuilder()->getLayoutPath());
  574. }
  575. /**
  576. * testRequestContentTypes method
  577. *
  578. * @return void
  579. */
  580. public function testRequestContentTypes(): void
  581. {
  582. $this->Controller->setRequest($this->request->withEnv('REQUEST_METHOD', 'GET'));
  583. $this->assertNull($this->RequestHandler->requestedWith());
  584. $this->Controller->setRequest($this->request->withEnv('REQUEST_METHOD', 'POST')
  585. ->withEnv('CONTENT_TYPE', 'application/json'));
  586. $this->assertSame('json', $this->RequestHandler->requestedWith());
  587. $result = $this->RequestHandler->requestedWith(['json', 'xml']);
  588. $this->assertSame('json', $result);
  589. $result = $this->RequestHandler->requestedWith(['rss', 'atom']);
  590. $this->assertFalse($result);
  591. $this->Controller->setRequest($this->request
  592. ->withEnv('REQUEST_METHOD', 'PATCH')
  593. ->withEnv('CONTENT_TYPE', 'application/json'));
  594. $this->assertSame('json', $this->RequestHandler->requestedWith());
  595. $this->Controller->setRequest($this->request
  596. ->withEnv('REQUEST_METHOD', 'DELETE')
  597. ->withEnv('CONTENT_TYPE', 'application/json'));
  598. $this->assertSame('json', $this->RequestHandler->requestedWith());
  599. $this->Controller->setRequest($this->request
  600. ->withEnv('REQUEST_METHOD', 'POST')
  601. ->withEnv('CONTENT_TYPE', 'application/json'));
  602. $result = $this->RequestHandler->requestedWith(['json', 'xml']);
  603. $this->assertSame('json', $result);
  604. $result = $this->RequestHandler->requestedWith(['rss', 'atom']);
  605. $this->assertFalse($result);
  606. $this->Controller->setRequest($this->request->withHeader(
  607. 'Accept',
  608. 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  609. ));
  610. $this->assertTrue($this->RequestHandler->prefers('xml'));
  611. $this->assertFalse($this->RequestHandler->prefers('atom'));
  612. $this->assertFalse($this->RequestHandler->prefers('rss'));
  613. $this->Controller->setRequest($this->request->withHeader(
  614. 'Accept',
  615. 'application/atom+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  616. ));
  617. $this->assertTrue($this->RequestHandler->prefers('atom'));
  618. $this->assertFalse($this->RequestHandler->prefers('rss'));
  619. $this->Controller->setRequest($this->request->withHeader(
  620. 'Accept',
  621. 'application/rss+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  622. ));
  623. $this->assertFalse($this->RequestHandler->prefers('atom'));
  624. $this->assertTrue($this->RequestHandler->prefers('rss'));
  625. }
  626. /**
  627. * test that map alias converts aliases to content types.
  628. *
  629. * @return void
  630. */
  631. public function testMapAlias(): void
  632. {
  633. $result = $this->RequestHandler->mapAlias('xml');
  634. $this->assertSame('application/xml', $result);
  635. $result = $this->RequestHandler->mapAlias('text/html');
  636. $this->assertNull($result);
  637. $result = $this->RequestHandler->mapAlias('wap');
  638. $this->assertSame('text/vnd.wap.wml', $result);
  639. $result = $this->RequestHandler->mapAlias(['xml', 'js', 'json']);
  640. $expected = ['application/xml', 'application/javascript', 'application/json'];
  641. $this->assertEquals($expected, $result);
  642. }
  643. /**
  644. * test accepts() on the component
  645. *
  646. * @return void
  647. */
  648. public function testAccepts(): void
  649. {
  650. $this->Controller->setRequest($this->request->withHeader(
  651. 'Accept',
  652. 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'
  653. ));
  654. $this->assertTrue($this->RequestHandler->accepts(['js', 'xml', 'html']));
  655. $this->assertFalse($this->RequestHandler->accepts(['gif', 'jpeg', 'foo']));
  656. $this->Controller->setRequest($this->request->withHeader('Accept', '*/*;q=0.5'));
  657. $this->assertFalse($this->RequestHandler->accepts('rss'));
  658. }
  659. /**
  660. * test accepts and prefers methods.
  661. *
  662. * @return void
  663. */
  664. public function testPrefers(): void
  665. {
  666. $this->Controller->setRequest($this->request->withHeader(
  667. 'Accept',
  668. 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  669. ));
  670. $this->assertNotEquals('rss', $this->RequestHandler->prefers());
  671. $this->RequestHandler->setExt('rss');
  672. $this->assertSame('rss', $this->RequestHandler->prefers());
  673. $this->assertFalse($this->RequestHandler->prefers('xml'));
  674. $this->assertSame('xml', $this->RequestHandler->prefers(['js', 'xml', 'xhtml']));
  675. $this->assertFalse($this->RequestHandler->prefers(['red', 'blue']));
  676. $this->assertSame('xhtml', $this->RequestHandler->prefers(['js', 'json', 'xhtml']));
  677. $this->assertTrue($this->RequestHandler->prefers(['rss']), 'Should return true if input matches ext.');
  678. $this->assertFalse($this->RequestHandler->prefers(['html']), 'No match with ext, return false.');
  679. $this->_init();
  680. $this->Controller->setRequest($this->request->withHeader(
  681. 'Accept',
  682. 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'
  683. ));
  684. $this->assertSame('xml', $this->RequestHandler->prefers());
  685. $this->Controller->setRequest($this->request->withHeader('Accept', '*/*;q=0.5'));
  686. $this->assertSame('html', $this->RequestHandler->prefers());
  687. $this->assertFalse($this->RequestHandler->prefers('rss'));
  688. $this->Controller->setRequest($this->request->withEnv('HTTP_ACCEPT', ''));
  689. $this->RequestHandler->setExt('json');
  690. $this->assertFalse($this->RequestHandler->prefers('xml'));
  691. }
  692. /**
  693. * Test checkNotModified method
  694. *
  695. * @return void
  696. * @triggers Controller.beforeRender $this->Controller
  697. */
  698. public function testCheckNotModifiedByEtagStar(): void
  699. {
  700. $response = new Response();
  701. $response = $response->withEtag('something')
  702. ->withHeader('Content-Type', 'text/plain')
  703. ->withStringBody('keeper');
  704. $this->Controller->setResponse($response);
  705. $this->Controller->setRequest($this->request->withHeader('If-None-Match', '*'));
  706. $event = new Event('Controller.beforeRender', $this->Controller);
  707. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  708. $requestHandler->beforeRender($event);
  709. $this->assertTrue($event->isStopped());
  710. $this->assertEquals(304, $this->Controller->getResponse()->getStatusCode());
  711. $this->assertSame('', (string)$this->Controller->getResponse()->getBody());
  712. $this->assertFalse($this->Controller->getResponse()->hasHeader('Content-Type'), 'header should not be removed.');
  713. }
  714. /**
  715. * Test checkNotModified method
  716. *
  717. * @return void
  718. * @triggers Controller.beforeRender
  719. */
  720. public function testCheckNotModifiedByEtagExact(): void
  721. {
  722. $response = new Response();
  723. $response = $response->withEtag('something', true)
  724. ->withHeader('Content-Type', 'text/plain')
  725. ->withStringBody('keeper');
  726. $this->Controller->setResponse($response);
  727. $this->Controller->setRequest($this->request->withHeader('If-None-Match', 'W/"something", "other"'));
  728. $event = new Event('Controller.beforeRender', $this->Controller);
  729. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  730. $requestHandler->beforeRender($event);
  731. $this->assertTrue($event->isStopped());
  732. $this->assertEquals(304, $this->Controller->getResponse()->getStatusCode());
  733. $this->assertSame('', (string)$this->Controller->getResponse()->getBody());
  734. $this->assertFalse($this->Controller->getResponse()->hasHeader('Content-Type'));
  735. }
  736. /**
  737. * Test checkNotModified method
  738. *
  739. * @return void
  740. * @triggers Controller.beforeRender $this->Controller
  741. */
  742. public function testCheckNotModifiedByEtagAndTime(): void
  743. {
  744. $this->Controller->setRequest($this->request
  745. ->withHeader('If-None-Match', 'W/"something", "other"')
  746. ->withHeader('If-Modified-Since', '2012-01-01 00:00:00'));
  747. $response = new Response();
  748. $response = $response->withEtag('something', true)
  749. ->withHeader('Content-type', 'text/plain')
  750. ->withStringBody('should be removed')
  751. ->withModified('2012-01-01 00:00:00');
  752. $this->Controller->setResponse($response);
  753. $event = new Event('Controller.beforeRender', $this->Controller);
  754. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  755. $requestHandler->beforeRender($event);
  756. $this->assertTrue($event->isStopped());
  757. $this->assertEquals(304, $this->Controller->getResponse()->getStatusCode());
  758. $this->assertSame('', (string)$this->Controller->getResponse()->getBody());
  759. $this->assertFalse($this->Controller->getResponse()->hasHeader('Content-type'));
  760. }
  761. /**
  762. * Test checkNotModified method
  763. *
  764. * @return void
  765. * @triggers Controller.beforeRender $this->Controller
  766. */
  767. public function testCheckNotModifiedNoInfo(): void
  768. {
  769. $response = new Response();
  770. $this->Controller->setResponse($response);
  771. $event = new Event('Controller.beforeRender', $this->Controller);
  772. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  773. $requestHandler->beforeRender($event);
  774. $this->assertSame(200, $response->getStatusCode());
  775. }
  776. /**
  777. * Test default options in construction
  778. *
  779. * @return void
  780. */
  781. public function testConstructDefaultOptions(): void
  782. {
  783. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  784. $viewClass = $requestHandler->getConfig('viewClassMap');
  785. $expected = [
  786. 'json' => 'Json',
  787. 'xml' => 'Xml',
  788. 'ajax' => 'Ajax',
  789. ];
  790. $this->assertEquals($expected, $viewClass);
  791. }
  792. /**
  793. * Test options in constructor replace defaults
  794. *
  795. * @return void
  796. */
  797. public function testConstructReplaceOptions(): void
  798. {
  799. $requestHandler = new RequestHandlerComponent(
  800. $this->Controller->components(),
  801. [
  802. 'viewClassMap' => ['json' => 'Json'],
  803. 'inputTypeMap' => ['json' => ['json_decode', true]],
  804. ]
  805. );
  806. $viewClass = $requestHandler->getConfig('viewClassMap');
  807. $expected = [
  808. 'json' => 'Json',
  809. ];
  810. $this->assertEquals($expected, $viewClass);
  811. $inputs = $requestHandler->getConfig('inputTypeMap');
  812. $this->assertArrayHasKey('json', $inputs);
  813. $this->assertCount(1, $inputs);
  814. }
  815. /**
  816. * test beforeRender() doesn't override response type set in controller action
  817. *
  818. * @return void
  819. */
  820. public function testBeforeRender(): void
  821. {
  822. $this->Controller->set_response_type();
  823. $event = new Event('Controller.beforeRender', $this->Controller);
  824. $this->RequestHandler->beforeRender($event);
  825. $this->assertSame('text/plain', $this->Controller->getResponse()->getType());
  826. }
  827. /**
  828. * tests beforeRender automatically uses renderAs when a supported extension is found
  829. *
  830. * @return void
  831. */
  832. public function testBeforeRenderAutoRenderAs(): void
  833. {
  834. $this->Controller->setRequest($this->request->withParam('_ext', 'csv'));
  835. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  836. $event = new Event('Controller.beforeRender', $this->Controller);
  837. $this->RequestHandler->beforeRender($event);
  838. $this->assertSame('text/csv', $this->Controller->getResponse()->getType());
  839. }
  840. }