RequestHandlerComponentTest.php 54 KB

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