RequestHandlerComponentTest.php 54 KB

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