RequestHandlerComponentTest.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 1.2.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Controller\Component;
  16. use Cake\Controller\ComponentRegistry;
  17. use Cake\Controller\Component\RequestHandlerComponent;
  18. use Cake\Event\Event;
  19. use Cake\Http\Response;
  20. use Cake\Http\ServerRequest;
  21. use Cake\Routing\Router;
  22. use Cake\TestSuite\TestCase;
  23. use Cake\View\AjaxView;
  24. use Cake\View\JsonView;
  25. use Cake\View\XmlView;
  26. use TestApp\Controller\RequestHandlerTestController;
  27. use Zend\Diactoros\Stream;
  28. /**
  29. * RequestHandlerComponentTest class
  30. */
  31. class RequestHandlerComponentTest extends TestCase
  32. {
  33. /**
  34. * Controller property
  35. *
  36. * @var RequestHandlerTestController
  37. */
  38. public $Controller;
  39. /**
  40. * RequestHandler property
  41. *
  42. * @var RequestHandlerComponent
  43. */
  44. public $RequestHandler;
  45. /**
  46. * @var ServerRequest
  47. */
  48. public $request;
  49. /**
  50. * Backup of $_SERVER
  51. *
  52. * @var array
  53. */
  54. protected $server = [];
  55. /**
  56. * setUp method
  57. *
  58. * @return void
  59. */
  60. public function setUp()
  61. {
  62. parent::setUp();
  63. $this->server = $_SERVER;
  64. static::setAppNamespace();
  65. $this->_init();
  66. }
  67. /**
  68. * init method
  69. *
  70. * @return void
  71. */
  72. protected function _init()
  73. {
  74. $request = new ServerRequest('controller_posts/index');
  75. $response = $this->getMockBuilder('Cake\Http\Response')
  76. ->setMethods(['_sendHeader', 'stop'])
  77. ->getMock();
  78. $this->Controller = new RequestHandlerTestController($request, $response);
  79. $this->RequestHandler = $this->Controller->components()->load('RequestHandler');
  80. $this->request = $request;
  81. Router::scope('/', function ($routes) {
  82. $routes->setExtensions('json');
  83. $routes->fallbacks('InflectedRoute');
  84. });
  85. }
  86. /**
  87. * tearDown method
  88. *
  89. * @return void
  90. */
  91. public function tearDown()
  92. {
  93. parent::tearDown();
  94. Router::reload();
  95. $_SERVER = $this->server;
  96. unset($this->RequestHandler, $this->Controller);
  97. }
  98. /**
  99. * Test that the constructor sets the config.
  100. *
  101. * @return void
  102. */
  103. public function testConstructorConfig()
  104. {
  105. $config = [
  106. 'viewClassMap' => ['json' => 'MyPlugin.MyJson']
  107. ];
  108. $controller = $this->getMockBuilder('Cake\Controller\Controller')
  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()
  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->assertEquals('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()
  133. {
  134. Router::reload();
  135. $this->Controller->setRequest($this->request->withHeader('Accept', 'application/json'));
  136. $this->RequestHandler->ext = null;
  137. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  138. $this->assertEquals('json', $this->RequestHandler->ext);
  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()
  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->ext = null;
  152. Router::extensions('json', false);
  153. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  154. $this->assertEquals('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()
  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()
  175. {
  176. Router::reload();
  177. $this->Controller->setRequest($this->request->withHeader('Accept', 'application/json, application/javascript, */*; q=0.01'));
  178. $this->RequestHandler->ext = null;
  179. Router::extensions(['rss', 'json'], false);
  180. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  181. $this->assertEquals('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()
  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()
  205. {
  206. $this->Controller->setRequest($this->request->withHeader(
  207. 'Accept',
  208. 'application/json, application/javascript, application/xml, */*; q=0.01'
  209. ));
  210. $this->RequestHandler->ext = null;
  211. Router::extensions(['xml', 'json'], false);
  212. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  213. $this->assertEquals('xml', $this->RequestHandler->ext);
  214. $this->RequestHandler->ext = null;
  215. Router::extensions(['json', 'xml'], false);
  216. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  217. $this->assertEquals('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()
  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->ext = null;
  232. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  233. $this->assertEquals('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()
  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->ext = 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()
  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()
  269. {
  270. $this->assertNull($this->RequestHandler->ext);
  271. $extensions = Router::extensions();
  272. Router::extensions('xml', false);
  273. $this->Controller->setRequest($this->getMockBuilder('Cake\Http\ServerRequest')
  274. ->setMethods(['accepts'])
  275. ->getMock());
  276. $this->Controller->getRequest()->expects($this->any())
  277. ->method('accepts')
  278. ->will($this->returnValue(['application/json']));
  279. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  280. $this->assertNull($this->RequestHandler->ext);
  281. Router::extensions($extensions, false);
  282. }
  283. /**
  284. * testViewClassMap
  285. *
  286. * @return void
  287. */
  288. public function testViewClassMap()
  289. {
  290. $this->RequestHandler->setConfig(['viewClassMap' => ['json' => 'CustomJson']]);
  291. $result = $this->RequestHandler->getConfig('viewClassMap');
  292. $expected = [
  293. 'json' => 'CustomJson',
  294. 'xml' => 'Xml',
  295. 'ajax' => 'Ajax'
  296. ];
  297. $this->assertEquals($expected, $result);
  298. $this->RequestHandler->setConfig(['viewClassMap' => ['xls' => 'Excel.Excel']]);
  299. $result = $this->RequestHandler->getConfig('viewClassMap');
  300. $expected = [
  301. 'json' => 'CustomJson',
  302. 'xml' => 'Xml',
  303. 'ajax' => 'Ajax',
  304. 'xls' => 'Excel.Excel'
  305. ];
  306. $this->assertEquals($expected, $result);
  307. $this->RequestHandler->renderAs($this->Controller, 'json');
  308. $this->assertEquals('TestApp\View\CustomJsonView', $this->Controller->viewBuilder()->getClassName());
  309. }
  310. /**
  311. * Verify that isAjax is set on the request params for ajax requests
  312. *
  313. * @return void
  314. * @triggers Controller.startup $this->Controller
  315. */
  316. public function testIsAjaxParams()
  317. {
  318. $this->Controller->setRequest($this->request->withHeader('X-Requested-With', 'XMLHttpRequest'));
  319. $event = new Event('Controller.startup', $this->Controller);
  320. $this->RequestHandler->initialize([]);
  321. $this->Controller->beforeFilter($event);
  322. $this->RequestHandler->startup($event);
  323. $this->assertTrue($this->Controller->getRequest()->getParam('isAjax'));
  324. }
  325. /**
  326. * testAutoAjaxLayout method
  327. *
  328. * @return void
  329. * @triggers Controller.startup $this->Controller
  330. */
  331. public function testAutoAjaxLayout()
  332. {
  333. $event = new Event('Controller.startup', $this->Controller);
  334. $this->Controller->setRequest($this->request->withHeader('X-Requested-With', 'XMLHttpRequest'));
  335. $this->RequestHandler->initialize([]);
  336. $this->RequestHandler->startup($event);
  337. $event = new Event('Controller.beforeRender', $this->Controller);
  338. $this->RequestHandler->beforeRender($event);
  339. $view = $this->Controller->createView();
  340. $this->assertInstanceOf(AjaxView::class, $view);
  341. $this->assertEquals('ajax', $view->getLayout());
  342. $this->_init();
  343. $this->Controller->setRequest($this->Controller->getRequest()->withParam('_ext', 'js'));
  344. $this->RequestHandler->initialize([]);
  345. $this->RequestHandler->startup($event);
  346. $this->assertNotEquals(AjaxView::class, $this->Controller->viewBuilder()->getClassName());
  347. }
  348. /**
  349. * test custom JsonView class is loaded and correct.
  350. *
  351. * @return void
  352. * @triggers Controller.startup $this->Controller
  353. */
  354. public function testJsonViewLoaded()
  355. {
  356. Router::extensions(['json', 'xml', 'ajax'], false);
  357. $this->Controller->setRequest($this->Controller->getRequest()->withParam('_ext', 'json'));
  358. $event = new Event('Controller.startup', $this->Controller);
  359. $this->RequestHandler->initialize([]);
  360. $this->RequestHandler->startup($event);
  361. $event = new Event('Controller.beforeRender', $this->Controller);
  362. $this->RequestHandler->beforeRender($event);
  363. $view = $this->Controller->createView();
  364. $this->assertInstanceOf(JsonView::class, $view);
  365. $this->assertEquals('json', $view->getLayoutPath());
  366. $this->assertEquals('json', $view->subDir);
  367. }
  368. /**
  369. * test custom XmlView class is loaded and correct.
  370. *
  371. * @return void
  372. * @triggers Controller.startup $this->Controller
  373. */
  374. public function testXmlViewLoaded()
  375. {
  376. Router::extensions(['json', 'xml', 'ajax'], false);
  377. $this->Controller->setRequest($this->Controller->getRequest()->withParam('_ext', 'xml'));
  378. $event = new Event('Controller.startup', $this->Controller);
  379. $this->RequestHandler->initialize([]);
  380. $this->RequestHandler->startup($event);
  381. $event = new Event('Controller.beforeRender', $this->Controller);
  382. $this->RequestHandler->beforeRender($event);
  383. $view = $this->Controller->createView();
  384. $this->assertInstanceOf(XmlView::class, $view);
  385. $this->assertEquals('xml', $view->getLayoutPath());
  386. $this->assertEquals('xml', $view->subDir);
  387. }
  388. /**
  389. * test custom AjaxView class is loaded and correct.
  390. *
  391. * @return void
  392. * @triggers Controller.startup $this->Controller
  393. */
  394. public function testAjaxViewLoaded()
  395. {
  396. Router::extensions(['json', 'xml', 'ajax'], false);
  397. $this->Controller->setRequest($this->Controller->getRequest()->withParam('_ext', 'ajax'));
  398. $event = new Event('Controller.startup', $this->Controller);
  399. $this->RequestHandler->initialize([]);
  400. $this->RequestHandler->startup($event);
  401. $event = new Event('Controller.beforeRender', $this->Controller);
  402. $this->RequestHandler->beforeRender($event);
  403. $view = $this->Controller->createView();
  404. $this->assertInstanceOf(AjaxView::class, $view);
  405. $this->assertEquals('ajax', $view->getLayout());
  406. }
  407. /**
  408. * test configured extension but no view class set.
  409. *
  410. * @return void
  411. * @triggers Controller.beforeRender $this->Controller
  412. */
  413. public function testNoViewClassExtension()
  414. {
  415. Router::extensions(['json', 'xml', 'ajax', 'csv'], false);
  416. $this->Controller->setRequest($this->Controller->getRequest()->withParam('_ext', 'csv'));
  417. $event = new Event('Controller.startup', $this->Controller);
  418. $this->RequestHandler->initialize([]);
  419. $this->RequestHandler->startup($event);
  420. $this->Controller->getEventManager()->on('Controller.beforeRender', function () {
  421. return $this->Controller->response;
  422. });
  423. $this->Controller->render();
  424. $this->assertEquals('RequestHandlerTest' . DS . 'csv', $this->Controller->viewBuilder()->getTemplatePath());
  425. $this->assertEquals('csv', $this->Controller->viewBuilder()->getLayoutPath());
  426. }
  427. /**
  428. * testStartupCallback method
  429. *
  430. * @return void
  431. * @triggers Controller.beforeRender $this->Controller
  432. */
  433. public function testStartupCallback()
  434. {
  435. $event = new Event('Controller.beforeRender', $this->Controller);
  436. $_SERVER['REQUEST_METHOD'] = 'PUT';
  437. $_SERVER['CONTENT_TYPE'] = 'application/xml';
  438. $this->Controller->setRequest(new ServerRequest());
  439. $this->RequestHandler->beforeRender($event);
  440. $this->assertInternalType('array', $this->Controller->getRequest()->getData());
  441. $this->assertNotInternalType('object', $this->Controller->getRequest()->getData());
  442. }
  443. /**
  444. * testStartupCallback with charset.
  445. *
  446. * @return void
  447. * @triggers Controller.startup $this->Controller
  448. */
  449. public function testStartupCallbackCharset()
  450. {
  451. $event = new Event('Controller.startup', $this->Controller);
  452. $_SERVER['REQUEST_METHOD'] = 'PUT';
  453. $_SERVER['CONTENT_TYPE'] = 'application/xml; charset=UTF-8';
  454. $this->Controller->setRequest(new ServerRequest());
  455. $this->RequestHandler->startup($event);
  456. $this->assertInternalType('array', $this->Controller->getRequest()->getData());
  457. $this->assertNotInternalType('object', $this->Controller->getRequest()->getData());
  458. }
  459. /**
  460. * Test that processing data results in an array.
  461. *
  462. * @return void
  463. * @triggers Controller.startup $this->Controller
  464. */
  465. public function testStartupProcessDataInvalid()
  466. {
  467. $this->Controller->setRequest(new ServerRequest([
  468. 'environment' => [
  469. 'REQUEST_METHOD' => 'POST',
  470. 'CONTENT_TYPE' => 'application/json'
  471. ]
  472. ]));
  473. $event = new Event('Controller.startup', $this->Controller);
  474. $this->RequestHandler->startup($event);
  475. $this->assertEquals([], $this->Controller->getRequest()->getData());
  476. $stream = new Stream('php://memory', 'w');
  477. $stream->write('"invalid"');
  478. $this->Controller->setRequest($this->Controller->getRequest()->withBody($stream));
  479. $this->RequestHandler->startup($event);
  480. $this->assertEquals(['invalid'], $this->Controller->getRequest()->getData());
  481. }
  482. /**
  483. * Test that processing data results in an array.
  484. *
  485. * @return void
  486. * @triggers Controller.startup $this->Controller
  487. */
  488. public function testStartupProcessData()
  489. {
  490. $this->Controller->setRequest(new ServerRequest([
  491. 'environment' => [
  492. 'REQUEST_METHOD' => 'POST',
  493. 'CONTENT_TYPE' => 'application/json'
  494. ]
  495. ]));
  496. $stream = new Stream('php://memory', 'w');
  497. $stream->write('{"valid":true}');
  498. $this->Controller->setRequest($this->Controller->getRequest()->withBody($stream));
  499. $event = new Event('Controller.startup', $this->Controller);
  500. $this->RequestHandler->startup($event);
  501. $this->assertEquals(['valid' => true], $this->Controller->getRequest()->getData());
  502. }
  503. /**
  504. * Test that file handles are ignored as XML data.
  505. *
  506. * @return void
  507. * @triggers Controller.startup $this->Controller
  508. */
  509. public function testStartupIgnoreFileAsXml()
  510. {
  511. $this->Controller->setRequest(new ServerRequest([
  512. 'input' => '/dev/random',
  513. 'environment' => [
  514. 'REQUEST_METHOD' => 'POST',
  515. 'CONTENT_TYPE' => 'application/xml'
  516. ]
  517. ]));
  518. $event = new Event('Controller.startup', $this->Controller);
  519. $this->RequestHandler->startup($event);
  520. $this->assertEquals([], $this->Controller->getRequest()->getData());
  521. }
  522. /**
  523. * Test that input xml is parsed
  524. *
  525. * @return void
  526. */
  527. public function testStartupConvertXmlDataWrapper()
  528. {
  529. $xml = <<<XML
  530. <?xml version="1.0" encoding="utf-8"?>
  531. <data>
  532. <article id="1" title="first"></article>
  533. </data>
  534. XML;
  535. $this->Controller->setRequest((new ServerRequest(['input' => $xml]))
  536. ->withEnv('REQUEST_METHOD', 'POST')
  537. ->withEnv('CONTENT_TYPE', 'application/xml'));
  538. $event = new Event('Controller.startup', $this->Controller);
  539. $this->RequestHandler->startup($event);
  540. $expected = [
  541. 'data' => [
  542. 'article' => [
  543. '@id' => 1,
  544. '@title' => 'first'
  545. ]
  546. ]
  547. ];
  548. $this->assertEquals($expected, $this->Controller->getRequest()->getData());
  549. }
  550. /**
  551. * Test that input xml is parsed
  552. *
  553. * @return void
  554. */
  555. public function testStartupConvertXmlElements()
  556. {
  557. $xml = <<<XML
  558. <?xml version="1.0" encoding="utf-8"?>
  559. <article>
  560. <id>1</id>
  561. <title><![CDATA[first]]></title>
  562. </article>
  563. XML;
  564. $this->Controller->setRequest((new ServerRequest(['input' => $xml]))
  565. ->withEnv('REQUEST_METHOD', 'POST')
  566. ->withEnv('CONTENT_TYPE', 'application/xml'));
  567. $event = new Event('Controller.startup', $this->Controller);
  568. $this->RequestHandler->startup($event);
  569. $expected = [
  570. 'article' => [
  571. 'id' => 1,
  572. 'title' => 'first'
  573. ]
  574. ];
  575. $this->assertEquals($expected, $this->Controller->getRequest()->getData());
  576. }
  577. /**
  578. * Test that input xml is parsed
  579. *
  580. * @return void
  581. */
  582. public function testStartupConvertXmlIgnoreEntities()
  583. {
  584. $xml = <<<XML
  585. <?xml version="1.0" encoding="UTF-8"?>
  586. <!DOCTYPE item [
  587. <!ENTITY item "item">
  588. <!ENTITY item1 "&item;&item;&item;&item;&item;&item;">
  589. <!ENTITY item2 "&item1;&item1;&item1;&item1;&item1;&item1;&item1;&item1;&item1;">
  590. <!ENTITY item3 "&item2;&item2;&item2;&item2;&item2;&item2;&item2;&item2;&item2;">
  591. <!ENTITY item4 "&item3;&item3;&item3;&item3;&item3;&item3;&item3;&item3;&item3;">
  592. <!ENTITY item5 "&item4;&item4;&item4;&item4;&item4;&item4;&item4;&item4;&item4;">
  593. <!ENTITY item6 "&item5;&item5;&item5;&item5;&item5;&item5;&item5;&item5;&item5;">
  594. <!ENTITY item7 "&item6;&item6;&item6;&item6;&item6;&item6;&item6;&item6;&item6;">
  595. <!ENTITY item8 "&item7;&item7;&item7;&item7;&item7;&item7;&item7;&item7;&item7;">
  596. ]>
  597. <item>
  598. <description>&item8;</description>
  599. </item>
  600. XML;
  601. $this->Controller->setRequest((new ServerRequest(['input' => $xml]))
  602. ->withEnv('REQUEST_METHOD', 'POST')
  603. ->withEnv('CONTENT_TYPE', 'application/xml'));
  604. $event = new Event('Controller.startup', $this->Controller);
  605. $this->RequestHandler->startup($event);
  606. $this->assertEquals([], $this->Controller->getRequest()->getData());
  607. }
  608. /**
  609. * Test that data isn't processed when parsed data already exists.
  610. *
  611. * @return void
  612. * @triggers Controller.startup $this->Controller
  613. */
  614. public function testStartupSkipDataProcess()
  615. {
  616. $this->Controller->setRequest(new ServerRequest([
  617. 'environment' => [
  618. 'REQUEST_METHOD' => 'POST',
  619. 'CONTENT_TYPE' => 'application/json'
  620. ]
  621. ]));
  622. $event = new Event('Controller.startup', $this->Controller);
  623. $this->RequestHandler->startup($event);
  624. $this->assertEquals([], $this->Controller->getRequest()->getData());
  625. $stream = new Stream('php://memory', 'w');
  626. $stream->write('{"new": "data"}');
  627. $this->Controller->setRequest($this->Controller->getRequest()
  628. ->withBody($stream)
  629. ->withParsedBody(['old' => 'news']));
  630. $this->RequestHandler->startup($event);
  631. $this->assertEquals(['old' => 'news'], $this->Controller->getRequest()->getData());
  632. }
  633. /**
  634. * testRenderAs method
  635. *
  636. * @return void
  637. */
  638. public function testRenderAs()
  639. {
  640. $this->RequestHandler->renderAs($this->Controller, 'rss');
  641. $this->Controller->viewBuilder()->setTemplatePath('request_handler_test\\rss');
  642. $this->RequestHandler->renderAs($this->Controller, 'js');
  643. $this->assertEquals('request_handler_test' . DS . 'js', $this->Controller->viewBuilder()->getTemplatePath());
  644. }
  645. /**
  646. * test that attachment headers work with renderAs
  647. *
  648. * @return void
  649. */
  650. public function testRenderAsWithAttachment()
  651. {
  652. $this->Controller->setRequest($this->request->withHeader('Accept', 'application/xml;q=1.0'));
  653. $this->RequestHandler->renderAs($this->Controller, 'xml', ['attachment' => 'myfile.xml']);
  654. $this->assertEquals(XmlView::class, $this->Controller->viewBuilder()->getClassName());
  655. $this->assertEquals('application/xml', $this->Controller->getResponse()->getType());
  656. $this->assertEquals('UTF-8', $this->Controller->getResponse()->getCharset());
  657. $this->assertContains('myfile.xml', $this->Controller->getResponse()->getHeaderLine('Content-Disposition'));
  658. }
  659. /**
  660. * test that respondAs works as expected.
  661. *
  662. * @return void
  663. */
  664. public function testRespondAs()
  665. {
  666. $result = $this->RequestHandler->respondAs('json');
  667. $this->assertTrue($result);
  668. $this->assertEquals('application/json', $this->Controller->getResponse()->getType());
  669. $result = $this->RequestHandler->respondAs('text/xml');
  670. $this->assertTrue($result);
  671. $this->assertEquals('text/xml', $this->Controller->getResponse()->getType());
  672. }
  673. /**
  674. * test that attachment headers work with respondAs
  675. *
  676. * @return void
  677. */
  678. public function testRespondAsWithAttachment()
  679. {
  680. $result = $this->RequestHandler->respondAs('xml', ['attachment' => 'myfile.xml']);
  681. $this->assertTrue($result);
  682. $response = $this->Controller->getResponse();
  683. $this->assertContains('myfile.xml', $response->getHeaderLine('Content-Disposition'));
  684. $this->assertContains('application/xml', $response->getType());
  685. }
  686. /**
  687. * test that calling renderAs() more than once continues to work.
  688. *
  689. * @link #6466
  690. * @return void
  691. */
  692. public function testRenderAsCalledTwice()
  693. {
  694. $this->Controller->getEventManager()->on('Controller.beforeRender', function (\Cake\Event\Event $e) {
  695. return $e->getSubject()->response;
  696. });
  697. $this->Controller->render();
  698. $this->RequestHandler->renderAs($this->Controller, 'print');
  699. $this->assertEquals('RequestHandlerTest' . DS . 'print', $this->Controller->viewBuilder()->getTemplatePath());
  700. $this->assertEquals('print', $this->Controller->viewBuilder()->getLayoutPath());
  701. $this->RequestHandler->renderAs($this->Controller, 'js');
  702. $this->assertEquals('RequestHandlerTest' . DS . 'js', $this->Controller->viewBuilder()->getTemplatePath());
  703. $this->assertEquals('js', $this->Controller->viewBuilder()->getLayoutPath());
  704. }
  705. /**
  706. * testRequestContentTypes method
  707. *
  708. * @return void
  709. */
  710. public function testRequestContentTypes()
  711. {
  712. $this->Controller->setRequest($this->request->withEnv('REQUEST_METHOD', 'GET'));
  713. $this->assertNull($this->RequestHandler->requestedWith());
  714. $this->Controller->setRequest($this->request->withEnv('REQUEST_METHOD', 'POST')
  715. ->withEnv('CONTENT_TYPE', 'application/json'));
  716. $this->assertEquals('json', $this->RequestHandler->requestedWith());
  717. $result = $this->RequestHandler->requestedWith(['json', 'xml']);
  718. $this->assertEquals('json', $result);
  719. $result = $this->RequestHandler->requestedWith(['rss', 'atom']);
  720. $this->assertFalse($result);
  721. $this->Controller->setRequest($this->request
  722. ->withEnv('REQUEST_METHOD', 'PATCH')
  723. ->withEnv('CONTENT_TYPE', 'application/json'));
  724. $this->assertEquals('json', $this->RequestHandler->requestedWith());
  725. $this->Controller->setRequest($this->request
  726. ->withEnv('REQUEST_METHOD', 'DELETE')
  727. ->withEnv('CONTENT_TYPE', 'application/json'));
  728. $this->assertEquals('json', $this->RequestHandler->requestedWith());
  729. $this->Controller->setRequest($this->request
  730. ->withEnv('REQUEST_METHOD', 'POST')
  731. ->withEnv('CONTENT_TYPE', 'application/json'));
  732. $result = $this->RequestHandler->requestedWith(['json', 'xml']);
  733. $this->assertEquals('json', $result);
  734. $result = $this->RequestHandler->requestedWith(['rss', 'atom']);
  735. $this->assertFalse($result);
  736. $this->Controller->setRequest($this->request->withHeader(
  737. 'Accept',
  738. 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  739. ));
  740. $this->assertTrue($this->RequestHandler->isXml());
  741. $this->assertFalse($this->RequestHandler->isAtom());
  742. $this->assertFalse($this->RequestHandler->isRSS());
  743. $this->Controller->setRequest($this->request->withHeader(
  744. 'Accept',
  745. 'application/atom+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  746. ));
  747. $this->assertTrue($this->RequestHandler->isAtom());
  748. $this->assertFalse($this->RequestHandler->isRSS());
  749. $this->Controller->setRequest($this->request->withHeader(
  750. 'Accept',
  751. 'application/rss+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  752. ));
  753. $this->assertFalse($this->RequestHandler->isAtom());
  754. $this->assertTrue($this->RequestHandler->isRSS());
  755. $this->assertFalse($this->RequestHandler->isWap());
  756. $this->Controller->setRequest($this->request->withHeader(
  757. 'Accept',
  758. 'text/vnd.wap.wml,text/html,text/plain,image/png,*/*'
  759. ));
  760. $this->assertTrue($this->RequestHandler->isWap());
  761. }
  762. /**
  763. * testResponseContentType method
  764. *
  765. * @return void
  766. */
  767. public function testResponseContentType()
  768. {
  769. $this->assertEquals('html', $this->RequestHandler->responseType());
  770. $this->assertTrue($this->RequestHandler->respondAs('atom'));
  771. $this->assertEquals('atom', $this->RequestHandler->responseType());
  772. }
  773. /**
  774. * testMobileDeviceDetection method
  775. *
  776. * @return void
  777. */
  778. public function testMobileDeviceDetection()
  779. {
  780. $request = $this->getMockBuilder('Cake\Http\ServerRequest')
  781. ->setMethods(['is'])
  782. ->getMock();
  783. $request->expects($this->once())->method('is')
  784. ->with('mobile')
  785. ->will($this->returnValue(true));
  786. $this->Controller->setRequest($request);
  787. $this->assertTrue($this->RequestHandler->isMobile());
  788. }
  789. /**
  790. * test that map alias converts aliases to content types.
  791. *
  792. * @return void
  793. */
  794. public function testMapAlias()
  795. {
  796. $result = $this->RequestHandler->mapAlias('xml');
  797. $this->assertEquals('application/xml', $result);
  798. $result = $this->RequestHandler->mapAlias('text/html');
  799. $this->assertNull($result);
  800. $result = $this->RequestHandler->mapAlias('wap');
  801. $this->assertEquals('text/vnd.wap.wml', $result);
  802. $result = $this->RequestHandler->mapAlias(['xml', 'js', 'json']);
  803. $expected = ['application/xml', 'application/javascript', 'application/json'];
  804. $this->assertEquals($expected, $result);
  805. }
  806. /**
  807. * test accepts() on the component
  808. *
  809. * @return void
  810. */
  811. public function testAccepts()
  812. {
  813. $this->Controller->setRequest($this->request->withHeader(
  814. 'Accept',
  815. 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'
  816. ));
  817. $this->assertTrue($this->RequestHandler->accepts(['js', 'xml', 'html']));
  818. $this->assertFalse($this->RequestHandler->accepts(['gif', 'jpeg', 'foo']));
  819. $this->Controller->setRequest($this->request->withHeader('Accept', '*/*;q=0.5'));
  820. $this->assertFalse($this->RequestHandler->accepts('rss'));
  821. }
  822. /**
  823. * test accepts and prefers methods.
  824. *
  825. * @return void
  826. */
  827. public function testPrefers()
  828. {
  829. $this->Controller->setRequest($this->request->withHeader(
  830. 'Accept',
  831. 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  832. ));
  833. $this->assertNotEquals('rss', $this->RequestHandler->prefers());
  834. $this->RequestHandler->ext = 'rss';
  835. $this->assertEquals('rss', $this->RequestHandler->prefers());
  836. $this->assertFalse($this->RequestHandler->prefers('xml'));
  837. $this->assertEquals('xml', $this->RequestHandler->prefers(['js', 'xml', 'xhtml']));
  838. $this->assertFalse($this->RequestHandler->prefers(['red', 'blue']));
  839. $this->assertEquals('xhtml', $this->RequestHandler->prefers(['js', 'json', 'xhtml']));
  840. $this->assertTrue($this->RequestHandler->prefers(['rss']), 'Should return true if input matches ext.');
  841. $this->assertFalse($this->RequestHandler->prefers(['html']), 'No match with ext, return false.');
  842. $this->_init();
  843. $this->Controller->setRequest($this->request->withHeader(
  844. 'Accept',
  845. 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'
  846. ));
  847. $this->assertEquals('xml', $this->RequestHandler->prefers());
  848. $this->Controller->setRequest($this->request->withHeader('Accept', '*/*;q=0.5'));
  849. $this->assertEquals('html', $this->RequestHandler->prefers());
  850. $this->assertFalse($this->RequestHandler->prefers('rss'));
  851. $this->Controller->setRequest($this->request->withEnv('HTTP_ACCEPT', null));
  852. $this->RequestHandler->ext = 'json';
  853. $this->assertFalse($this->RequestHandler->prefers('xml'));
  854. }
  855. /**
  856. * Test checkNotModified method
  857. *
  858. * @return void
  859. * @triggers Controller.beforeRender $this->Controller
  860. */
  861. public function testCheckNotModifiedByEtagStar()
  862. {
  863. $response = new Response();
  864. $response = $response->withEtag('something')
  865. ->withHeader('Content-Type', 'text/plain')
  866. ->withStringBody('keeper');
  867. $this->Controller->setResponse($response);
  868. $this->Controller->setRequest($this->request->withHeader('If-None-Match', '*'));
  869. $event = new Event('Controller.beforeRender', $this->Controller);
  870. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  871. $this->assertFalse($requestHandler->beforeRender($event));
  872. $this->assertEquals(304, $this->Controller->getResponse()->getStatusCode());
  873. $this->assertEquals('', (string)$this->Controller->getResponse()->getBody());
  874. $this->assertFalse($this->Controller->getResponse()->hasHeader('Content-Type'), 'header should not be removed.');
  875. }
  876. /**
  877. * Test checkNotModified method
  878. *
  879. * @return void
  880. * @triggers Controller.beforeRender
  881. */
  882. public function testCheckNotModifiedByEtagExact()
  883. {
  884. $response = new Response();
  885. $response = $response->withEtag('something', true)
  886. ->withHeader('Content-Type', 'text/plain')
  887. ->withStringBody('keeper');
  888. $this->Controller->setResponse($response);
  889. $this->Controller->setRequest($this->request->withHeader('If-None-Match', 'W/"something", "other"'));
  890. $event = new Event('Controller.beforeRender', $this->Controller);
  891. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  892. $this->assertFalse($requestHandler->beforeRender($event));
  893. $this->assertEquals(304, $this->Controller->getResponse()->getStatusCode());
  894. $this->assertEquals('', (string)$this->Controller->getResponse()->getBody());
  895. $this->assertFalse($this->Controller->getResponse()->hasHeader('Content-Type'));
  896. }
  897. /**
  898. * Test checkNotModified method
  899. *
  900. * @return void
  901. * @triggers Controller.beforeRender $this->Controller
  902. */
  903. public function testCheckNotModifiedByEtagAndTime()
  904. {
  905. $this->Controller->setRequest($this->request
  906. ->withHeader('If-None-Match', 'W/"something", "other"')
  907. ->withHeader('If-Modified-Since', '2012-01-01 00:00:00'));
  908. $response = new Response();
  909. $response = $response->withEtag('something', true)
  910. ->withHeader('Content-type', 'text/plain')
  911. ->withStringBody('should be removed')
  912. ->withModified('2012-01-01 00:00:00');
  913. $this->Controller->setResponse($response);
  914. $event = new Event('Controller.beforeRender', $this->Controller);
  915. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  916. $this->assertFalse($requestHandler->beforeRender($event));
  917. $this->assertEquals(304, $this->Controller->getResponse()->getStatusCode());
  918. $this->assertEquals('', (string)$this->Controller->getResponse()->getBody());
  919. $this->assertFalse($this->Controller->getResponse()->hasHeader('Content-type'));
  920. }
  921. /**
  922. * Test checkNotModified method
  923. *
  924. * @return void
  925. * @triggers Controller.beforeRender $this->Controller
  926. */
  927. public function testCheckNotModifiedNoInfo()
  928. {
  929. $response = $this->getMockBuilder('Cake\Http\Response')
  930. ->setMethods(['notModified', 'stop'])
  931. ->getMock();
  932. $response->expects($this->never())->method('notModified');
  933. $this->Controller->setResponse($response);
  934. $event = new Event('Controller.beforeRender', $this->Controller);
  935. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  936. $this->assertNull($requestHandler->beforeRender($event));
  937. }
  938. /**
  939. * Test default options in construction
  940. *
  941. * @return void
  942. */
  943. public function testConstructDefaultOptions()
  944. {
  945. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  946. $viewClass = $requestHandler->getConfig('viewClassMap');
  947. $expected = [
  948. 'json' => 'Json',
  949. 'xml' => 'Xml',
  950. 'ajax' => 'Ajax',
  951. ];
  952. $this->assertEquals($expected, $viewClass);
  953. $inputs = $requestHandler->getConfig('inputTypeMap');
  954. $this->assertArrayHasKey('json', $inputs);
  955. $this->assertArrayHasKey('xml', $inputs);
  956. }
  957. /**
  958. * Test options in constructor replace defaults
  959. *
  960. * @return void
  961. */
  962. public function testConstructReplaceOptions()
  963. {
  964. $requestHandler = new RequestHandlerComponent(
  965. $this->Controller->components(),
  966. [
  967. 'viewClassMap' => ['json' => 'Json'],
  968. 'inputTypeMap' => ['json' => ['json_decode', true]]
  969. ]
  970. );
  971. $viewClass = $requestHandler->getConfig('viewClassMap');
  972. $expected = [
  973. 'json' => 'Json',
  974. ];
  975. $this->assertEquals($expected, $viewClass);
  976. $inputs = $requestHandler->getConfig('inputTypeMap');
  977. $this->assertArrayHasKey('json', $inputs);
  978. $this->assertCount(1, $inputs);
  979. }
  980. /**
  981. * test beforeRender() doesn't override response type set in controller action
  982. *
  983. * @return void
  984. */
  985. public function testBeforeRender()
  986. {
  987. $this->Controller->set_response_type();
  988. $event = new Event('Controller.beforeRender', $this->Controller);
  989. $this->RequestHandler->beforeRender($event);
  990. $this->assertEquals('text/plain', $this->Controller->getResponse()->getType());
  991. }
  992. /**
  993. * tests beforeRender automatically uses renderAs when a supported extension is found
  994. *
  995. * @return void
  996. */
  997. public function testBeforeRenderAutoRenderAs()
  998. {
  999. $this->Controller->setRequest($this->request->withParam('_ext', 'csv'));
  1000. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  1001. $event = new Event('Controller.beforeRender', $this->Controller);
  1002. $this->RequestHandler->beforeRender($event);
  1003. $this->assertEquals('text/csv', $this->Controller->getResponse()->getType());
  1004. }
  1005. }