RequestHandlerComponentTest.php 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504
  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\Router;
  23. use Cake\TestSuite\TestCase;
  24. use TestApp\Controller\RequestHandlerTestController;
  25. use Zend\Diactoros\Stream;
  26. /**
  27. * RequestHandlerComponentTest class
  28. */
  29. class RequestHandlerComponentTest extends TestCase
  30. {
  31. /**
  32. * Controller property
  33. *
  34. * @var RequestHandlerTestController
  35. */
  36. public $Controller;
  37. /**
  38. * RequestHandler property
  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 ($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. $this->RequestHandler->initialize([]);
  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->viewClass);
  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->RequestHandler->initialize([]);
  374. $this->Controller->beforeFilter($event);
  375. $this->RequestHandler->startup($event);
  376. $this->assertTrue($this->Controller->request->getParam('isAjax'));
  377. }
  378. /**
  379. * testAutoAjaxLayout method
  380. *
  381. * @return void
  382. * @triggers Controller.startup $this->Controller
  383. */
  384. public function testAutoAjaxLayout()
  385. {
  386. $event = new Event('Controller.startup', $this->Controller);
  387. $this->Controller->request = $this->request->withHeader('X-Requested-With', 'XMLHttpRequest');
  388. $this->RequestHandler->initialize([]);
  389. $this->RequestHandler->startup($event);
  390. $event = new Event('Controller.beforeRender', $this->Controller);
  391. $this->RequestHandler->beforeRender($event);
  392. $this->assertEquals($this->Controller->viewClass, 'Cake\View\AjaxView');
  393. $view = $this->Controller->createView();
  394. $this->assertEquals('ajax', $view->getLayout());
  395. $this->_init();
  396. $this->Controller->request = $this->Controller->request->withParam('_ext', 'js');
  397. $this->RequestHandler->initialize([]);
  398. $this->RequestHandler->startup($event);
  399. $this->assertNotEquals($this->Controller->viewClass, 'Cake\View\AjaxView');
  400. }
  401. /**
  402. * test custom JsonView class is loaded and correct.
  403. *
  404. * @return void
  405. * @triggers Controller.startup $this->Controller
  406. */
  407. public function testJsonViewLoaded()
  408. {
  409. Router::extensions(['json', 'xml', 'ajax'], false);
  410. $this->Controller->request = $this->Controller->request->withParam('_ext', 'json');
  411. $event = new Event('Controller.startup', $this->Controller);
  412. $this->RequestHandler->initialize([]);
  413. $this->RequestHandler->startup($event);
  414. $event = new Event('Controller.beforeRender', $this->Controller);
  415. $this->RequestHandler->beforeRender($event);
  416. $this->assertEquals('Cake\View\JsonView', $this->Controller->viewClass);
  417. $view = $this->Controller->createView();
  418. $this->assertEquals('json', $view->getLayoutPath());
  419. $this->assertEquals('json', $view->subDir);
  420. }
  421. /**
  422. * test custom XmlView class is loaded and correct.
  423. *
  424. * @return void
  425. * @triggers Controller.startup $this->Controller
  426. */
  427. public function testXmlViewLoaded()
  428. {
  429. Router::extensions(['json', 'xml', 'ajax'], false);
  430. $this->Controller->request = $this->Controller->request->withParam('_ext', 'xml');
  431. $event = new Event('Controller.startup', $this->Controller);
  432. $this->RequestHandler->initialize([]);
  433. $this->RequestHandler->startup($event);
  434. $event = new Event('Controller.beforeRender', $this->Controller);
  435. $this->RequestHandler->beforeRender($event);
  436. $this->assertEquals('Cake\View\XmlView', $this->Controller->viewClass);
  437. $view = $this->Controller->createView();
  438. $this->assertEquals('xml', $view->getLayoutPath());
  439. $this->assertEquals('xml', $view->subDir);
  440. }
  441. /**
  442. * test custom AjaxView class is loaded and correct.
  443. *
  444. * @return void
  445. * @triggers Controller.startup $this->Controller
  446. */
  447. public function testAjaxViewLoaded()
  448. {
  449. Router::extensions(['json', 'xml', 'ajax'], false);
  450. $this->Controller->request = $this->Controller->request->withParam('_ext', 'ajax');
  451. $event = new Event('Controller.startup', $this->Controller);
  452. $this->RequestHandler->initialize([]);
  453. $this->RequestHandler->startup($event);
  454. $event = new Event('Controller.beforeRender', $this->Controller);
  455. $this->RequestHandler->beforeRender($event);
  456. $this->assertEquals('Cake\View\AjaxView', $this->Controller->viewClass);
  457. $view = $this->Controller->createView();
  458. $this->assertEquals('ajax', $view->getLayout());
  459. }
  460. /**
  461. * test configured extension but no view class set.
  462. *
  463. * @return void
  464. * @triggers Controller.beforeRender $this->Controller
  465. */
  466. public function testNoViewClassExtension()
  467. {
  468. Router::extensions(['json', 'xml', 'ajax', 'csv'], false);
  469. $this->Controller->request = $this->Controller->request->withParam('_ext', 'csv');
  470. $event = new Event('Controller.startup', $this->Controller);
  471. $this->RequestHandler->initialize([]);
  472. $this->RequestHandler->startup($event);
  473. $this->Controller->getEventManager()->on('Controller.beforeRender', function () {
  474. return $this->Controller->response;
  475. });
  476. $this->Controller->render();
  477. $this->assertEquals('RequestHandlerTest' . DS . 'csv', $this->Controller->viewBuilder()->templatePath());
  478. $this->assertEquals('csv', $this->Controller->viewBuilder()->layoutPath());
  479. }
  480. /**
  481. * testStartupCallback method
  482. *
  483. * @return void
  484. * @triggers Controller.beforeRender $this->Controller
  485. */
  486. public function testStartupCallback()
  487. {
  488. $event = new Event('Controller.beforeRender', $this->Controller);
  489. $_SERVER['REQUEST_METHOD'] = 'PUT';
  490. $_SERVER['CONTENT_TYPE'] = 'application/xml';
  491. $this->Controller->request = new ServerRequest();
  492. $this->RequestHandler->beforeRender($event);
  493. $this->assertInternalType('array', $this->Controller->request->getData());
  494. $this->assertNotInternalType('object', $this->Controller->request->getData());
  495. }
  496. /**
  497. * testStartupCallback with charset.
  498. *
  499. * @return void
  500. * @triggers Controller.startup $this->Controller
  501. */
  502. public function testStartupCallbackCharset()
  503. {
  504. $event = new Event('Controller.startup', $this->Controller);
  505. $_SERVER['REQUEST_METHOD'] = 'PUT';
  506. $_SERVER['CONTENT_TYPE'] = 'application/xml; charset=UTF-8';
  507. $this->Controller->request = new ServerRequest();
  508. $this->RequestHandler->startup($event);
  509. $this->assertInternalType('array', $this->Controller->request->getData());
  510. $this->assertNotInternalType('object', $this->Controller->request->getData());
  511. }
  512. /**
  513. * Test that processing data results in an array.
  514. *
  515. * @return void
  516. * @triggers Controller.startup $this->Controller
  517. */
  518. public function testStartupProcessDataInvalid()
  519. {
  520. $this->Controller->request = new ServerRequest([
  521. 'environment' => [
  522. 'REQUEST_METHOD' => 'POST',
  523. 'CONTENT_TYPE' => 'application/json'
  524. ]
  525. ]);
  526. $event = new Event('Controller.startup', $this->Controller);
  527. $this->RequestHandler->startup($event);
  528. $this->assertEquals([], $this->Controller->request->getData());
  529. $stream = new Stream('php://memory', 'w');
  530. $stream->write('"invalid"');
  531. $this->Controller->request = $this->Controller->request->withBody($stream);
  532. $this->RequestHandler->startup($event);
  533. $this->assertEquals(['invalid'], $this->Controller->request->getData());
  534. }
  535. /**
  536. * Test that processing data results in an array.
  537. *
  538. * @return void
  539. * @triggers Controller.startup $this->Controller
  540. */
  541. public function testStartupProcessData()
  542. {
  543. $this->Controller->request = new ServerRequest([
  544. 'environment' => [
  545. 'REQUEST_METHOD' => 'POST',
  546. 'CONTENT_TYPE' => 'application/json'
  547. ]
  548. ]);
  549. $stream = new Stream('php://memory', 'w');
  550. $stream->write('{"valid":true}');
  551. $this->Controller->request = $this->Controller->request->withBody($stream);
  552. $event = new Event('Controller.startup', $this->Controller);
  553. $this->RequestHandler->startup($event);
  554. $this->assertEquals(['valid' => true], $this->Controller->request->getData());
  555. }
  556. /**
  557. * Test that file handles are ignored as XML data.
  558. *
  559. * @return void
  560. * @triggers Controller.startup $this->Controller
  561. */
  562. public function testStartupIgnoreFileAsXml()
  563. {
  564. $this->Controller->request = new ServerRequest([
  565. 'input' => '/dev/random',
  566. 'environment' => [
  567. 'REQUEST_METHOD' => 'POST',
  568. 'CONTENT_TYPE' => 'application/xml'
  569. ]
  570. ]);
  571. $event = new Event('Controller.startup', $this->Controller);
  572. $this->RequestHandler->startup($event);
  573. $this->assertEquals([], $this->Controller->request->getData());
  574. }
  575. /**
  576. * Test that input xml is parsed
  577. *
  578. * @return void
  579. */
  580. public function testStartupConvertXmlDataWrapper()
  581. {
  582. $xml = <<<XML
  583. <?xml version="1.0" encoding="utf-8"?>
  584. <data>
  585. <article id="1" title="first"></article>
  586. </data>
  587. XML;
  588. $this->Controller->request = new ServerRequest(['input' => $xml]);
  589. $this->Controller->request = $this->Controller->request
  590. ->withEnv('REQUEST_METHOD', 'POST')
  591. ->withEnv('CONTENT_TYPE', 'application/xml');
  592. $event = new Event('Controller.startup', $this->Controller);
  593. $this->RequestHandler->startup($event);
  594. $expected = [
  595. 'data' => [
  596. 'article' => [
  597. '@id' => 1,
  598. '@title' => 'first'
  599. ]
  600. ]
  601. ];
  602. $this->assertEquals($expected, $this->Controller->request->getData());
  603. }
  604. /**
  605. * Test that input xml is parsed
  606. *
  607. * @return void
  608. */
  609. public function testStartupConvertXmlElements()
  610. {
  611. $xml = <<<XML
  612. <?xml version="1.0" encoding="utf-8"?>
  613. <article>
  614. <id>1</id>
  615. <title><![CDATA[first]]></title>
  616. </article>
  617. XML;
  618. $this->Controller->request = new ServerRequest(['input' => $xml]);
  619. $this->Controller->request = $this->Controller->request
  620. ->withEnv('REQUEST_METHOD', 'POST')
  621. ->withEnv('CONTENT_TYPE', 'application/xml');
  622. $event = new Event('Controller.startup', $this->Controller);
  623. $this->RequestHandler->startup($event);
  624. $expected = [
  625. 'article' => [
  626. 'id' => 1,
  627. 'title' => 'first'
  628. ]
  629. ];
  630. $this->assertEquals($expected, $this->Controller->request->getData());
  631. }
  632. /**
  633. * Test that input xml is parsed
  634. *
  635. * @return void
  636. */
  637. public function testStartupConvertXmlIgnoreEntities()
  638. {
  639. $xml = <<<XML
  640. <?xml version="1.0" encoding="UTF-8"?>
  641. <!DOCTYPE item [
  642. <!ENTITY item "item">
  643. <!ENTITY item1 "&item;&item;&item;&item;&item;&item;">
  644. <!ENTITY item2 "&item1;&item1;&item1;&item1;&item1;&item1;&item1;&item1;&item1;">
  645. <!ENTITY item3 "&item2;&item2;&item2;&item2;&item2;&item2;&item2;&item2;&item2;">
  646. <!ENTITY item4 "&item3;&item3;&item3;&item3;&item3;&item3;&item3;&item3;&item3;">
  647. <!ENTITY item5 "&item4;&item4;&item4;&item4;&item4;&item4;&item4;&item4;&item4;">
  648. <!ENTITY item6 "&item5;&item5;&item5;&item5;&item5;&item5;&item5;&item5;&item5;">
  649. <!ENTITY item7 "&item6;&item6;&item6;&item6;&item6;&item6;&item6;&item6;&item6;">
  650. <!ENTITY item8 "&item7;&item7;&item7;&item7;&item7;&item7;&item7;&item7;&item7;">
  651. ]>
  652. <item>
  653. <description>&item8;</description>
  654. </item>
  655. XML;
  656. $this->Controller->request = new ServerRequest(['input' => $xml]);
  657. $this->Controller->request = $this->Controller->request
  658. ->withEnv('REQUEST_METHOD', 'POST')
  659. ->withEnv('CONTENT_TYPE', 'application/xml');
  660. $event = new Event('Controller.startup', $this->Controller);
  661. $this->RequestHandler->startup($event);
  662. $this->assertEquals([], $this->Controller->request->getData());
  663. }
  664. /**
  665. * Test mapping a new type and having startup process it.
  666. *
  667. * @group deprecated
  668. * @return void
  669. * @triggers Controller.startup $this->Controller
  670. */
  671. public function testStartupCustomTypeProcess()
  672. {
  673. $this->deprecated(function () {
  674. $this->Controller->request = new ServerRequest([
  675. 'input' => '"A","csv","string"',
  676. 'environment' => [
  677. 'REQUEST_METHOD' => 'POST',
  678. 'CONTENT_TYPE' => 'text/csv'
  679. ]
  680. ]);
  681. $this->RequestHandler->addInputType('csv', ['str_getcsv']);
  682. $event = new Event('Controller.startup', $this->Controller);
  683. $this->RequestHandler->startup($event);
  684. $expected = [
  685. 'A', 'csv', 'string'
  686. ];
  687. $this->assertEquals($expected, $this->Controller->request->getData());
  688. });
  689. }
  690. /**
  691. * Test that data isn't processed when parsed data already exists.
  692. *
  693. * @return void
  694. * @triggers Controller.startup $this->Controller
  695. */
  696. public function testStartupSkipDataProcess()
  697. {
  698. $this->Controller->request = new ServerRequest([
  699. 'environment' => [
  700. 'REQUEST_METHOD' => 'POST',
  701. 'CONTENT_TYPE' => 'application/json'
  702. ]
  703. ]);
  704. $event = new Event('Controller.startup', $this->Controller);
  705. $this->RequestHandler->startup($event);
  706. $this->assertEquals([], $this->Controller->request->getData());
  707. $stream = new Stream('php://memory', 'w');
  708. $stream->write('{"new": "data"}');
  709. $this->Controller->request = $this->Controller->request
  710. ->withBody($stream)
  711. ->withParsedBody(['old' => 'news']);
  712. $this->RequestHandler->startup($event);
  713. $this->assertEquals(['old' => 'news'], $this->Controller->request->getData());
  714. }
  715. /**
  716. * test beforeRedirect when disabled.
  717. *
  718. * @return void
  719. * @triggers Controller.startup $this->Controller
  720. */
  721. public function testBeforeRedirectDisabled()
  722. {
  723. static::setAppNamespace();
  724. Router::connect('/:controller/:action');
  725. $this->Controller->request = $this->Controller->request->withHeader('X-Requested-With', 'XMLHttpRequest');
  726. $event = new Event('Controller.startup', $this->Controller);
  727. $this->RequestHandler->initialize([]);
  728. $this->RequestHandler->setConfig('enableBeforeRedirect', false);
  729. $this->RequestHandler->startup($event);
  730. $this->assertNull($this->RequestHandler->beforeRedirect($event, '/posts/index', $this->Controller->response));
  731. }
  732. /**
  733. * testNonAjaxRedirect method
  734. *
  735. * @group deprecated
  736. * @return void
  737. * @triggers Controller.startup $this->Controller
  738. */
  739. public function testNonAjaxRedirect()
  740. {
  741. $this->deprecated(function () {
  742. $event = new Event('Controller.startup', $this->Controller);
  743. $this->RequestHandler->initialize([]);
  744. $this->RequestHandler->startup($event);
  745. $this->assertNull($this->RequestHandler->beforeRedirect($event, '/', $this->Controller->response));
  746. });
  747. }
  748. /**
  749. * test that redirects with ajax and no URL don't do anything.
  750. *
  751. * @group deprecated
  752. * @return void
  753. * @triggers Controller.startup $this->Controller
  754. */
  755. public function testAjaxRedirectWithNoUrl()
  756. {
  757. $this->deprecated(function () {
  758. $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
  759. $event = new Event('Controller.startup', $this->Controller);
  760. $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  761. $this->Controller->response->expects($this->never())
  762. ->method('body');
  763. $this->RequestHandler->initialize([]);
  764. $this->RequestHandler->startup($event);
  765. $this->assertNull($this->RequestHandler->beforeRedirect($event, null, $this->Controller->response));
  766. });
  767. }
  768. /**
  769. * testRenderAs method
  770. *
  771. * @return void
  772. */
  773. public function testRenderAs()
  774. {
  775. $this->RequestHandler->renderAs($this->Controller, 'rss');
  776. $this->Controller->viewBuilder()->templatePath('request_handler_test\\rss');
  777. $this->RequestHandler->renderAs($this->Controller, 'js');
  778. $this->assertEquals('request_handler_test' . DS . 'js', $this->Controller->viewBuilder()->templatePath());
  779. }
  780. /**
  781. * test that attachment headers work with renderAs
  782. *
  783. * @return void
  784. */
  785. public function testRenderAsWithAttachment()
  786. {
  787. $this->Controller->request = $this->request->withHeader('Accept', 'application/xml;q=1.0');
  788. $this->RequestHandler->renderAs($this->Controller, 'xml', ['attachment' => 'myfile.xml']);
  789. $this->assertEquals('Cake\View\XmlView', $this->Controller->viewClass);
  790. $this->assertEquals('application/xml', $this->Controller->response->getType());
  791. $this->assertEquals('UTF-8', $this->Controller->response->getCharset());
  792. $this->assertContains('myfile.xml', $this->Controller->response->getHeaderLine('Content-Disposition'));
  793. }
  794. /**
  795. * test that respondAs works as expected.
  796. *
  797. * @return void
  798. */
  799. public function testRespondAs()
  800. {
  801. $result = $this->RequestHandler->respondAs('json');
  802. $this->assertTrue($result);
  803. $this->assertEquals('application/json', $this->Controller->response->getType());
  804. $result = $this->RequestHandler->respondAs('text/xml');
  805. $this->assertTrue($result);
  806. $this->assertEquals('text/xml', $this->Controller->response->getType());
  807. }
  808. /**
  809. * test that attachment headers work with respondAs
  810. *
  811. * @return void
  812. */
  813. public function testRespondAsWithAttachment()
  814. {
  815. $result = $this->RequestHandler->respondAs('xml', ['attachment' => 'myfile.xml']);
  816. $this->assertTrue($result);
  817. $response = $this->Controller->response;
  818. $this->assertContains('myfile.xml', $response->getHeaderLine('Content-Disposition'));
  819. $this->assertContains('application/xml', $response->getType());
  820. }
  821. /**
  822. * test that calling renderAs() more than once continues to work.
  823. *
  824. * @link #6466
  825. * @return void
  826. */
  827. public function testRenderAsCalledTwice()
  828. {
  829. $this->Controller->getEventManager()->on('Controller.beforeRender', function (\Cake\Event\Event $e) {
  830. return $e->getSubject()->response;
  831. });
  832. $this->Controller->render();
  833. $this->RequestHandler->renderAs($this->Controller, 'print');
  834. $this->assertEquals('RequestHandlerTest' . DS . 'print', $this->Controller->viewBuilder()->templatePath());
  835. $this->assertEquals('print', $this->Controller->viewBuilder()->layoutPath());
  836. $this->RequestHandler->renderAs($this->Controller, 'js');
  837. $this->assertEquals('RequestHandlerTest' . DS . 'js', $this->Controller->viewBuilder()->templatePath());
  838. $this->assertEquals('js', $this->Controller->viewBuilder()->layoutPath());
  839. }
  840. /**
  841. * testRequestContentTypes method
  842. *
  843. * @return void
  844. */
  845. public function testRequestContentTypes()
  846. {
  847. $this->Controller->request = $this->request->withEnv('REQUEST_METHOD', 'GET');
  848. $this->assertNull($this->RequestHandler->requestedWith());
  849. $this->Controller->request = $this->request->withEnv('REQUEST_METHOD', 'POST')
  850. ->withEnv('CONTENT_TYPE', 'application/json');
  851. $this->assertEquals('json', $this->RequestHandler->requestedWith());
  852. $result = $this->RequestHandler->requestedWith(['json', 'xml']);
  853. $this->assertEquals('json', $result);
  854. $result = $this->RequestHandler->requestedWith(['rss', 'atom']);
  855. $this->assertFalse($result);
  856. $this->Controller->request = $this->request
  857. ->withEnv('REQUEST_METHOD', 'PATCH')
  858. ->withEnv('CONTENT_TYPE', 'application/json');
  859. $this->assertEquals('json', $this->RequestHandler->requestedWith());
  860. $this->Controller->request = $this->request
  861. ->withEnv('REQUEST_METHOD', 'DELETE')
  862. ->withEnv('CONTENT_TYPE', 'application/json');
  863. $this->assertEquals('json', $this->RequestHandler->requestedWith());
  864. $this->Controller->request = $this->request
  865. ->withEnv('REQUEST_METHOD', 'POST')
  866. ->withEnv('CONTENT_TYPE', 'application/json');
  867. $result = $this->RequestHandler->requestedWith(['json', 'xml']);
  868. $this->assertEquals('json', $result);
  869. $result = $this->RequestHandler->requestedWith(['rss', 'atom']);
  870. $this->assertFalse($result);
  871. $this->Controller->request = $this->request->withHeader(
  872. 'Accept',
  873. 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  874. );
  875. $this->assertTrue($this->RequestHandler->isXml());
  876. $this->assertFalse($this->RequestHandler->isAtom());
  877. $this->assertFalse($this->RequestHandler->isRSS());
  878. $this->Controller->request = $this->request->withHeader(
  879. 'Accept',
  880. 'application/atom+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  881. );
  882. $this->assertTrue($this->RequestHandler->isAtom());
  883. $this->assertFalse($this->RequestHandler->isRSS());
  884. $this->Controller->request = $this->request->withHeader(
  885. 'Accept',
  886. 'application/rss+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  887. );
  888. $this->assertFalse($this->RequestHandler->isAtom());
  889. $this->assertTrue($this->RequestHandler->isRSS());
  890. $this->assertFalse($this->RequestHandler->isWap());
  891. $this->Controller->request = $this->request->withHeader(
  892. 'Accept',
  893. 'text/vnd.wap.wml,text/html,text/plain,image/png,*/*'
  894. );
  895. $this->assertTrue($this->RequestHandler->isWap());
  896. }
  897. /**
  898. * testResponseContentType method
  899. *
  900. * @return void
  901. */
  902. public function testResponseContentType()
  903. {
  904. $this->assertEquals('html', $this->RequestHandler->responseType());
  905. $this->assertTrue($this->RequestHandler->respondAs('atom'));
  906. $this->assertEquals('atom', $this->RequestHandler->responseType());
  907. }
  908. /**
  909. * testMobileDeviceDetection method
  910. *
  911. * @return void
  912. */
  913. public function testMobileDeviceDetection()
  914. {
  915. $request = $this->getMockBuilder('Cake\Http\ServerRequest')
  916. ->setMethods(['is'])
  917. ->getMock();
  918. $request->expects($this->once())->method('is')
  919. ->with('mobile')
  920. ->will($this->returnValue(true));
  921. $this->Controller->request = $request;
  922. $this->assertTrue($this->RequestHandler->isMobile());
  923. }
  924. /**
  925. * test that map alias converts aliases to content types.
  926. *
  927. * @return void
  928. */
  929. public function testMapAlias()
  930. {
  931. $result = $this->RequestHandler->mapAlias('xml');
  932. $this->assertEquals('application/xml', $result);
  933. $result = $this->RequestHandler->mapAlias('text/html');
  934. $this->assertNull($result);
  935. $result = $this->RequestHandler->mapAlias('wap');
  936. $this->assertEquals('text/vnd.wap.wml', $result);
  937. $result = $this->RequestHandler->mapAlias(['xml', 'js', 'json']);
  938. $expected = ['application/xml', 'application/javascript', 'application/json'];
  939. $this->assertEquals($expected, $result);
  940. }
  941. /**
  942. * test accepts() on the component
  943. *
  944. * @return void
  945. */
  946. public function testAccepts()
  947. {
  948. $this->Controller->request = $this->request->withHeader(
  949. 'Accept',
  950. 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'
  951. );
  952. $this->assertTrue($this->RequestHandler->accepts(['js', 'xml', 'html']));
  953. $this->assertFalse($this->RequestHandler->accepts(['gif', 'jpeg', 'foo']));
  954. $this->Controller->request = $this->request->withHeader('Accept', '*/*;q=0.5');
  955. $this->assertFalse($this->RequestHandler->accepts('rss'));
  956. }
  957. /**
  958. * test accepts and prefers methods.
  959. *
  960. * @return void
  961. */
  962. public function testPrefers()
  963. {
  964. $this->Controller->request = $this->request->withHeader(
  965. 'Accept',
  966. 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  967. );
  968. $this->assertNotEquals('rss', $this->RequestHandler->prefers());
  969. $this->RequestHandler->ext = 'rss';
  970. $this->assertEquals('rss', $this->RequestHandler->prefers());
  971. $this->assertFalse($this->RequestHandler->prefers('xml'));
  972. $this->assertEquals('xml', $this->RequestHandler->prefers(['js', 'xml', 'xhtml']));
  973. $this->assertFalse($this->RequestHandler->prefers(['red', 'blue']));
  974. $this->assertEquals('xhtml', $this->RequestHandler->prefers(['js', 'json', 'xhtml']));
  975. $this->assertTrue($this->RequestHandler->prefers(['rss']), 'Should return true if input matches ext.');
  976. $this->assertFalse($this->RequestHandler->prefers(['html']), 'No match with ext, return false.');
  977. $this->_init();
  978. $this->Controller->request = $this->request->withHeader(
  979. 'Accept',
  980. 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'
  981. );
  982. $this->assertEquals('xml', $this->RequestHandler->prefers());
  983. $this->Controller->request = $this->request->withHeader('Accept', '*/*;q=0.5');
  984. $this->assertEquals('html', $this->RequestHandler->prefers());
  985. $this->assertFalse($this->RequestHandler->prefers('rss'));
  986. $this->Controller->request = $this->request->withEnv('HTTP_ACCEPT', null);
  987. $this->RequestHandler->ext = 'json';
  988. $this->assertFalse($this->RequestHandler->prefers('xml'));
  989. }
  990. /**
  991. * test that AJAX requests involving redirects trigger requestAction instead.
  992. *
  993. * @group deprecated
  994. * @return void
  995. * @triggers Controller.beforeRedirect $this->Controller
  996. */
  997. public function testAjaxRedirectAsRequestAction()
  998. {
  999. $this->deprecated(function () {
  1000. static::setAppNamespace();
  1001. Router::connect('/:controller/:action');
  1002. $event = new Event('Controller.beforeRedirect', $this->Controller);
  1003. $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
  1004. $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
  1005. ->setMethods(['is'])
  1006. ->getMock();
  1007. $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
  1008. ->setMethods(['_sendHeader', 'stop'])
  1009. ->getMock();
  1010. $this->Controller->request->expects($this->any())
  1011. ->method('is')
  1012. ->will($this->returnValue(true));
  1013. $response = $this->RequestHandler->beforeRedirect(
  1014. $event,
  1015. ['controller' => 'RequestHandlerTest', 'action' => 'destination'],
  1016. $this->Controller->response
  1017. );
  1018. $this->assertRegExp('/posts index/', $response->body(), 'RequestAction redirect failed.');
  1019. });
  1020. }
  1021. /**
  1022. * Test that AJAX requests involving redirects handle querystrings
  1023. *
  1024. * @group deprecated
  1025. * @return void
  1026. * @triggers Controller.beforeRedirect $this->Controller
  1027. */
  1028. public function testAjaxRedirectAsRequestActionWithQueryString()
  1029. {
  1030. $this->deprecated(function () {
  1031. static::setAppNamespace();
  1032. Router::connect('/:controller/:action');
  1033. $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
  1034. $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
  1035. ->setMethods(['is'])
  1036. ->getMock();
  1037. $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
  1038. ->setMethods(['_sendHeader', 'stop'])
  1039. ->getMock();
  1040. $this->Controller->request->expects($this->any())
  1041. ->method('is')
  1042. ->with('ajax')
  1043. ->will($this->returnValue(true));
  1044. $event = new Event('Controller.beforeRedirect', $this->Controller);
  1045. $response = $this->RequestHandler->beforeRedirect(
  1046. $event,
  1047. '/request_action/params_pass?a=b&x=y?ish',
  1048. $this->Controller->response
  1049. );
  1050. $data = json_decode($response, true);
  1051. $this->assertEquals('/request_action/params_pass', $data['here']);
  1052. $response = $this->RequestHandler->beforeRedirect(
  1053. $event,
  1054. '/request_action/query_pass?a=b&x=y?ish',
  1055. $this->Controller->response
  1056. );
  1057. $data = json_decode($response, true);
  1058. $this->assertEquals('y?ish', $data['x']);
  1059. });
  1060. }
  1061. /**
  1062. * Test that AJAX requests involving redirects handle cookie data
  1063. *
  1064. * @group deprecated
  1065. * @return void
  1066. * @triggers Controller.beforeRedirect $this->Controller
  1067. */
  1068. public function testAjaxRedirectAsRequestActionWithCookieData()
  1069. {
  1070. $this->deprecated(function () {
  1071. static::setAppNamespace();
  1072. Router::connect('/:controller/:action');
  1073. $event = new Event('Controller.beforeRedirect', $this->Controller);
  1074. $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
  1075. $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
  1076. ->setMethods(['is'])
  1077. ->getMock();
  1078. $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
  1079. ->setMethods(['_sendHeader', 'stop'])
  1080. ->getMock();
  1081. $this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true));
  1082. $cookies = [
  1083. 'foo' => 'bar'
  1084. ];
  1085. $this->Controller->request->cookies = $cookies;
  1086. $response = $this->RequestHandler->beforeRedirect(
  1087. $event,
  1088. '/request_action/cookie_pass',
  1089. $this->Controller->response
  1090. );
  1091. $data = json_decode($response, true);
  1092. $this->assertEquals($cookies, $data);
  1093. });
  1094. }
  1095. /**
  1096. * Tests that AJAX requests involving redirects don't let the status code bleed through.
  1097. *
  1098. * @group deprecated
  1099. * @return void
  1100. * @triggers Controller.beforeRedirect $this->Controller
  1101. */
  1102. public function testAjaxRedirectAsRequestActionStatusCode()
  1103. {
  1104. $this->deprecated(function () {
  1105. static::setAppNamespace();
  1106. Router::connect('/:controller/:action');
  1107. $event = new Event('Controller.beforeRedirect', $this->Controller);
  1108. $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
  1109. $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
  1110. ->setMethods(['is'])
  1111. ->getMock();
  1112. $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
  1113. ->setMethods(['_sendHeader', 'stop'])
  1114. ->getMock();
  1115. $this->Controller->response->statusCode(302);
  1116. $this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true));
  1117. $response = $this->RequestHandler->beforeRedirect(
  1118. $event,
  1119. ['controller' => 'RequestHandlerTest', 'action' => 'destination'],
  1120. $this->Controller->response
  1121. );
  1122. $this->assertRegExp('/posts index/', $response->body(), 'RequestAction redirect failed.');
  1123. $this->assertSame(200, $response->statusCode());
  1124. });
  1125. }
  1126. /**
  1127. * test that ajax requests involving redirects don't force no layout
  1128. * this would cause the ajax layout to not be rendered.
  1129. *
  1130. * @group deprecated
  1131. * @return void
  1132. * @triggers Controller.beforeRedirect $this->Controller
  1133. */
  1134. public function testAjaxRedirectAsRequestActionStillRenderingLayout()
  1135. {
  1136. $this->deprecated(function () {
  1137. static::setAppNamespace();
  1138. Router::connect('/:controller/:action');
  1139. $event = new Event('Controller.beforeRedirect', $this->Controller);
  1140. $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
  1141. $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
  1142. ->setMethods(['is'])
  1143. ->getMock();
  1144. $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
  1145. ->setMethods(['_sendHeader', 'stop'])
  1146. ->getMock();
  1147. $this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true));
  1148. $response = $this->RequestHandler->beforeRedirect(
  1149. $event,
  1150. ['controller' => 'RequestHandlerTest', 'action' => 'ajax2_layout'],
  1151. $this->Controller->response
  1152. );
  1153. $this->assertRegExp('/posts index/', $response->body(), 'RequestAction redirect failed.');
  1154. $this->assertRegExp('/Ajax!/', $response->body(), 'Layout was not rendered.');
  1155. });
  1156. }
  1157. /**
  1158. * test that the beforeRedirect callback properly converts
  1159. * array URLs into their correct string ones, and adds base => false so
  1160. * the correct URLs are generated.
  1161. *
  1162. * @group deprecated
  1163. * @return void
  1164. * @triggers Controller.beforeRender $this->Controller
  1165. */
  1166. public function testBeforeRedirectCallbackWithArrayUrl()
  1167. {
  1168. $this->deprecated(function () {
  1169. static::setAppNamespace();
  1170. Router::connect('/:controller/:action/*');
  1171. $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
  1172. $event = new Event('Controller.beforeRender', $this->Controller);
  1173. Router::setRequestInfo([
  1174. ['plugin' => null, 'controller' => 'accounts', 'action' => 'index', 'pass' => []],
  1175. ['base' => '', 'here' => '/accounts/', 'webroot' => '/']
  1176. ]);
  1177. $RequestHandler = new RequestHandlerComponent($this->Controller->components());
  1178. $this->Controller->request = new ServerRequest('posts/index');
  1179. ob_start();
  1180. $RequestHandler->beforeRedirect(
  1181. $event,
  1182. ['controller' => 'RequestHandlerTest', 'action' => 'param_method', 'first', 'second'],
  1183. $this->Controller->response
  1184. );
  1185. $result = ob_get_clean();
  1186. $this->assertEquals('one: first two: second', $result);
  1187. });
  1188. }
  1189. /**
  1190. * testAddInputTypeException method
  1191. *
  1192. * @group deprecated
  1193. * @return void
  1194. */
  1195. public function testAddInputTypeException()
  1196. {
  1197. $this->expectException(\Cake\Core\Exception\Exception::class);
  1198. $this->deprecated(function () {
  1199. $this->RequestHandler->addInputType('csv', ['I am not callable']);
  1200. });
  1201. }
  1202. /**
  1203. * Test checkNotModified method
  1204. *
  1205. * @return void
  1206. * @triggers Controller.beforeRender $this->Controller
  1207. */
  1208. public function testCheckNotModifiedByEtagStar()
  1209. {
  1210. $response = new Response();
  1211. $response = $response->withEtag('something')
  1212. ->withHeader('Content-Type', 'text/plain')
  1213. ->withStringBody('keeper');
  1214. $this->Controller->response = $response;
  1215. $this->Controller->request = $this->request->withHeader('If-None-Match', '*');
  1216. $event = new Event('Controller.beforeRender', $this->Controller);
  1217. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  1218. $this->assertFalse($requestHandler->beforeRender($event));
  1219. $this->assertEquals(304, $this->Controller->response->getStatusCode());
  1220. $this->assertEquals('', (string)$this->Controller->response->getBody());
  1221. $this->assertFalse($this->Controller->response->hasHeader('Content-Type'), 'header should not be removed.');
  1222. }
  1223. /**
  1224. * Test checkNotModified method
  1225. *
  1226. * @return void
  1227. * @triggers Controller.beforeRender
  1228. */
  1229. public function testCheckNotModifiedByEtagExact()
  1230. {
  1231. $response = new Response();
  1232. $response = $response->withEtag('something', true)
  1233. ->withHeader('Content-Type', 'text/plain')
  1234. ->withStringBody('keeper');
  1235. $this->Controller->response = $response;
  1236. $this->Controller->request = $this->request->withHeader('If-None-Match', 'W/"something", "other"');
  1237. $event = new Event('Controller.beforeRender', $this->Controller);
  1238. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  1239. $this->assertFalse($requestHandler->beforeRender($event));
  1240. $this->assertEquals(304, $this->Controller->response->getStatusCode());
  1241. $this->assertEquals('', (string)$this->Controller->response->getBody());
  1242. $this->assertFalse($this->Controller->response->hasHeader('Content-Type'));
  1243. }
  1244. /**
  1245. * Test checkNotModified method
  1246. *
  1247. * @return void
  1248. * @triggers Controller.beforeRender $this->Controller
  1249. */
  1250. public function testCheckNotModifiedByEtagAndTime()
  1251. {
  1252. $this->Controller->request = $this->request
  1253. ->withHeader('If-None-Match', 'W/"something", "other"')
  1254. ->withHeader('If-Modified-Since', '2012-01-01 00:00:00');
  1255. $response = new Response();
  1256. $response = $response->withEtag('something', true)
  1257. ->withHeader('Content-type', 'text/plain')
  1258. ->withStringBody('should be removed')
  1259. ->withModified('2012-01-01 00:00:00');
  1260. $this->Controller->response = $response;
  1261. $event = new Event('Controller.beforeRender', $this->Controller);
  1262. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  1263. $this->assertFalse($requestHandler->beforeRender($event));
  1264. $this->assertEquals(304, $this->Controller->response->getStatusCode());
  1265. $this->assertEquals('', (string)$this->Controller->response->getBody());
  1266. $this->assertFalse($this->Controller->response->hasHeader('Content-type'));
  1267. }
  1268. /**
  1269. * Test checkNotModified method
  1270. *
  1271. * @return void
  1272. * @triggers Controller.beforeRender $this->Controller
  1273. */
  1274. public function testCheckNotModifiedNoInfo()
  1275. {
  1276. $response = $this->getMockBuilder('Cake\Http\Response')
  1277. ->setMethods(['notModified', 'stop'])
  1278. ->getMock();
  1279. $response->expects($this->never())->method('notModified');
  1280. $this->Controller->response = $response;
  1281. $event = new Event('Controller.beforeRender', $this->Controller);
  1282. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  1283. $this->assertNull($requestHandler->beforeRender($event));
  1284. }
  1285. /**
  1286. * Test default options in construction
  1287. *
  1288. * @return void
  1289. */
  1290. public function testConstructDefaultOptions()
  1291. {
  1292. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  1293. $viewClass = $requestHandler->getConfig('viewClassMap');
  1294. $expected = [
  1295. 'json' => 'Json',
  1296. 'xml' => 'Xml',
  1297. 'ajax' => 'Ajax',
  1298. ];
  1299. $this->assertEquals($expected, $viewClass);
  1300. $inputs = $requestHandler->getConfig('inputTypeMap');
  1301. $this->assertArrayHasKey('json', $inputs);
  1302. $this->assertArrayHasKey('xml', $inputs);
  1303. }
  1304. /**
  1305. * Test options in constructor replace defaults
  1306. *
  1307. * @return void
  1308. */
  1309. public function testConstructReplaceOptions()
  1310. {
  1311. $requestHandler = new RequestHandlerComponent(
  1312. $this->Controller->components(),
  1313. [
  1314. 'viewClassMap' => ['json' => 'Json'],
  1315. 'inputTypeMap' => ['json' => ['json_decode', true]]
  1316. ]
  1317. );
  1318. $viewClass = $requestHandler->getConfig('viewClassMap');
  1319. $expected = [
  1320. 'json' => 'Json',
  1321. ];
  1322. $this->assertEquals($expected, $viewClass);
  1323. $inputs = $requestHandler->getConfig('inputTypeMap');
  1324. $this->assertArrayHasKey('json', $inputs);
  1325. $this->assertCount(1, $inputs);
  1326. }
  1327. /**
  1328. * test beforeRender() doesn't override response type set in controller action
  1329. *
  1330. * @return void
  1331. */
  1332. public function testBeforeRender()
  1333. {
  1334. $this->Controller->set_response_type();
  1335. $event = new Event('Controller.beforeRender', $this->Controller);
  1336. $this->RequestHandler->beforeRender($event);
  1337. $this->assertEquals('text/plain', $this->Controller->response->getType());
  1338. }
  1339. /**
  1340. * tests beforeRender automatically uses renderAs when a supported extension is found
  1341. *
  1342. * @return void
  1343. */
  1344. public function testBeforeRenderAutoRenderAs()
  1345. {
  1346. $this->Controller->setRequest($this->request->withParam('_ext', 'csv'));
  1347. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  1348. $event = new Event('Controller.beforeRender', $this->Controller);
  1349. $this->RequestHandler->beforeRender($event);
  1350. $this->assertEquals('text/csv', $this->Controller->response->getType());
  1351. }
  1352. }