RequestHandlerComponentTest.php 52 KB

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