RequestHandlerComponentTest.php 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587
  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\DispatcherFactory;
  22. use Cake\Routing\RouteBuilder;
  23. use Cake\Routing\Router;
  24. use Cake\TestSuite\TestCase;
  25. use Cake\View\AjaxView;
  26. use Cake\View\JsonView;
  27. use Cake\View\XmlView;
  28. use TestApp\Controller\RequestHandlerTestController;
  29. use TestApp\View\AppView;
  30. use Zend\Diactoros\Stream;
  31. /**
  32. * RequestHandlerComponentTest class
  33. */
  34. class RequestHandlerComponentTest extends TestCase
  35. {
  36. /**
  37. * @var RequestHandlerTestController
  38. */
  39. public $Controller;
  40. /**
  41. * @var RequestHandlerComponent
  42. */
  43. public $RequestHandler;
  44. /**
  45. * @var ServerRequest
  46. */
  47. public $request;
  48. /**
  49. * Backup of $_SERVER
  50. *
  51. * @var array
  52. */
  53. protected $server = [];
  54. /**
  55. * setUp method
  56. *
  57. * @return void
  58. */
  59. public function setUp()
  60. {
  61. parent::setUp();
  62. $this->server = $_SERVER;
  63. static::setAppNamespace();
  64. DispatcherFactory::add('Routing');
  65. DispatcherFactory::add('ControllerFactory');
  66. $this->_init();
  67. }
  68. /**
  69. * init method
  70. *
  71. * @return void
  72. */
  73. protected function _init()
  74. {
  75. $request = new ServerRequest('controller_posts/index');
  76. $response = $this->getMockBuilder('Cake\Http\Response')
  77. ->setMethods(['_sendHeader', 'stop'])
  78. ->getMock();
  79. $this->Controller = new RequestHandlerTestController($request, $response);
  80. $this->RequestHandler = $this->Controller->components()->load('RequestHandler');
  81. $this->request = $request;
  82. Router::scope('/', function (RouteBuilder $routes) {
  83. $routes->setExtensions('json');
  84. $routes->fallbacks('InflectedRoute');
  85. });
  86. }
  87. /**
  88. * tearDown method
  89. *
  90. * @return void
  91. */
  92. public function tearDown()
  93. {
  94. parent::tearDown();
  95. DispatcherFactory::clear();
  96. Router::reload();
  97. Router::$initialized = false;
  98. $_SERVER = $this->server;
  99. unset($this->RequestHandler, $this->Controller);
  100. }
  101. /**
  102. * Test that the constructor sets the config.
  103. *
  104. * @return void
  105. */
  106. public function testConstructorConfig()
  107. {
  108. $config = [
  109. 'viewClassMap' => ['json' => 'MyPlugin.MyJson'],
  110. ];
  111. $controller = $this->getMockBuilder('Cake\Controller\Controller')
  112. ->setMethods(['redirect'])
  113. ->getMock();
  114. $collection = new ComponentRegistry($controller);
  115. $requestHandler = new RequestHandlerComponent($collection, $config);
  116. $this->assertEquals(['json' => 'MyPlugin.MyJson'], $requestHandler->getConfig('viewClassMap'));
  117. }
  118. /**
  119. * testInitializeCallback method
  120. *
  121. * @return void
  122. */
  123. public function testInitializeCallback()
  124. {
  125. $this->assertNull($this->RequestHandler->ext);
  126. $this->Controller->request = $this->Controller->request->withParam('_ext', 'rss');
  127. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  128. $this->assertEquals('rss', $this->RequestHandler->ext);
  129. }
  130. /**
  131. * test that a mapped Accept-type header will set $this->ext correctly.
  132. *
  133. * @return void
  134. */
  135. public function testInitializeContentTypeSettingExt()
  136. {
  137. Router::reload();
  138. Router::$initialized = true;
  139. $this->Controller->request = $this->request->withHeader('Accept', 'application/json');
  140. $this->RequestHandler->ext = null;
  141. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  142. $this->assertEquals('json', $this->RequestHandler->ext);
  143. }
  144. /**
  145. * Test that RequestHandler sets $this->ext when jQuery sends its wonky-ish headers.
  146. *
  147. * @return void
  148. */
  149. public function testInitializeContentTypeWithjQueryAccept()
  150. {
  151. Router::reload();
  152. Router::$initialized = true;
  153. $this->Controller->request = $this->request
  154. ->withHeader('Accept', 'application/json, application/javascript, */*; q=0.01')
  155. ->withHeader('X-Requested-With', 'XMLHttpRequest');
  156. $this->RequestHandler->ext = null;
  157. Router::extensions('json', false);
  158. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  159. $this->assertEquals('json', $this->RequestHandler->ext);
  160. }
  161. /**
  162. * Test that RequestHandler does not set extension to csv for text/plain mimetype
  163. *
  164. * @return void
  165. */
  166. public function testInitializeContentTypeWithjQueryTextPlainAccept()
  167. {
  168. Router::reload();
  169. Router::$initialized = true;
  170. $this->Controller->request = $this->request->withHeader('Accept', 'text/plain, */*; q=0.01');
  171. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  172. $this->assertNull($this->RequestHandler->ext);
  173. }
  174. /**
  175. * Test that RequestHandler sets $this->ext when jQuery sends its wonky-ish headers
  176. * and the application is configured to handle multiple extensions
  177. *
  178. * @return void
  179. */
  180. public function testInitializeContentTypeWithjQueryAcceptAndMultiplesExtensions()
  181. {
  182. Router::reload();
  183. Router::$initialized = true;
  184. $this->Controller->request = $this->request->withHeader('Accept', 'application/json, application/javascript, */*; q=0.01');
  185. $this->RequestHandler->ext = null;
  186. Router::extensions(['rss', 'json'], false);
  187. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  188. $this->assertEquals('json', $this->RequestHandler->ext);
  189. }
  190. /**
  191. * Test that RequestHandler does not set $this->ext when multiple accepts are sent.
  192. *
  193. * @return void
  194. */
  195. public function testInitializeNoContentTypeWithSingleAccept()
  196. {
  197. Router::reload();
  198. Router::$initialized = true;
  199. $_SERVER['HTTP_ACCEPT'] = 'application/json, text/html, */*; q=0.01';
  200. $this->assertNull($this->RequestHandler->ext);
  201. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  202. $this->assertNull($this->RequestHandler->ext);
  203. }
  204. /**
  205. * Test that ext is set to the first listed extension with multiple accepted
  206. * content types.
  207. * Having multiple types accepted with same weight, means the client lets the
  208. * server choose the returned content type.
  209. *
  210. * @return void
  211. */
  212. public function testInitializeNoContentTypeWithMultipleAcceptedTypes()
  213. {
  214. $this->Controller->request = $this->request->withHeader(
  215. 'Accept',
  216. 'application/json, application/javascript, application/xml, */*; q=0.01'
  217. );
  218. $this->RequestHandler->ext = null;
  219. Router::extensions(['xml', 'json'], false);
  220. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  221. $this->assertEquals('xml', $this->RequestHandler->ext);
  222. $this->RequestHandler->ext = null;
  223. Router::extensions(['json', 'xml'], false);
  224. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  225. $this->assertEquals('json', $this->RequestHandler->ext);
  226. }
  227. /**
  228. * Test that ext is set to type with highest weight
  229. *
  230. * @return void
  231. */
  232. public function testInitializeContentTypeWithMultipleAcceptedTypes()
  233. {
  234. Router::reload();
  235. Router::$initialized = true;
  236. $this->Controller->request = $this->request->withHeader(
  237. 'Accept',
  238. 'text/csv;q=1.0, application/json;q=0.8, application/xml;q=0.7'
  239. );
  240. $this->RequestHandler->ext = null;
  241. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  242. $this->assertEquals('json', $this->RequestHandler->ext);
  243. }
  244. /**
  245. * Test that ext is not set with confusing android accepts headers.
  246. *
  247. * @return void
  248. */
  249. public function testInitializeAmbiguousAndroidAccepts()
  250. {
  251. Router::reload();
  252. Router::$initialized = true;
  253. $this->request = $this->request->withEnv(
  254. 'HTTP_ACCEPT',
  255. 'application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'
  256. );
  257. $this->RequestHandler->ext = null;
  258. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  259. $this->assertNull($this->RequestHandler->ext);
  260. }
  261. /**
  262. * Test that the headers sent by firefox are not treated as XML requests.
  263. *
  264. * @return void
  265. */
  266. public function testInititalizeFirefoxHeaderNotXml()
  267. {
  268. $_SERVER['HTTP_ACCEPT'] = 'text/html,application/xhtml+xml,application/xml;image/png,image/jpeg,image/*;q=0.9,*/*;q=0.8';
  269. Router::extensions(['xml', 'json'], false);
  270. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  271. $this->assertNull($this->RequestHandler->ext);
  272. }
  273. /**
  274. * Test that a type mismatch doesn't incorrectly set the ext
  275. *
  276. * @return void
  277. */
  278. public function testInitializeContentTypeAndExtensionMismatch()
  279. {
  280. $this->assertNull($this->RequestHandler->ext);
  281. $extensions = Router::extensions();
  282. Router::extensions('xml', false);
  283. $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
  284. ->setMethods(['accepts'])
  285. ->getMock();
  286. $this->Controller->request->expects($this->any())
  287. ->method('accepts')
  288. ->will($this->returnValue(['application/json']));
  289. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  290. $this->assertNull($this->RequestHandler->ext);
  291. Router::extensions($extensions, false);
  292. }
  293. /**
  294. * testViewClassMap
  295. *
  296. * @return void
  297. */
  298. public function testViewClassMap()
  299. {
  300. $this->RequestHandler->setConfig(['viewClassMap' => ['json' => 'CustomJson']]);
  301. $result = $this->RequestHandler->getConfig('viewClassMap');
  302. $expected = [
  303. 'json' => 'CustomJson',
  304. 'xml' => 'Xml',
  305. 'ajax' => 'Ajax',
  306. ];
  307. $this->assertEquals($expected, $result);
  308. $this->RequestHandler->setConfig(['viewClassMap' => ['xls' => 'Excel.Excel']]);
  309. $result = $this->RequestHandler->getConfig('viewClassMap');
  310. $expected = [
  311. 'json' => 'CustomJson',
  312. 'xml' => 'Xml',
  313. 'ajax' => 'Ajax',
  314. 'xls' => 'Excel.Excel',
  315. ];
  316. $this->assertEquals($expected, $result);
  317. $this->RequestHandler->renderAs($this->Controller, 'json');
  318. $this->assertEquals('TestApp\View\CustomJsonView', $this->Controller->viewBuilder()->getClassName());
  319. }
  320. /**
  321. * test addInputType method
  322. *
  323. * @group deprecated
  324. * @return void
  325. */
  326. public function testDeprecatedAddInputType()
  327. {
  328. $this->deprecated(function () {
  329. $this->RequestHandler->addInputType('csv', ['str_getcsv']);
  330. $result = $this->RequestHandler->getConfig('inputTypeMap');
  331. $this->assertArrayHasKey('csv', $result);
  332. });
  333. }
  334. /**
  335. * testViewClassMap method
  336. *
  337. * @group deprecated
  338. * @return void
  339. */
  340. public function testViewClassMapMethod()
  341. {
  342. $this->deprecated(function () {
  343. $this->RequestHandler->setConfig(['viewClassMap' => ['json' => 'CustomJson']]);
  344. $result = $this->RequestHandler->viewClassMap();
  345. $expected = [
  346. 'json' => 'CustomJson',
  347. 'xml' => 'Xml',
  348. 'ajax' => 'Ajax',
  349. ];
  350. $this->assertEquals($expected, $result);
  351. $result = $this->RequestHandler->viewClassMap('xls', 'Excel.Excel');
  352. $expected = [
  353. 'json' => 'CustomJson',
  354. 'xml' => 'Xml',
  355. 'ajax' => 'Ajax',
  356. 'xls' => 'Excel.Excel',
  357. ];
  358. $this->assertEquals($expected, $result);
  359. $this->RequestHandler->renderAs($this->Controller, 'json');
  360. $this->assertEquals('TestApp\View\CustomJsonView', $this->Controller->viewBuilder()->getClassName());
  361. });
  362. }
  363. /**
  364. * Verify that isAjax is set on the request params for ajax requests
  365. *
  366. * @return void
  367. * @triggers Controller.startup $this->Controller
  368. */
  369. public function testIsAjaxParams()
  370. {
  371. $this->Controller->request = $this->request->withHeader('X-Requested-With', 'XMLHttpRequest');
  372. $event = new Event('Controller.startup', $this->Controller);
  373. $this->Controller->beforeFilter($event);
  374. $this->RequestHandler->startup($event);
  375. $this->assertTrue($this->Controller->request->getParam('isAjax'));
  376. }
  377. /**
  378. * testAutoAjaxLayout method
  379. *
  380. * @return void
  381. * @triggers Controller.startup $this->Controller
  382. */
  383. public function testAutoAjaxLayout()
  384. {
  385. $event = new Event('Controller.startup', $this->Controller);
  386. $this->Controller->request = $this->request->withHeader('X-Requested-With', 'XMLHttpRequest');
  387. $this->RequestHandler->startup($event);
  388. $event = new Event('Controller.beforeRender', $this->Controller);
  389. $this->RequestHandler->beforeRender($event);
  390. $view = $this->Controller->createView();
  391. $this->assertInstanceOf(AjaxView::class, $view);
  392. $this->assertEquals('ajax', $view->getLayout());
  393. $this->_init();
  394. $this->Controller->request = $this->Controller->request->withParam('_ext', 'js');
  395. $this->RequestHandler->startup($event);
  396. $this->assertNotEquals(AjaxView::class, $this->Controller->viewBuilder()->getClassName());
  397. }
  398. /**
  399. * @return array
  400. */
  401. public function defaultExtensionsProvider()
  402. {
  403. return [['html'], ['htm']];
  404. }
  405. /**
  406. * Tests that the default extensions are using the default view.
  407. *
  408. * @param string $extension Extension to test.
  409. * @dataProvider defaultExtensionsProvider
  410. * @return void
  411. */
  412. public function testDefaultExtensions($extension)
  413. {
  414. Router::extensions([$extension], false);
  415. $this->Controller->request = $this->Controller->request->withParam('_ext', $extension);
  416. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  417. $this->RequestHandler->beforeRender(new Event('Controller.beforeRender', $this->Controller));
  418. $this->assertEquals($extension, $this->RequestHandler->ext);
  419. $this->assertEquals('text/html', $this->Controller->response->getType());
  420. $view = $this->Controller->createView();
  421. $this->assertInstanceOf(AppView::class, $view);
  422. $this->assertEmpty($view->getLayoutPath());
  423. $this->assertEmpty($view->getSubDir());
  424. }
  425. /**
  426. * Tests that the default extensions can be overwritten by the accept header.
  427. *
  428. * @param string $extension Extension to test.
  429. * @dataProvider defaultExtensionsProvider
  430. * @return void
  431. */
  432. public function testDefaultExtensionsOverwrittenByAcceptHeader($extension)
  433. {
  434. Router::extensions([$extension], false);
  435. $this->Controller->request = $this->request->withHeader(
  436. 'Accept',
  437. 'application/xml'
  438. );
  439. $this->Controller->request = $this->Controller->request->withParam('_ext', $extension);
  440. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  441. $this->RequestHandler->beforeRender(new Event('Controller.beforeRender', $this->Controller));
  442. $this->assertEquals('xml', $this->RequestHandler->ext);
  443. $this->assertEquals('application/xml', $this->Controller->response->getType());
  444. $view = $this->Controller->createView();
  445. $this->assertInstanceOf(XmlView::class, $view);
  446. $this->assertEquals('xml', $view->getLayoutPath());
  447. $this->assertEquals('xml', $view->getSubDir());
  448. }
  449. /**
  450. * test custom JsonView class is loaded and correct.
  451. *
  452. * @return void
  453. * @triggers Controller.startup $this->Controller
  454. */
  455. public function testJsonViewLoaded()
  456. {
  457. Router::extensions(['json', 'xml', 'ajax'], false);
  458. $this->Controller->request = $this->Controller->request->withParam('_ext', 'json');
  459. $event = new Event('Controller.startup', $this->Controller);
  460. $this->RequestHandler->startup($event);
  461. $event = new Event('Controller.beforeRender', $this->Controller);
  462. $this->RequestHandler->beforeRender($event);
  463. $view = $this->Controller->createView();
  464. $this->assertInstanceOf(JsonView::class, $view);
  465. $this->assertEquals('json', $view->getLayoutPath());
  466. $this->assertEquals('json', $view->getSubDir());
  467. }
  468. /**
  469. * test custom XmlView class is loaded and correct.
  470. *
  471. * @return void
  472. * @triggers Controller.startup $this->Controller
  473. */
  474. public function testXmlViewLoaded()
  475. {
  476. Router::extensions(['json', 'xml', 'ajax'], false);
  477. $this->Controller->request = $this->Controller->request->withParam('_ext', 'xml');
  478. $event = new Event('Controller.startup', $this->Controller);
  479. $this->RequestHandler->startup($event);
  480. $event = new Event('Controller.beforeRender', $this->Controller);
  481. $this->RequestHandler->beforeRender($event);
  482. $view = $this->Controller->createView();
  483. $this->assertInstanceOf(XmlView::class, $view);
  484. $this->assertEquals('xml', $view->getLayoutPath());
  485. $this->assertEquals('xml', $view->getSubDir());
  486. }
  487. /**
  488. * test custom AjaxView class is loaded and correct.
  489. *
  490. * @return void
  491. * @triggers Controller.startup $this->Controller
  492. */
  493. public function testAjaxViewLoaded()
  494. {
  495. Router::extensions(['json', 'xml', 'ajax'], false);
  496. $this->Controller->request = $this->Controller->request->withParam('_ext', 'ajax');
  497. $event = new Event('Controller.startup', $this->Controller);
  498. $this->RequestHandler->startup($event);
  499. $event = new Event('Controller.beforeRender', $this->Controller);
  500. $this->RequestHandler->beforeRender($event);
  501. $view = $this->Controller->createView();
  502. $this->assertInstanceOf(AjaxView::class, $view);
  503. $this->assertEquals('ajax', $view->getLayout());
  504. }
  505. /**
  506. * test configured extension but no view class set.
  507. *
  508. * @return void
  509. * @triggers Controller.beforeRender $this->Controller
  510. */
  511. public function testNoViewClassExtension()
  512. {
  513. Router::extensions(['json', 'xml', 'ajax', 'csv'], false);
  514. $this->Controller->request = $this->Controller->request->withParam('_ext', 'csv');
  515. $event = new Event('Controller.startup', $this->Controller);
  516. $this->RequestHandler->startup($event);
  517. $this->Controller->getEventManager()->on('Controller.beforeRender', function () {
  518. return $this->Controller->response;
  519. });
  520. $this->Controller->render();
  521. $this->assertEquals('RequestHandlerTest' . DS . 'csv', $this->Controller->viewBuilder()->getTemplatePath());
  522. $this->assertEquals('csv', $this->Controller->viewBuilder()->getLayoutPath());
  523. }
  524. /**
  525. * Tests that configured extensions that have no configured mimetype do not silently fallback to HTML.
  526. *
  527. * @return void
  528. * @expectedException \Cake\Http\Exception\NotFoundException
  529. * @expectedExceptionMessage Invoked extension not recognized/configured: foo
  530. */
  531. public function testUnrecognizedExtensionFailure()
  532. {
  533. Router::extensions(['json', 'foo'], false);
  534. $this->Controller->setRequest($this->Controller->getRequest()->withParam('_ext', 'foo'));
  535. $event = new Event('Controller.startup', $this->Controller);
  536. $this->RequestHandler->startup($event);
  537. $this->Controller->getEventManager()->on('Controller.beforeRender', function () {
  538. return $this->Controller->getResponse();
  539. });
  540. $this->Controller->render();
  541. $this->assertEquals('RequestHandlerTest' . DS . 'csv', $this->Controller->viewBuilder()->getTemplatePath());
  542. }
  543. /**
  544. * testStartupCallback method
  545. *
  546. * @return void
  547. * @triggers Controller.beforeRender $this->Controller
  548. */
  549. public function testStartupCallback()
  550. {
  551. $event = new Event('Controller.beforeRender', $this->Controller);
  552. $_SERVER['REQUEST_METHOD'] = 'PUT';
  553. $_SERVER['CONTENT_TYPE'] = 'application/xml';
  554. $this->Controller->request = new ServerRequest();
  555. $this->RequestHandler->beforeRender($event);
  556. $this->assertInternalType('array', $this->Controller->request->getData());
  557. $this->assertNotInternalType('object', $this->Controller->request->getData());
  558. }
  559. /**
  560. * testStartupCallback with charset.
  561. *
  562. * @return void
  563. * @triggers Controller.startup $this->Controller
  564. */
  565. public function testStartupCallbackCharset()
  566. {
  567. $event = new Event('Controller.startup', $this->Controller);
  568. $_SERVER['REQUEST_METHOD'] = 'PUT';
  569. $_SERVER['CONTENT_TYPE'] = 'application/xml; charset=UTF-8';
  570. $this->Controller->request = new ServerRequest();
  571. $this->RequestHandler->startup($event);
  572. $this->assertInternalType('array', $this->Controller->request->getData());
  573. $this->assertNotInternalType('object', $this->Controller->request->getData());
  574. }
  575. /**
  576. * Test that processing data results in an array.
  577. *
  578. * @return void
  579. * @triggers Controller.startup $this->Controller
  580. */
  581. public function testStartupProcessDataInvalid()
  582. {
  583. $this->Controller->request = new ServerRequest([
  584. 'environment' => [
  585. 'REQUEST_METHOD' => 'POST',
  586. 'CONTENT_TYPE' => 'application/json',
  587. ],
  588. ]);
  589. $event = new Event('Controller.startup', $this->Controller);
  590. $this->RequestHandler->startup($event);
  591. $this->assertEquals([], $this->Controller->request->getData());
  592. $stream = new Stream('php://memory', 'w');
  593. $stream->write('"invalid"');
  594. $this->Controller->request = $this->Controller->request->withBody($stream);
  595. $this->RequestHandler->startup($event);
  596. $this->assertEquals(['invalid'], $this->Controller->request->getData());
  597. }
  598. /**
  599. * Test that processing data results in an array.
  600. *
  601. * @return void
  602. * @triggers Controller.startup $this->Controller
  603. */
  604. public function testStartupProcessData()
  605. {
  606. $this->Controller->request = new ServerRequest([
  607. 'environment' => [
  608. 'REQUEST_METHOD' => 'POST',
  609. 'CONTENT_TYPE' => 'application/json',
  610. ],
  611. ]);
  612. $stream = new Stream('php://memory', 'w');
  613. $stream->write('{"valid":true}');
  614. $this->Controller->request = $this->Controller->request->withBody($stream);
  615. $event = new Event('Controller.startup', $this->Controller);
  616. $this->RequestHandler->startup($event);
  617. $this->assertEquals(['valid' => true], $this->Controller->request->getData());
  618. }
  619. /**
  620. * Test that file handles are ignored as XML data.
  621. *
  622. * @return void
  623. * @triggers Controller.startup $this->Controller
  624. */
  625. public function testStartupIgnoreFileAsXml()
  626. {
  627. $this->Controller->request = new ServerRequest([
  628. 'input' => '/dev/random',
  629. 'environment' => [
  630. 'REQUEST_METHOD' => 'POST',
  631. 'CONTENT_TYPE' => 'application/xml',
  632. ],
  633. ]);
  634. $event = new Event('Controller.startup', $this->Controller);
  635. $this->RequestHandler->startup($event);
  636. $this->assertEquals([], $this->Controller->request->getData());
  637. }
  638. /**
  639. * Test that input xml is parsed
  640. *
  641. * @return void
  642. */
  643. public function testStartupConvertXmlDataWrapper()
  644. {
  645. $xml = <<<XML
  646. <?xml version="1.0" encoding="utf-8"?>
  647. <data>
  648. <article id="1" title="first"></article>
  649. </data>
  650. XML;
  651. $this->Controller->request = new ServerRequest(['input' => $xml]);
  652. $this->Controller->request = $this->Controller->request
  653. ->withEnv('REQUEST_METHOD', 'POST')
  654. ->withEnv('CONTENT_TYPE', 'application/xml');
  655. $event = new Event('Controller.startup', $this->Controller);
  656. $this->RequestHandler->startup($event);
  657. $expected = [
  658. 'data' => [
  659. 'article' => [
  660. '@id' => 1,
  661. '@title' => 'first',
  662. ],
  663. ],
  664. ];
  665. $this->assertEquals($expected, $this->Controller->request->getData());
  666. }
  667. /**
  668. * Test that input xml is parsed
  669. *
  670. * @return void
  671. */
  672. public function testStartupConvertXmlElements()
  673. {
  674. $xml = <<<XML
  675. <?xml version="1.0" encoding="utf-8"?>
  676. <article>
  677. <id>1</id>
  678. <title><![CDATA[first]]></title>
  679. </article>
  680. XML;
  681. $this->Controller->request = new ServerRequest(['input' => $xml]);
  682. $this->Controller->request = $this->Controller->request
  683. ->withEnv('REQUEST_METHOD', 'POST')
  684. ->withEnv('CONTENT_TYPE', 'application/xml');
  685. $event = new Event('Controller.startup', $this->Controller);
  686. $this->RequestHandler->startup($event);
  687. $expected = [
  688. 'article' => [
  689. 'id' => 1,
  690. 'title' => 'first',
  691. ],
  692. ];
  693. $this->assertEquals($expected, $this->Controller->request->getData());
  694. }
  695. /**
  696. * Test that input xml is parsed
  697. *
  698. * @return void
  699. */
  700. public function testStartupConvertXmlIgnoreEntities()
  701. {
  702. $xml = <<<XML
  703. <?xml version="1.0" encoding="UTF-8"?>
  704. <!DOCTYPE item [
  705. <!ENTITY item "item">
  706. <!ENTITY item1 "&item;&item;&item;&item;&item;&item;">
  707. <!ENTITY item2 "&item1;&item1;&item1;&item1;&item1;&item1;&item1;&item1;&item1;">
  708. <!ENTITY item3 "&item2;&item2;&item2;&item2;&item2;&item2;&item2;&item2;&item2;">
  709. <!ENTITY item4 "&item3;&item3;&item3;&item3;&item3;&item3;&item3;&item3;&item3;">
  710. <!ENTITY item5 "&item4;&item4;&item4;&item4;&item4;&item4;&item4;&item4;&item4;">
  711. <!ENTITY item6 "&item5;&item5;&item5;&item5;&item5;&item5;&item5;&item5;&item5;">
  712. <!ENTITY item7 "&item6;&item6;&item6;&item6;&item6;&item6;&item6;&item6;&item6;">
  713. <!ENTITY item8 "&item7;&item7;&item7;&item7;&item7;&item7;&item7;&item7;&item7;">
  714. ]>
  715. <item>
  716. <description>&item8;</description>
  717. </item>
  718. XML;
  719. $this->Controller->request = new ServerRequest(['input' => $xml]);
  720. $this->Controller->request = $this->Controller->request
  721. ->withEnv('REQUEST_METHOD', 'POST')
  722. ->withEnv('CONTENT_TYPE', 'application/xml');
  723. $event = new Event('Controller.startup', $this->Controller);
  724. $this->RequestHandler->startup($event);
  725. $this->assertEquals([], $this->Controller->request->getData());
  726. }
  727. /**
  728. * Test mapping a new type and having startup process it.
  729. *
  730. * @group deprecated
  731. * @return void
  732. * @triggers Controller.startup $this->Controller
  733. */
  734. public function testStartupCustomTypeProcess()
  735. {
  736. $this->deprecated(function () {
  737. $this->Controller->request = new ServerRequest([
  738. 'input' => '"A","csv","string"',
  739. 'environment' => [
  740. 'REQUEST_METHOD' => 'POST',
  741. 'CONTENT_TYPE' => 'text/csv',
  742. ],
  743. ]);
  744. $this->RequestHandler->addInputType('csv', ['str_getcsv']);
  745. $event = new Event('Controller.startup', $this->Controller);
  746. $this->RequestHandler->startup($event);
  747. $expected = [
  748. 'A', 'csv', 'string',
  749. ];
  750. $this->assertEquals($expected, $this->Controller->request->getData());
  751. });
  752. }
  753. /**
  754. * Test that data isn't processed when parsed data already exists.
  755. *
  756. * @return void
  757. * @triggers Controller.startup $this->Controller
  758. */
  759. public function testStartupSkipDataProcess()
  760. {
  761. $this->Controller->request = new ServerRequest([
  762. 'environment' => [
  763. 'REQUEST_METHOD' => 'POST',
  764. 'CONTENT_TYPE' => 'application/json',
  765. ],
  766. ]);
  767. $event = new Event('Controller.startup', $this->Controller);
  768. $this->RequestHandler->startup($event);
  769. $this->assertEquals([], $this->Controller->request->getData());
  770. $stream = new Stream('php://memory', 'w');
  771. $stream->write('{"new": "data"}');
  772. $this->Controller->request = $this->Controller->request
  773. ->withBody($stream)
  774. ->withParsedBody(['old' => 'news']);
  775. $this->RequestHandler->startup($event);
  776. $this->assertEquals(['old' => 'news'], $this->Controller->request->getData());
  777. }
  778. /**
  779. * test beforeRedirect when disabled.
  780. *
  781. * @return void
  782. * @triggers Controller.startup $this->Controller
  783. */
  784. public function testBeforeRedirectDisabled()
  785. {
  786. static::setAppNamespace();
  787. Router::connect('/:controller/:action');
  788. $this->Controller->request = $this->Controller->request->withHeader('X-Requested-With', 'XMLHttpRequest');
  789. $event = new Event('Controller.startup', $this->Controller);
  790. $this->RequestHandler->setConfig('enableBeforeRedirect', false);
  791. $this->RequestHandler->startup($event);
  792. $this->assertNull($this->RequestHandler->beforeRedirect($event, '/posts/index', $this->Controller->response));
  793. }
  794. /**
  795. * testNonAjaxRedirect method
  796. *
  797. * @group deprecated
  798. * @return void
  799. * @triggers Controller.startup $this->Controller
  800. */
  801. public function testNonAjaxRedirect()
  802. {
  803. $this->deprecated(function () {
  804. $event = new Event('Controller.startup', $this->Controller);
  805. $this->RequestHandler->startup($event);
  806. $this->assertNull($this->RequestHandler->beforeRedirect($event, '/', $this->Controller->response));
  807. });
  808. }
  809. /**
  810. * test that redirects with ajax and no URL don't do anything.
  811. *
  812. * @group deprecated
  813. * @return void
  814. * @triggers Controller.startup $this->Controller
  815. */
  816. public function testAjaxRedirectWithNoUrl()
  817. {
  818. $this->deprecated(function () {
  819. $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
  820. $event = new Event('Controller.startup', $this->Controller);
  821. $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  822. $this->Controller->response->expects($this->never())
  823. ->method('body');
  824. $this->RequestHandler->startup($event);
  825. $this->assertNull($this->RequestHandler->beforeRedirect($event, null, $this->Controller->response));
  826. });
  827. }
  828. /**
  829. * testRenderAs method
  830. *
  831. * @return void
  832. */
  833. public function testRenderAs()
  834. {
  835. $this->RequestHandler->renderAs($this->Controller, 'rss');
  836. $this->Controller->viewBuilder()->setTemplatePath('request_handler_test\\rss');
  837. $this->RequestHandler->renderAs($this->Controller, 'js');
  838. $this->assertEquals('request_handler_test' . DS . 'js', $this->Controller->viewBuilder()->getTemplatePath());
  839. }
  840. /**
  841. * test that attachment headers work with renderAs
  842. *
  843. * @return void
  844. */
  845. public function testRenderAsWithAttachment()
  846. {
  847. $this->Controller->request = $this->request->withHeader('Accept', 'application/xml;q=1.0');
  848. $this->RequestHandler->renderAs($this->Controller, 'xml', ['attachment' => 'myfile.xml']);
  849. $this->assertEquals(XmlView::class, $this->Controller->viewBuilder()->getClassName());
  850. $this->assertEquals('application/xml', $this->Controller->response->getType());
  851. $this->assertEquals('UTF-8', $this->Controller->response->getCharset());
  852. $this->assertContains('myfile.xml', $this->Controller->response->getHeaderLine('Content-Disposition'));
  853. }
  854. /**
  855. * test that respondAs works as expected.
  856. *
  857. * @return void
  858. */
  859. public function testRespondAs()
  860. {
  861. $result = $this->RequestHandler->respondAs('json');
  862. $this->assertTrue($result);
  863. $this->assertEquals('application/json', $this->Controller->response->getType());
  864. $result = $this->RequestHandler->respondAs('text/xml');
  865. $this->assertTrue($result);
  866. $this->assertEquals('text/xml', $this->Controller->response->getType());
  867. }
  868. /**
  869. * test that attachment headers work with respondAs
  870. *
  871. * @return void
  872. */
  873. public function testRespondAsWithAttachment()
  874. {
  875. $result = $this->RequestHandler->respondAs('xml', ['attachment' => 'myfile.xml']);
  876. $this->assertTrue($result);
  877. $response = $this->Controller->response;
  878. $this->assertContains('myfile.xml', $response->getHeaderLine('Content-Disposition'));
  879. $this->assertContains('application/xml', $response->getType());
  880. }
  881. /**
  882. * test that calling renderAs() more than once continues to work.
  883. *
  884. * @link #6466
  885. * @return void
  886. */
  887. public function testRenderAsCalledTwice()
  888. {
  889. $this->Controller->getEventManager()->on('Controller.beforeRender', function (\Cake\Event\Event $e) {
  890. return $e->getSubject()->response;
  891. });
  892. $this->Controller->render();
  893. $this->RequestHandler->renderAs($this->Controller, 'print');
  894. $this->assertEquals('RequestHandlerTest' . DS . 'print', $this->Controller->viewBuilder()->getTemplatePath());
  895. $this->assertEquals('print', $this->Controller->viewBuilder()->getLayoutPath());
  896. $this->RequestHandler->renderAs($this->Controller, 'js');
  897. $this->assertEquals('RequestHandlerTest' . DS . 'js', $this->Controller->viewBuilder()->getTemplatePath());
  898. $this->assertEquals('js', $this->Controller->viewBuilder()->getLayoutPath());
  899. }
  900. /**
  901. * testRequestContentTypes method
  902. *
  903. * @return void
  904. */
  905. public function testRequestContentTypes()
  906. {
  907. $this->Controller->request = $this->request->withEnv('REQUEST_METHOD', 'GET');
  908. $this->assertNull($this->RequestHandler->requestedWith());
  909. $this->Controller->request = $this->request->withEnv('REQUEST_METHOD', 'POST')
  910. ->withEnv('CONTENT_TYPE', 'application/json');
  911. $this->assertEquals('json', $this->RequestHandler->requestedWith());
  912. $result = $this->RequestHandler->requestedWith(['json', 'xml']);
  913. $this->assertEquals('json', $result);
  914. $result = $this->RequestHandler->requestedWith(['rss', 'atom']);
  915. $this->assertFalse($result);
  916. $this->Controller->request = $this->request
  917. ->withEnv('REQUEST_METHOD', 'PATCH')
  918. ->withEnv('CONTENT_TYPE', 'application/json');
  919. $this->assertEquals('json', $this->RequestHandler->requestedWith());
  920. $this->Controller->request = $this->request
  921. ->withEnv('REQUEST_METHOD', 'DELETE')
  922. ->withEnv('CONTENT_TYPE', 'application/json');
  923. $this->assertEquals('json', $this->RequestHandler->requestedWith());
  924. $this->Controller->request = $this->request
  925. ->withEnv('REQUEST_METHOD', 'POST')
  926. ->withEnv('CONTENT_TYPE', 'application/json');
  927. $result = $this->RequestHandler->requestedWith(['json', 'xml']);
  928. $this->assertEquals('json', $result);
  929. $result = $this->RequestHandler->requestedWith(['rss', 'atom']);
  930. $this->assertFalse($result);
  931. $this->Controller->request = $this->request->withHeader(
  932. 'Accept',
  933. 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  934. );
  935. $this->deprecated(function () {
  936. $this->assertTrue($this->RequestHandler->isXml());
  937. $this->assertFalse($this->RequestHandler->isAtom());
  938. $this->assertFalse($this->RequestHandler->isRSS());
  939. });
  940. $this->Controller->request = $this->request->withHeader(
  941. 'Accept',
  942. 'application/atom+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  943. );
  944. $this->deprecated(function () {
  945. $this->assertTrue($this->RequestHandler->isAtom());
  946. $this->assertFalse($this->RequestHandler->isRSS());
  947. });
  948. $this->Controller->request = $this->request->withHeader(
  949. 'Accept',
  950. 'application/rss+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  951. );
  952. $this->deprecated(function () {
  953. $this->assertFalse($this->RequestHandler->isAtom());
  954. $this->assertTrue($this->RequestHandler->isRSS());
  955. });
  956. $this->deprecated(function () {
  957. $this->assertFalse($this->RequestHandler->isWap());
  958. });
  959. $this->Controller->request = $this->request->withHeader(
  960. 'Accept',
  961. 'text/vnd.wap.wml,text/html,text/plain,image/png,*/*'
  962. );
  963. $this->deprecated(function () {
  964. $this->assertTrue($this->RequestHandler->isWap());
  965. });
  966. }
  967. /**
  968. * testResponseContentType method
  969. *
  970. * @return void
  971. */
  972. public function testResponseContentType()
  973. {
  974. $this->deprecated(function () {
  975. $this->assertEquals('html', $this->RequestHandler->responseType());
  976. $this->assertTrue($this->RequestHandler->respondAs('atom'));
  977. $this->assertEquals('atom', $this->RequestHandler->responseType());
  978. });
  979. }
  980. /**
  981. * testMobileDeviceDetection method
  982. *
  983. * @return void
  984. */
  985. public function testMobileDeviceDetection()
  986. {
  987. $request = $this->getMockBuilder('Cake\Http\ServerRequest')
  988. ->setMethods(['is'])
  989. ->getMock();
  990. $request->expects($this->once())->method('is')
  991. ->with('mobile')
  992. ->will($this->returnValue(true));
  993. $this->Controller->request = $request;
  994. $this->deprecated(function () {
  995. $this->assertTrue($this->RequestHandler->isMobile());
  996. });
  997. }
  998. /**
  999. * test that map alias converts aliases to content types.
  1000. *
  1001. * @return void
  1002. */
  1003. public function testMapAlias()
  1004. {
  1005. $result = $this->RequestHandler->mapAlias('xml');
  1006. $this->assertEquals('application/xml', $result);
  1007. $result = $this->RequestHandler->mapAlias('text/html');
  1008. $this->assertNull($result);
  1009. $result = $this->RequestHandler->mapAlias('wap');
  1010. $this->assertEquals('text/vnd.wap.wml', $result);
  1011. $result = $this->RequestHandler->mapAlias(['xml', 'js', 'json']);
  1012. $expected = ['application/xml', 'application/javascript', 'application/json'];
  1013. $this->assertEquals($expected, $result);
  1014. }
  1015. /**
  1016. * test accepts() on the component
  1017. *
  1018. * @return void
  1019. */
  1020. public function testAccepts()
  1021. {
  1022. $this->Controller->request = $this->request->withHeader(
  1023. 'Accept',
  1024. 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'
  1025. );
  1026. $this->assertTrue($this->RequestHandler->accepts(['js', 'xml', 'html']));
  1027. $this->assertFalse($this->RequestHandler->accepts(['gif', 'jpeg', 'foo']));
  1028. $this->Controller->request = $this->request->withHeader('Accept', '*/*;q=0.5');
  1029. $this->assertFalse($this->RequestHandler->accepts('rss'));
  1030. }
  1031. /**
  1032. * test accepts and prefers methods.
  1033. *
  1034. * @return void
  1035. */
  1036. public function testPrefers()
  1037. {
  1038. $this->Controller->request = $this->request->withHeader(
  1039. 'Accept',
  1040. 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  1041. );
  1042. $this->assertNotEquals('rss', $this->RequestHandler->prefers());
  1043. $this->RequestHandler->ext = 'rss';
  1044. $this->assertEquals('rss', $this->RequestHandler->prefers());
  1045. $this->assertFalse($this->RequestHandler->prefers('xml'));
  1046. $this->assertEquals('xml', $this->RequestHandler->prefers(['js', 'xml', 'xhtml']));
  1047. $this->assertFalse($this->RequestHandler->prefers(['red', 'blue']));
  1048. $this->assertEquals('xhtml', $this->RequestHandler->prefers(['js', 'json', 'xhtml']));
  1049. $this->assertTrue($this->RequestHandler->prefers(['rss']), 'Should return true if input matches ext.');
  1050. $this->assertFalse($this->RequestHandler->prefers(['html']), 'No match with ext, return false.');
  1051. $this->_init();
  1052. $this->Controller->request = $this->request->withHeader(
  1053. 'Accept',
  1054. 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'
  1055. );
  1056. $this->assertEquals('xml', $this->RequestHandler->prefers());
  1057. $this->Controller->request = $this->request->withHeader('Accept', '*/*;q=0.5');
  1058. $this->assertEquals('html', $this->RequestHandler->prefers());
  1059. $this->assertFalse($this->RequestHandler->prefers('rss'));
  1060. $this->Controller->request = $this->request->withEnv('HTTP_ACCEPT', null);
  1061. $this->RequestHandler->ext = 'json';
  1062. $this->assertFalse($this->RequestHandler->prefers('xml'));
  1063. }
  1064. /**
  1065. * test that AJAX requests involving redirects trigger requestAction instead.
  1066. *
  1067. * @group deprecated
  1068. * @return void
  1069. * @triggers Controller.beforeRedirect $this->Controller
  1070. */
  1071. public function testAjaxRedirectAsRequestAction()
  1072. {
  1073. $this->deprecated(function () {
  1074. static::setAppNamespace();
  1075. Router::connect('/:controller/:action');
  1076. $event = new Event('Controller.beforeRedirect', $this->Controller);
  1077. $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
  1078. $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
  1079. ->setMethods(['is'])
  1080. ->getMock();
  1081. $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
  1082. ->setMethods(['_sendHeader', 'stop'])
  1083. ->getMock();
  1084. $this->Controller->request->expects($this->any())
  1085. ->method('is')
  1086. ->will($this->returnValue(true));
  1087. $response = $this->RequestHandler->beforeRedirect(
  1088. $event,
  1089. ['controller' => 'RequestHandlerTest', 'action' => 'destination'],
  1090. $this->Controller->response
  1091. );
  1092. $this->assertRegExp('/posts index/', $response->body(), 'RequestAction redirect failed.');
  1093. });
  1094. }
  1095. /**
  1096. * Test that AJAX requests involving redirects handle querystrings
  1097. *
  1098. * @group deprecated
  1099. * @return void
  1100. * @triggers Controller.beforeRedirect $this->Controller
  1101. */
  1102. public function testAjaxRedirectAsRequestActionWithQueryString()
  1103. {
  1104. $this->deprecated(function () {
  1105. static::setAppNamespace();
  1106. Router::connect('/:controller/:action');
  1107. $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
  1108. $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
  1109. ->setMethods(['is'])
  1110. ->getMock();
  1111. $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
  1112. ->setMethods(['_sendHeader', 'stop'])
  1113. ->getMock();
  1114. $this->Controller->request->expects($this->any())
  1115. ->method('is')
  1116. ->with('ajax')
  1117. ->will($this->returnValue(true));
  1118. $event = new Event('Controller.beforeRedirect', $this->Controller);
  1119. $response = $this->RequestHandler->beforeRedirect(
  1120. $event,
  1121. '/request_action/params_pass?a=b&x=y?ish',
  1122. $this->Controller->response
  1123. );
  1124. $data = json_decode($response, true);
  1125. $this->assertEquals('/request_action/params_pass', $data['here']);
  1126. $response = $this->RequestHandler->beforeRedirect(
  1127. $event,
  1128. '/request_action/query_pass?a=b&x=y?ish',
  1129. $this->Controller->response
  1130. );
  1131. $data = json_decode($response, true);
  1132. $this->assertEquals('y?ish', $data['x']);
  1133. });
  1134. }
  1135. /**
  1136. * Test that AJAX requests involving redirects handle cookie data
  1137. *
  1138. * @group deprecated
  1139. * @return void
  1140. * @triggers Controller.beforeRedirect $this->Controller
  1141. */
  1142. public function testAjaxRedirectAsRequestActionWithCookieData()
  1143. {
  1144. $this->deprecated(function () {
  1145. static::setAppNamespace();
  1146. Router::connect('/:controller/:action');
  1147. $event = new Event('Controller.beforeRedirect', $this->Controller);
  1148. $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
  1149. $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
  1150. ->setMethods(['is'])
  1151. ->getMock();
  1152. $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
  1153. ->setMethods(['_sendHeader', 'stop'])
  1154. ->getMock();
  1155. $this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true));
  1156. $cookies = [
  1157. 'foo' => 'bar',
  1158. ];
  1159. $this->Controller->request->cookies = $cookies;
  1160. $response = $this->RequestHandler->beforeRedirect(
  1161. $event,
  1162. '/request_action/cookie_pass',
  1163. $this->Controller->response
  1164. );
  1165. $data = json_decode($response, true);
  1166. $this->assertEquals($cookies, $data);
  1167. });
  1168. }
  1169. /**
  1170. * Tests that AJAX requests involving redirects don't let the status code bleed through.
  1171. *
  1172. * @group deprecated
  1173. * @return void
  1174. * @triggers Controller.beforeRedirect $this->Controller
  1175. */
  1176. public function testAjaxRedirectAsRequestActionStatusCode()
  1177. {
  1178. $this->deprecated(function () {
  1179. static::setAppNamespace();
  1180. Router::connect('/:controller/:action');
  1181. $event = new Event('Controller.beforeRedirect', $this->Controller);
  1182. $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
  1183. $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
  1184. ->setMethods(['is'])
  1185. ->getMock();
  1186. $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
  1187. ->setMethods(['_sendHeader', 'stop'])
  1188. ->getMock();
  1189. $this->Controller->response->statusCode(302);
  1190. $this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true));
  1191. $response = $this->RequestHandler->beforeRedirect(
  1192. $event,
  1193. ['controller' => 'RequestHandlerTest', 'action' => 'destination'],
  1194. $this->Controller->response
  1195. );
  1196. $this->assertRegExp('/posts index/', $response->body(), 'RequestAction redirect failed.');
  1197. $this->assertSame(200, $response->statusCode());
  1198. });
  1199. }
  1200. /**
  1201. * test that ajax requests involving redirects don't force no layout
  1202. * this would cause the ajax layout to not be rendered.
  1203. *
  1204. * @group deprecated
  1205. * @return void
  1206. * @triggers Controller.beforeRedirect $this->Controller
  1207. */
  1208. public function testAjaxRedirectAsRequestActionStillRenderingLayout()
  1209. {
  1210. $this->deprecated(function () {
  1211. static::setAppNamespace();
  1212. Router::connect('/:controller/:action');
  1213. $event = new Event('Controller.beforeRedirect', $this->Controller);
  1214. $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
  1215. $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
  1216. ->setMethods(['is'])
  1217. ->getMock();
  1218. $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
  1219. ->setMethods(['_sendHeader', 'stop'])
  1220. ->getMock();
  1221. $this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true));
  1222. $response = $this->RequestHandler->beforeRedirect(
  1223. $event,
  1224. ['controller' => 'RequestHandlerTest', 'action' => 'ajax2_layout'],
  1225. $this->Controller->response
  1226. );
  1227. $this->assertRegExp('/posts index/', $response->body(), 'RequestAction redirect failed.');
  1228. $this->assertRegExp('/Ajax!/', $response->body(), 'Layout was not rendered.');
  1229. });
  1230. }
  1231. /**
  1232. * test that the beforeRedirect callback properly converts
  1233. * array URLs into their correct string ones, and adds base => false so
  1234. * the correct URLs are generated.
  1235. *
  1236. * @group deprecated
  1237. * @return void
  1238. * @triggers Controller.beforeRender $this->Controller
  1239. */
  1240. public function testBeforeRedirectCallbackWithArrayUrl()
  1241. {
  1242. $this->deprecated(function () {
  1243. static::setAppNamespace();
  1244. Router::connect('/:controller/:action/*');
  1245. $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
  1246. $event = new Event('Controller.beforeRender', $this->Controller);
  1247. Router::setRequestInfo([
  1248. ['plugin' => null, 'controller' => 'accounts', 'action' => 'index', 'pass' => []],
  1249. ['base' => '', 'here' => '/accounts/', 'webroot' => '/'],
  1250. ]);
  1251. $RequestHandler = new RequestHandlerComponent($this->Controller->components());
  1252. $this->Controller->request = new ServerRequest('posts/index');
  1253. ob_start();
  1254. $RequestHandler->beforeRedirect(
  1255. $event,
  1256. ['controller' => 'RequestHandlerTest', 'action' => 'param_method', 'first', 'second'],
  1257. $this->Controller->response
  1258. );
  1259. $result = ob_get_clean();
  1260. $this->assertEquals('one: first two: second', $result);
  1261. });
  1262. }
  1263. /**
  1264. * testAddInputTypeException method
  1265. *
  1266. * @group deprecated
  1267. * @return void
  1268. */
  1269. public function testAddInputTypeException()
  1270. {
  1271. $this->expectException(\Cake\Core\Exception\Exception::class);
  1272. $this->deprecated(function () {
  1273. $this->RequestHandler->addInputType('csv', ['I am not callable']);
  1274. });
  1275. }
  1276. /**
  1277. * Test checkNotModified method
  1278. *
  1279. * @return void
  1280. * @triggers Controller.beforeRender $this->Controller
  1281. */
  1282. public function testCheckNotModifiedByEtagStar()
  1283. {
  1284. $response = new Response();
  1285. $response = $response->withEtag('something')
  1286. ->withHeader('Content-Type', 'text/plain')
  1287. ->withStringBody('keeper');
  1288. $this->Controller->response = $response;
  1289. $this->Controller->request = $this->request->withHeader('If-None-Match', '*');
  1290. $event = new Event('Controller.beforeRender', $this->Controller);
  1291. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  1292. $this->assertFalse($requestHandler->beforeRender($event));
  1293. $this->assertEquals(304, $this->Controller->response->getStatusCode());
  1294. $this->assertEquals('', (string)$this->Controller->response->getBody());
  1295. $this->assertFalse($this->Controller->response->hasHeader('Content-Type'), 'header should not be removed.');
  1296. }
  1297. /**
  1298. * Test checkNotModified method
  1299. *
  1300. * @return void
  1301. * @triggers Controller.beforeRender
  1302. */
  1303. public function testCheckNotModifiedByEtagExact()
  1304. {
  1305. $response = new Response();
  1306. $response = $response->withEtag('something', true)
  1307. ->withHeader('Content-Type', 'text/plain')
  1308. ->withStringBody('keeper');
  1309. $this->Controller->response = $response;
  1310. $this->Controller->request = $this->request->withHeader('If-None-Match', 'W/"something", "other"');
  1311. $event = new Event('Controller.beforeRender', $this->Controller);
  1312. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  1313. $this->assertFalse($requestHandler->beforeRender($event));
  1314. $this->assertEquals(304, $this->Controller->response->getStatusCode());
  1315. $this->assertEquals('', (string)$this->Controller->response->getBody());
  1316. $this->assertFalse($this->Controller->response->hasHeader('Content-Type'));
  1317. }
  1318. /**
  1319. * Test checkNotModified method
  1320. *
  1321. * @return void
  1322. * @triggers Controller.beforeRender $this->Controller
  1323. */
  1324. public function testCheckNotModifiedByEtagAndTime()
  1325. {
  1326. $this->Controller->request = $this->request
  1327. ->withHeader('If-None-Match', 'W/"something", "other"')
  1328. ->withHeader('If-Modified-Since', '2012-01-01 00:00:00');
  1329. $response = new Response();
  1330. $response = $response->withEtag('something', true)
  1331. ->withHeader('Content-type', 'text/plain')
  1332. ->withStringBody('should be removed')
  1333. ->withModified('2012-01-01 00:00:00');
  1334. $this->Controller->response = $response;
  1335. $event = new Event('Controller.beforeRender', $this->Controller);
  1336. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  1337. $this->assertFalse($requestHandler->beforeRender($event));
  1338. $this->assertEquals(304, $this->Controller->response->getStatusCode());
  1339. $this->assertEquals('', (string)$this->Controller->response->getBody());
  1340. $this->assertFalse($this->Controller->response->hasHeader('Content-type'));
  1341. }
  1342. /**
  1343. * Test checkNotModified method
  1344. *
  1345. * @return void
  1346. * @triggers Controller.beforeRender $this->Controller
  1347. */
  1348. public function testCheckNotModifiedNoInfo()
  1349. {
  1350. $response = $this->getMockBuilder('Cake\Http\Response')
  1351. ->setMethods(['notModified', 'stop'])
  1352. ->getMock();
  1353. $response->expects($this->never())->method('notModified');
  1354. $this->Controller->response = $response;
  1355. $event = new Event('Controller.beforeRender', $this->Controller);
  1356. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  1357. $this->assertNull($requestHandler->beforeRender($event));
  1358. }
  1359. /**
  1360. * Test default options in construction
  1361. *
  1362. * @return void
  1363. */
  1364. public function testConstructDefaultOptions()
  1365. {
  1366. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  1367. $viewClass = $requestHandler->getConfig('viewClassMap');
  1368. $expected = [
  1369. 'json' => 'Json',
  1370. 'xml' => 'Xml',
  1371. 'ajax' => 'Ajax',
  1372. ];
  1373. $this->assertEquals($expected, $viewClass);
  1374. $inputs = $requestHandler->getConfig('inputTypeMap');
  1375. $this->assertArrayHasKey('json', $inputs);
  1376. $this->assertArrayHasKey('xml', $inputs);
  1377. }
  1378. /**
  1379. * Test options in constructor replace defaults
  1380. *
  1381. * @return void
  1382. */
  1383. public function testConstructReplaceOptions()
  1384. {
  1385. $requestHandler = new RequestHandlerComponent(
  1386. $this->Controller->components(),
  1387. [
  1388. 'viewClassMap' => ['json' => 'Json'],
  1389. 'inputTypeMap' => ['json' => ['json_decode', true]],
  1390. ]
  1391. );
  1392. $viewClass = $requestHandler->getConfig('viewClassMap');
  1393. $expected = [
  1394. 'json' => 'Json',
  1395. ];
  1396. $this->assertEquals($expected, $viewClass);
  1397. $inputs = $requestHandler->getConfig('inputTypeMap');
  1398. $this->assertArrayHasKey('json', $inputs);
  1399. $this->assertCount(1, $inputs);
  1400. }
  1401. /**
  1402. * test beforeRender() doesn't override response type set in controller action
  1403. *
  1404. * @return void
  1405. */
  1406. public function testBeforeRender()
  1407. {
  1408. $this->Controller->set_response_type();
  1409. $event = new Event('Controller.beforeRender', $this->Controller);
  1410. $this->RequestHandler->beforeRender($event);
  1411. $this->assertEquals('text/plain', $this->Controller->response->getType());
  1412. }
  1413. /**
  1414. * tests beforeRender automatically uses renderAs when a supported extension is found
  1415. *
  1416. * @return void
  1417. */
  1418. public function testBeforeRenderAutoRenderAs()
  1419. {
  1420. $this->Controller->setRequest($this->request->withParam('_ext', 'csv'));
  1421. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  1422. $event = new Event('Controller.beforeRender', $this->Controller);
  1423. $this->RequestHandler->beforeRender($event);
  1424. $this->assertEquals('text/csv', $this->Controller->response->getType());
  1425. }
  1426. }