RequestHandlerComponentTest.php 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 1.2.0
  13. * @license http://www.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\Controller\Controller;
  19. use Cake\Core\App;
  20. use Cake\Core\Configure;
  21. use Cake\Event\Event;
  22. use Cake\Network\Request;
  23. use Cake\Network\Response;
  24. use Cake\Routing\DispatcherFactory;
  25. use Cake\Routing\Router;
  26. use Cake\TestSuite\TestCase;
  27. use TestApp\Controller\RequestHandlerTestController;
  28. /**
  29. * RequestHandlerComponentTest class
  30. */
  31. class RequestHandlerComponentTest extends TestCase
  32. {
  33. /**
  34. * Controller property
  35. *
  36. * @var RequestHandlerTestController
  37. */
  38. public $Controller;
  39. /**
  40. * RequestHandler property
  41. *
  42. * @var RequestHandlerComponent
  43. */
  44. public $RequestHandler;
  45. /**
  46. * setUp method
  47. *
  48. * @return void
  49. */
  50. public function setUp()
  51. {
  52. parent::setUp();
  53. Configure::write('App.namespace', 'TestApp');
  54. DispatcherFactory::add('Routing');
  55. DispatcherFactory::add('ControllerFactory');
  56. $this->_init();
  57. }
  58. /**
  59. * init method
  60. *
  61. * @return void
  62. */
  63. protected function _init()
  64. {
  65. $request = new Request('controller_posts/index');
  66. $response = $this->getMock('Cake\Network\Response', ['_sendHeader', 'stop']);
  67. $this->Controller = new RequestHandlerTestController($request, $response);
  68. $this->RequestHandler = $this->Controller->components()->load('RequestHandler');
  69. $this->request = $request;
  70. Router::scope('/', function ($routes) {
  71. $routes->extensions('json');
  72. $routes->fallbacks('InflectedRoute');
  73. });
  74. }
  75. /**
  76. * tearDown method
  77. *
  78. * @return void
  79. */
  80. public function tearDown()
  81. {
  82. parent::tearDown();
  83. DispatcherFactory::clear();
  84. $this->_init();
  85. unset($this->RequestHandler, $this->Controller);
  86. }
  87. /**
  88. * Test that the constructor sets the config.
  89. *
  90. * @return void
  91. */
  92. public function testConstructorConfig()
  93. {
  94. $config = [
  95. 'viewClassMap' => ['json' => 'MyPlugin.MyJson']
  96. ];
  97. $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
  98. $collection = new ComponentRegistry($controller);
  99. $requestHandler = new RequestHandlerComponent($collection, $config);
  100. $this->assertEquals(['json' => 'MyPlugin.MyJson'], $requestHandler->config('viewClassMap'));
  101. }
  102. /**
  103. * testInitializeCallback method
  104. *
  105. * @return void
  106. */
  107. public function testInitializeCallback()
  108. {
  109. $this->assertNull($this->RequestHandler->ext);
  110. $this->Controller->request->params['_ext'] = 'rss';
  111. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  112. $this->assertEquals('rss', $this->RequestHandler->ext);
  113. }
  114. /**
  115. * test that a mapped Accept-type header will set $this->ext correctly.
  116. *
  117. * @return void
  118. */
  119. public function testInitializeContentTypeSettingExt()
  120. {
  121. $this->request->env('HTTP_ACCEPT', 'application/json');
  122. Router::extensions('json', false);
  123. $this->RequestHandler->ext = null;
  124. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  125. $this->assertEquals('json', $this->RequestHandler->ext);
  126. }
  127. /**
  128. * Test that RequestHandler sets $this->ext when jQuery sends its wonky-ish headers.
  129. *
  130. * @return void
  131. */
  132. public function testInitializeContentTypeWithjQueryAccept()
  133. {
  134. $this->request->env('HTTP_ACCEPT', 'application/json, application/javascript, */*; q=0.01');
  135. $this->request->env('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest');
  136. $this->RequestHandler->ext = null;
  137. Router::extensions('json', false);
  138. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  139. $this->assertEquals('json', $this->RequestHandler->ext);
  140. }
  141. /**
  142. * Test that RequestHandler does not set extension to csv for text/plain mimetype
  143. *
  144. * @return void
  145. */
  146. public function testInitializeContentTypeWithjQueryTextPlainAccept()
  147. {
  148. Router::extensions('csv', false);
  149. $this->request->env('HTTP_ACCEPT', 'text/plain, */*; q=0.01');
  150. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  151. $this->assertNull($this->RequestHandler->ext);
  152. }
  153. /**
  154. * Test that RequestHandler sets $this->ext when jQuery sends its wonky-ish headers
  155. * and the application is configured to handle multiple extensions
  156. *
  157. * @return void
  158. */
  159. public function testInitializeContentTypeWithjQueryAcceptAndMultiplesExtensions()
  160. {
  161. $this->request->env('HTTP_ACCEPT', 'application/json, application/javascript, */*; q=0.01');
  162. $this->RequestHandler->ext = null;
  163. Router::extensions(['rss', 'json'], false);
  164. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  165. $this->assertEquals('json', $this->RequestHandler->ext);
  166. }
  167. /**
  168. * Test that RequestHandler does not set $this->ext when multiple accepts are sent.
  169. *
  170. * @return void
  171. */
  172. public function testInitializeNoContentTypeWithSingleAccept()
  173. {
  174. $_SERVER['HTTP_ACCEPT'] = 'application/json, text/html, */*; q=0.01';
  175. $this->assertNull($this->RequestHandler->ext);
  176. Router::extensions('json', false);
  177. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  178. $this->assertNull($this->RequestHandler->ext);
  179. }
  180. /**
  181. * Test that ext is set to the first listed extension with multiple accepted
  182. * content types.
  183. * Having multiple types accepted with same weight, means the client lets the
  184. * server choose the returned content type.
  185. *
  186. * @return void
  187. */
  188. public function testInitializeNoContentTypeWithMultipleAcceptedTypes()
  189. {
  190. $this->request->env(
  191. 'HTTP_ACCEPT',
  192. 'application/json, application/javascript, application/xml, */*; q=0.01'
  193. );
  194. $this->RequestHandler->ext = null;
  195. Router::extensions(['xml', 'json'], false);
  196. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  197. $this->assertEquals('xml', $this->RequestHandler->ext);
  198. $this->RequestHandler->ext = null;
  199. Router::extensions(['json', 'xml'], false);
  200. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  201. $this->assertEquals('json', $this->RequestHandler->ext);
  202. }
  203. /**
  204. * Test that ext is set to type with highest weight
  205. *
  206. * @return void
  207. */
  208. public function testInitializeContentTypeWithMultipleAcceptedTypes()
  209. {
  210. $this->request->env(
  211. 'HTTP_ACCEPT',
  212. 'text/csv;q=1.0, application/json;q=0.8, application/xml;q=0.7'
  213. );
  214. $this->RequestHandler->ext = null;
  215. Router::extensions(['xml', 'json'], false);
  216. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  217. $this->assertEquals('json', $this->RequestHandler->ext);
  218. }
  219. /**
  220. * Test that ext is not set with confusing android accepts headers.
  221. *
  222. * @return void
  223. */
  224. public function testInitializeAmbiguousAndroidAccepts()
  225. {
  226. $this->request->env(
  227. 'HTTP_ACCEPT',
  228. 'application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'
  229. );
  230. $this->RequestHandler->ext = null;
  231. Router::extensions(['html', 'xml'], false);
  232. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  233. $this->assertNull($this->RequestHandler->ext);
  234. }
  235. /**
  236. * Test that the headers sent by firefox are not treated as XML requests.
  237. *
  238. * @return void
  239. */
  240. public function testInititalizeFirefoxHeaderNotXml()
  241. {
  242. $_SERVER['HTTP_ACCEPT'] = 'text/html,application/xhtml+xml,application/xml;image/png,image/jpeg,image/*;q=0.9,*/*;q=0.8';
  243. Router::extensions(['xml', 'json'], false);
  244. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  245. $this->assertNull($this->RequestHandler->ext);
  246. }
  247. /**
  248. * Test that a type mismatch doesn't incorrectly set the ext
  249. *
  250. * @return void
  251. */
  252. public function testInitializeContentTypeAndExtensionMismatch()
  253. {
  254. $this->assertNull($this->RequestHandler->ext);
  255. $extensions = Router::extensions();
  256. Router::extensions('xml', false);
  257. $this->Controller->request = $this->getMock('Cake\Network\Request', ['accepts']);
  258. $this->Controller->request->expects($this->any())
  259. ->method('accepts')
  260. ->will($this->returnValue(['application/json']));
  261. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  262. $this->assertNull($this->RequestHandler->ext);
  263. call_user_func_array(['Cake\Routing\Router', 'extensions'], [$extensions, false]);
  264. }
  265. /**
  266. * testViewClassMap method
  267. *
  268. * @return void
  269. */
  270. public function testViewClassMap()
  271. {
  272. $restore = error_reporting(E_ALL & ~E_USER_DEPRECATED);
  273. $this->RequestHandler->config(['viewClassMap' => ['json' => 'CustomJson']]);
  274. $this->RequestHandler->initialize([]);
  275. $result = $this->RequestHandler->viewClassMap();
  276. $expected = [
  277. 'json' => 'CustomJson',
  278. 'xml' => 'Xml',
  279. 'ajax' => 'Ajax'
  280. ];
  281. $this->assertEquals($expected, $result);
  282. $result = $this->RequestHandler->viewClassMap('xls', 'Excel.Excel');
  283. $expected = [
  284. 'json' => 'CustomJson',
  285. 'xml' => 'Xml',
  286. 'ajax' => 'Ajax',
  287. 'xls' => 'Excel.Excel'
  288. ];
  289. $this->assertEquals($expected, $result);
  290. $this->RequestHandler->renderAs($this->Controller, 'json');
  291. $this->assertEquals('TestApp\View\CustomJsonView', $this->Controller->viewClass);
  292. error_reporting($restore);
  293. }
  294. /**
  295. * Verify that isAjax is set on the request params for ajax requests
  296. *
  297. * @return void
  298. * @triggers Controller.startup $this->Controller
  299. */
  300. public function testIsAjaxParams()
  301. {
  302. $this->request->env('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest');
  303. $event = new Event('Controller.startup', $this->Controller);
  304. $this->RequestHandler->initialize([]);
  305. $this->Controller->beforeFilter($event);
  306. $this->RequestHandler->startup($event);
  307. $this->assertEquals(true, $this->Controller->request->params['isAjax']);
  308. }
  309. /**
  310. * testAutoAjaxLayout method
  311. *
  312. * @return void
  313. * @triggers Controller.startup $this->Controller
  314. */
  315. public function testAutoAjaxLayout()
  316. {
  317. $event = new Event('Controller.startup', $this->Controller);
  318. $this->request->env('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest');
  319. $this->RequestHandler->initialize([]);
  320. $this->RequestHandler->startup($event);
  321. $event = new Event('Controller.beforeRender', $this->Controller);
  322. $this->RequestHandler->beforeRender($event);
  323. $this->assertEquals($this->Controller->viewClass, 'Cake\View\AjaxView');
  324. $view = $this->Controller->createView();
  325. $this->assertEquals('ajax', $view->layout);
  326. $this->_init();
  327. $this->Controller->request->params['_ext'] = 'js';
  328. $this->RequestHandler->initialize([]);
  329. $this->RequestHandler->startup($event);
  330. $this->assertNotEquals($this->Controller->viewClass, 'Cake\View\AjaxView');
  331. }
  332. /**
  333. * test custom JsonView class is loaded and correct.
  334. *
  335. * @return void
  336. * @triggers Controller.startup $this->Controller
  337. */
  338. public function testJsonViewLoaded()
  339. {
  340. Router::extensions(['json', 'xml', 'ajax'], false);
  341. $this->Controller->request->params['_ext'] = 'json';
  342. $event = new Event('Controller.startup', $this->Controller);
  343. $this->RequestHandler->initialize([]);
  344. $this->RequestHandler->startup($event);
  345. $event = new Event('Controller.beforeRender', $this->Controller);
  346. $this->RequestHandler->beforeRender($event);
  347. $this->assertEquals('Cake\View\JsonView', $this->Controller->viewClass);
  348. $view = $this->Controller->createView();
  349. $this->assertEquals('json', $view->layoutPath);
  350. $this->assertEquals('json', $view->subDir);
  351. }
  352. /**
  353. * test custom XmlView class is loaded and correct.
  354. *
  355. * @return void
  356. * @triggers Controller.startup $this->Controller
  357. */
  358. public function testXmlViewLoaded()
  359. {
  360. Router::extensions(['json', 'xml', 'ajax'], false);
  361. $this->Controller->request->params['_ext'] = 'xml';
  362. $event = new Event('Controller.startup', $this->Controller);
  363. $this->RequestHandler->initialize([]);
  364. $this->RequestHandler->startup($event);
  365. $event = new Event('Controller.beforeRender', $this->Controller);
  366. $this->RequestHandler->beforeRender($event);
  367. $this->assertEquals('Cake\View\XmlView', $this->Controller->viewClass);
  368. $view = $this->Controller->createView();
  369. $this->assertEquals('xml', $view->layoutPath);
  370. $this->assertEquals('xml', $view->subDir);
  371. }
  372. /**
  373. * test custom AjaxView class is loaded and correct.
  374. *
  375. * @return void
  376. * @triggers Controller.startup $this->Controller
  377. */
  378. public function testAjaxViewLoaded()
  379. {
  380. Router::extensions(['json', 'xml', 'ajax'], false);
  381. $this->Controller->request->params['_ext'] = 'ajax';
  382. $event = new Event('Controller.startup', $this->Controller);
  383. $this->RequestHandler->initialize([]);
  384. $this->RequestHandler->startup($event);
  385. $event = new Event('Controller.beforeRender', $this->Controller);
  386. $this->RequestHandler->beforeRender($event);
  387. $this->assertEquals('Cake\View\AjaxView', $this->Controller->viewClass);
  388. $view = $this->Controller->createView();
  389. $this->assertEquals('ajax', $view->layout);
  390. }
  391. /**
  392. * test configured extension but no view class set.
  393. *
  394. * @return void
  395. * @triggers Controller.beforeRender $this->Controller
  396. */
  397. public function testNoViewClassExtension()
  398. {
  399. Router::extensions(['json', 'xml', 'ajax', 'csv'], false);
  400. $this->Controller->request->params['_ext'] = 'csv';
  401. $event = new Event('Controller.startup', $this->Controller);
  402. $this->RequestHandler->initialize([]);
  403. $this->RequestHandler->startup($event);
  404. $this->Controller->eventManager()->on('Controller.beforeRender', function () {
  405. return $this->Controller->response;
  406. });
  407. $this->Controller->render();
  408. $this->assertEquals('RequestHandlerTest' . DS . 'csv', $this->Controller->viewBuilder()->templatePath());
  409. $this->assertEquals('csv', $this->Controller->viewBuilder()->layoutPath());
  410. }
  411. /**
  412. * testStartupCallback method
  413. *
  414. * @return void
  415. * @triggers Controller.beforeRender $this->Controller
  416. */
  417. public function testStartupCallback()
  418. {
  419. $event = new Event('Controller.beforeRender', $this->Controller);
  420. $_SERVER['REQUEST_METHOD'] = 'PUT';
  421. $_SERVER['CONTENT_TYPE'] = 'application/xml';
  422. $this->Controller->request = $this->getMock('Cake\Network\Request', ['_readInput']);
  423. $this->RequestHandler->beforeRender($event);
  424. $this->assertTrue(is_array($this->Controller->request->data));
  425. $this->assertFalse(is_object($this->Controller->request->data));
  426. }
  427. /**
  428. * testStartupCallback with charset.
  429. *
  430. * @return void
  431. * @triggers Controller.startup $this->Controller
  432. */
  433. public function testStartupCallbackCharset()
  434. {
  435. $event = new Event('Controller.startup', $this->Controller);
  436. $_SERVER['REQUEST_METHOD'] = 'PUT';
  437. $_SERVER['CONTENT_TYPE'] = 'application/xml; charset=UTF-8';
  438. $this->Controller->request = $this->getMock('Cake\Network\Request', ['_readInput']);
  439. $this->RequestHandler->startup($event);
  440. $this->assertTrue(is_array($this->Controller->request->data));
  441. $this->assertFalse(is_object($this->Controller->request->data));
  442. }
  443. /**
  444. * Test that processing data results in an array.
  445. *
  446. * @return void
  447. * @triggers Controller.startup $this->Controller
  448. */
  449. public function testStartupProcessData()
  450. {
  451. $this->Controller->request = $this->getMock('Cake\Network\Request', ['_readInput']);
  452. $this->Controller->request->expects($this->at(0))
  453. ->method('_readInput')
  454. ->will($this->returnValue(''));
  455. $this->Controller->request->expects($this->at(1))
  456. ->method('_readInput')
  457. ->will($this->returnValue('"invalid"'));
  458. $this->Controller->request->expects($this->at(2))
  459. ->method('_readInput')
  460. ->will($this->returnValue('{"valid":true}'));
  461. $this->Controller->request->env('REQUEST_METHOD', 'POST');
  462. $this->Controller->request->env('CONTENT_TYPE', 'application/json');
  463. $event = new Event('Controller.startup', $this->Controller);
  464. $this->RequestHandler->startup($event);
  465. $this->assertEquals([], $this->Controller->request->data);
  466. $this->RequestHandler->startup($event);
  467. $this->assertEquals(['invalid'], $this->Controller->request->data);
  468. $this->RequestHandler->startup($event);
  469. $this->assertEquals(['valid' => true], $this->Controller->request->data);
  470. }
  471. /**
  472. * Test that file handles are ignored as XML data.
  473. *
  474. * @return void
  475. * @triggers Controller.startup $this->Controller
  476. */
  477. public function testStartupIgnoreFileAsXml()
  478. {
  479. $this->Controller->request = $this->getMock('Cake\Network\Request', ['_readInput']);
  480. $this->Controller->request->expects($this->any())
  481. ->method('_readInput')
  482. ->will($this->returnValue('/dev/random'));
  483. $this->Controller->request->env('REQUEST_METHOD', 'POST');
  484. $this->Controller->request->env('CONTENT_TYPE', 'application/xml');
  485. $event = new Event('Controller.startup', $this->Controller);
  486. $this->RequestHandler->startup($event);
  487. $this->assertEquals([], $this->Controller->request->data);
  488. }
  489. /**
  490. * Test mapping a new type and having startup process it.
  491. *
  492. * @return void
  493. * @triggers Controller.startup $this->Controller
  494. */
  495. public function testStartupCustomTypeProcess()
  496. {
  497. $restore = error_reporting(E_ALL & ~E_USER_DEPRECATED);
  498. $this->Controller->request = $this->getMock('Cake\Network\Request', ['_readInput']);
  499. $this->Controller->request->expects($this->once())
  500. ->method('_readInput')
  501. ->will($this->returnValue('"A","csv","string"'));
  502. $this->RequestHandler->addInputType('csv', ['str_getcsv']);
  503. $this->Controller->request->env('REQUEST_METHOD', 'POST');
  504. $this->Controller->request->env('CONTENT_TYPE', 'text/csv');
  505. $event = new Event('Controller.startup', $this->Controller);
  506. $this->RequestHandler->startup($event);
  507. $expected = [
  508. 'A', 'csv', 'string'
  509. ];
  510. $this->assertEquals($expected, $this->Controller->request->data);
  511. error_reporting($restore);
  512. }
  513. /**
  514. * testNonAjaxRedirect method
  515. *
  516. * @return void
  517. * @triggers Controller.startup $this->Controller
  518. */
  519. public function testNonAjaxRedirect()
  520. {
  521. $event = new Event('Controller.startup', $this->Controller);
  522. $this->RequestHandler->initialize([]);
  523. $this->RequestHandler->startup($event);
  524. $this->assertNull($this->RequestHandler->beforeRedirect($event, '/', $this->Controller->response));
  525. }
  526. /**
  527. * test that redirects with ajax and no URL don't do anything.
  528. *
  529. * @return void
  530. * @triggers Controller.startup $this->Controller
  531. */
  532. public function testAjaxRedirectWithNoUrl()
  533. {
  534. $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
  535. $event = new Event('Controller.startup', $this->Controller);
  536. $this->Controller->response = $this->getMock('Cake\Network\Response');
  537. $this->Controller->response->expects($this->never())
  538. ->method('body');
  539. $this->RequestHandler->initialize([]);
  540. $this->RequestHandler->startup($event);
  541. $this->assertNull($this->RequestHandler->beforeRedirect($event, null, $this->Controller->response));
  542. }
  543. /**
  544. * testRenderAs method
  545. *
  546. * @return void
  547. */
  548. public function testRenderAs()
  549. {
  550. $this->assertFalse(in_array('Rss', $this->Controller->helpers));
  551. $this->RequestHandler->renderAs($this->Controller, 'rss');
  552. $this->assertTrue(in_array('Rss', $this->Controller->helpers));
  553. $this->Controller->viewBuilder()->templatePath('request_handler_test\\rss');
  554. $this->RequestHandler->renderAs($this->Controller, 'js');
  555. $this->assertEquals('request_handler_test' . DS . 'js', $this->Controller->viewBuilder()->templatePath());
  556. }
  557. /**
  558. * test that attachment headers work with renderAs
  559. *
  560. * @return void
  561. */
  562. public function testRenderAsWithAttachment()
  563. {
  564. $this->RequestHandler->request = $this->getMock('Cake\Network\Request', ['parseAccept']);
  565. $this->RequestHandler->request->expects($this->any())
  566. ->method('parseAccept')
  567. ->will($this->returnValue(['1.0' => ['application/xml']]));
  568. $this->RequestHandler->response = $this->getMock('Cake\Network\Response', ['type', 'download', 'charset']);
  569. $this->RequestHandler->response->expects($this->at(0))
  570. ->method('type')
  571. ->with('application/xml');
  572. $this->RequestHandler->response->expects($this->at(1))
  573. ->method('charset')
  574. ->with('UTF-8');
  575. $this->RequestHandler->response->expects($this->at(2))
  576. ->method('download')
  577. ->with('myfile.xml');
  578. $this->RequestHandler->renderAs($this->Controller, 'xml', ['attachment' => 'myfile.xml']);
  579. $this->assertEquals('Cake\View\XmlView', $this->Controller->viewClass);
  580. }
  581. /**
  582. * test that respondAs works as expected.
  583. *
  584. * @return void
  585. */
  586. public function testRespondAs()
  587. {
  588. $this->RequestHandler->response = $this->getMock('Cake\Network\Response', ['type']);
  589. $this->RequestHandler->response->expects($this->at(0))->method('type')
  590. ->with('application/json');
  591. $this->RequestHandler->response->expects($this->at(1))->method('type')
  592. ->with('text/xml');
  593. $result = $this->RequestHandler->respondAs('json');
  594. $this->assertTrue($result);
  595. $result = $this->RequestHandler->respondAs('text/xml');
  596. $this->assertTrue($result);
  597. }
  598. /**
  599. * test that attachment headers work with respondAs
  600. *
  601. * @return void
  602. */
  603. public function testRespondAsWithAttachment()
  604. {
  605. $this->RequestHandler = $this->getMock(
  606. 'Cake\Controller\Component\RequestHandlerComponent',
  607. ['_header'],
  608. [$this->Controller->components()]
  609. );
  610. $this->RequestHandler->response = $this->getMock('Cake\Network\Response', ['type', 'download']);
  611. $this->RequestHandler->request = $this->getMock('Cake\Network\Request', ['parseAccept']);
  612. $this->RequestHandler->request->expects($this->once())
  613. ->method('parseAccept')
  614. ->will($this->returnValue(['1.0' => ['application/xml']]));
  615. $this->RequestHandler->response->expects($this->once())->method('download')
  616. ->with('myfile.xml');
  617. $this->RequestHandler->response->expects($this->once())->method('type')
  618. ->with('application/xml');
  619. $result = $this->RequestHandler->respondAs('xml', ['attachment' => 'myfile.xml']);
  620. $this->assertTrue($result);
  621. }
  622. /**
  623. * test that calling renderAs() more than once continues to work.
  624. *
  625. * @link #6466
  626. * @return void
  627. */
  628. public function testRenderAsCalledTwice()
  629. {
  630. $this->Controller->eventManager()->on('Controller.beforeRender', function (\Cake\Event\Event $e) {
  631. return $e->subject()->response;
  632. });
  633. $this->Controller->render();
  634. $this->RequestHandler->renderAs($this->Controller, 'print');
  635. $this->assertEquals('RequestHandlerTest' . DS . 'print', $this->Controller->viewBuilder()->templatePath());
  636. $this->assertEquals('print', $this->Controller->viewBuilder()->layoutPath());
  637. $this->RequestHandler->renderAs($this->Controller, 'js');
  638. $this->assertEquals('RequestHandlerTest' . DS . 'js', $this->Controller->viewBuilder()->templatePath());
  639. $this->assertEquals('js', $this->Controller->viewBuilder()->layoutPath());
  640. }
  641. /**
  642. * testRequestContentTypes method
  643. *
  644. * @return void
  645. */
  646. public function testRequestContentTypes()
  647. {
  648. $this->request->env('REQUEST_METHOD', 'GET');
  649. $this->assertNull($this->RequestHandler->requestedWith());
  650. $this->request->env('REQUEST_METHOD', 'POST');
  651. $this->request->env('CONTENT_TYPE', 'application/json');
  652. $this->assertEquals('json', $this->RequestHandler->requestedWith());
  653. $result = $this->RequestHandler->requestedWith(['json', 'xml']);
  654. $this->assertEquals('json', $result);
  655. $result = $this->RequestHandler->requestedWith(['rss', 'atom']);
  656. $this->assertFalse($result);
  657. $this->request->env('REQUEST_METHOD', 'PATCH');
  658. $this->assertEquals('json', $this->RequestHandler->requestedWith());
  659. $this->request->env('REQUEST_METHOD', 'DELETE');
  660. $this->assertEquals('json', $this->RequestHandler->requestedWith());
  661. $this->request->env('REQUEST_METHOD', 'POST');
  662. $this->request->env('CONTENT_TYPE', '');
  663. $this->request->env('HTTP_CONTENT_TYPE', 'application/json');
  664. $result = $this->RequestHandler->requestedWith(['json', 'xml']);
  665. $this->assertEquals('json', $result);
  666. $result = $this->RequestHandler->requestedWith(['rss', 'atom']);
  667. $this->assertFalse($result);
  668. $this->request->env('HTTP_ACCEPT', 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*');
  669. $this->assertTrue($this->RequestHandler->isXml());
  670. $this->assertFalse($this->RequestHandler->isAtom());
  671. $this->assertFalse($this->RequestHandler->isRSS());
  672. $this->request->env('HTTP_ACCEPT', 'application/atom+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*');
  673. $this->assertTrue($this->RequestHandler->isAtom());
  674. $this->assertFalse($this->RequestHandler->isRSS());
  675. $this->request->env('HTTP_ACCEPT', 'application/rss+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*');
  676. $this->assertFalse($this->RequestHandler->isAtom());
  677. $this->assertTrue($this->RequestHandler->isRSS());
  678. $this->assertFalse($this->RequestHandler->isWap());
  679. $this->request->env('HTTP_ACCEPT', 'text/vnd.wap.wml,text/html,text/plain,image/png,*/*');
  680. $this->assertTrue($this->RequestHandler->isWap());
  681. }
  682. /**
  683. * testResponseContentType method
  684. *
  685. * @return void
  686. */
  687. public function testResponseContentType()
  688. {
  689. $this->assertEquals('html', $this->RequestHandler->responseType());
  690. $this->assertTrue($this->RequestHandler->respondAs('atom'));
  691. $this->assertEquals('atom', $this->RequestHandler->responseType());
  692. }
  693. /**
  694. * testMobileDeviceDetection method
  695. *
  696. * @return void
  697. */
  698. public function testMobileDeviceDetection()
  699. {
  700. $request = $this->getMock('Cake\Network\Request', ['is']);
  701. $request->expects($this->once())->method('is')
  702. ->with('mobile')
  703. ->will($this->returnValue(true));
  704. $this->RequestHandler->request = $request;
  705. $this->assertTrue($this->RequestHandler->isMobile());
  706. }
  707. /**
  708. * test that map alias converts aliases to content types.
  709. *
  710. * @return void
  711. */
  712. public function testMapAlias()
  713. {
  714. $result = $this->RequestHandler->mapAlias('xml');
  715. $this->assertEquals('application/xml', $result);
  716. $result = $this->RequestHandler->mapAlias('text/html');
  717. $this->assertNull($result);
  718. $result = $this->RequestHandler->mapAlias('wap');
  719. $this->assertEquals('text/vnd.wap.wml', $result);
  720. $result = $this->RequestHandler->mapAlias(['xml', 'js', 'json']);
  721. $expected = ['application/xml', 'application/javascript', 'application/json'];
  722. $this->assertEquals($expected, $result);
  723. }
  724. /**
  725. * test accepts() on the component
  726. *
  727. * @return void
  728. */
  729. public function testAccepts()
  730. {
  731. $this->request->env('HTTP_ACCEPT', 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5');
  732. $this->assertTrue($this->RequestHandler->accepts(['js', 'xml', 'html']));
  733. $this->assertFalse($this->RequestHandler->accepts(['gif', 'jpeg', 'foo']));
  734. $this->request->env('HTTP_ACCEPT', '*/*;q=0.5');
  735. $this->assertFalse($this->RequestHandler->accepts('rss'));
  736. }
  737. /**
  738. * test accepts and prefers methods.
  739. *
  740. * @return void
  741. */
  742. public function testPrefers()
  743. {
  744. $this->request->env(
  745. 'HTTP_ACCEPT',
  746. 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  747. );
  748. $this->assertNotEquals('rss', $this->RequestHandler->prefers());
  749. $this->RequestHandler->ext = 'rss';
  750. $this->assertEquals('rss', $this->RequestHandler->prefers());
  751. $this->assertFalse($this->RequestHandler->prefers('xml'));
  752. $this->assertEquals('xml', $this->RequestHandler->prefers(['js', 'xml', 'xhtml']));
  753. $this->assertFalse($this->RequestHandler->prefers(['red', 'blue']));
  754. $this->assertEquals('xhtml', $this->RequestHandler->prefers(['js', 'json', 'xhtml']));
  755. $this->assertTrue($this->RequestHandler->prefers(['rss']), 'Should return true if input matches ext.');
  756. $this->assertFalse($this->RequestHandler->prefers(['html']), 'No match with ext, return false.');
  757. $this->_init();
  758. $this->request->env(
  759. 'HTTP_ACCEPT',
  760. 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'
  761. );
  762. $this->assertEquals('xml', $this->RequestHandler->prefers());
  763. $this->request->env('HTTP_ACCEPT', '*/*;q=0.5');
  764. $this->assertEquals('html', $this->RequestHandler->prefers());
  765. $this->assertFalse($this->RequestHandler->prefers('rss'));
  766. }
  767. /**
  768. * test that AJAX requests involving redirects trigger requestAction instead.
  769. *
  770. * @return void
  771. * @triggers Controller.beforeRedirect $this->Controller
  772. */
  773. public function testAjaxRedirectAsRequestAction()
  774. {
  775. Configure::write('App.namespace', 'TestApp');
  776. Router::connect('/:controller/:action');
  777. $event = new Event('Controller.beforeRedirect', $this->Controller);
  778. $this->Controller->RequestHandler = new RequestHandlerComponent($this->Controller->components());
  779. $this->Controller->request = $this->getMock('Cake\Network\Request', ['is']);
  780. $this->Controller->response = $this->getMock('Cake\Network\Response', ['_sendHeader', 'stop']);
  781. $this->Controller->RequestHandler->request = $this->Controller->request;
  782. $this->Controller->RequestHandler->response = $this->Controller->response;
  783. $this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true));
  784. $response = $this->Controller->RequestHandler->beforeRedirect(
  785. $event,
  786. ['controller' => 'RequestHandlerTest', 'action' => 'destination'],
  787. $this->Controller->response
  788. );
  789. $this->assertRegExp('/posts index/', $response->body(), 'RequestAction redirect failed.');
  790. }
  791. /**
  792. * Tests that AJAX requests involving redirects don't let the status code bleed through.
  793. *
  794. * @return void
  795. * @triggers Controller.beforeRedirect $this->Controller
  796. */
  797. public function testAjaxRedirectAsRequestActionStatusCode()
  798. {
  799. Configure::write('App.namespace', 'TestApp');
  800. Router::connect('/:controller/:action');
  801. $event = new Event('Controller.beforeRedirect', $this->Controller);
  802. $this->Controller->RequestHandler = new RequestHandlerComponent($this->Controller->components());
  803. $this->Controller->request = $this->getMock('Cake\Network\Request', ['is']);
  804. $this->Controller->response = $this->getMock('Cake\Network\Response', ['_sendHeader', 'stop']);
  805. $this->Controller->response->statusCode(302);
  806. $this->Controller->RequestHandler->request = $this->Controller->request;
  807. $this->Controller->RequestHandler->response = $this->Controller->response;
  808. $this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true));
  809. $response = $this->Controller->RequestHandler->beforeRedirect(
  810. $event,
  811. ['controller' => 'RequestHandlerTest', 'action' => 'destination'],
  812. $this->Controller->response
  813. );
  814. $this->assertRegExp('/posts index/', $response->body(), 'RequestAction redirect failed.');
  815. $this->assertSame(200, $response->statusCode());
  816. }
  817. /**
  818. * test that ajax requests involving redirects don't force no layout
  819. * this would cause the ajax layout to not be rendered.
  820. *
  821. * @return void
  822. * @triggers Controller.beforeRedirect $this->Controller
  823. */
  824. public function testAjaxRedirectAsRequestActionStillRenderingLayout()
  825. {
  826. Configure::write('App.namespace', 'TestApp');
  827. Router::connect('/:controller/:action');
  828. $event = new Event('Controller.beforeRedirect', $this->Controller);
  829. $this->Controller->RequestHandler = new RequestHandlerComponent($this->Controller->components());
  830. $this->Controller->request = $this->getMock('Cake\Network\Request', ['is']);
  831. $this->Controller->response = $this->getMock('Cake\Network\Response', ['_sendHeader', 'stop']);
  832. $this->Controller->RequestHandler->request = $this->Controller->request;
  833. $this->Controller->RequestHandler->response = $this->Controller->response;
  834. $this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true));
  835. $response = $this->Controller->RequestHandler->beforeRedirect(
  836. $event,
  837. ['controller' => 'RequestHandlerTest', 'action' => 'ajax2_layout'],
  838. $this->Controller->response
  839. );
  840. $this->assertRegExp('/posts index/', $response->body(), 'RequestAction redirect failed.');
  841. $this->assertRegExp('/Ajax!/', $response->body(), 'Layout was not rendered.');
  842. }
  843. /**
  844. * test that the beforeRedirect callback properly converts
  845. * array URLs into their correct string ones, and adds base => false so
  846. * the correct URLs are generated.
  847. *
  848. * @link https://cakephp.lighthouseapp.com/projects/42648-cakephp-1x/tickets/276
  849. * @return void
  850. * @triggers Controller.beforeRender $this->Controller
  851. */
  852. public function testBeforeRedirectCallbackWithArrayUrl()
  853. {
  854. Configure::write('App.namespace', 'TestApp');
  855. Router::connect('/:controller/:action/*');
  856. $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
  857. $event = new Event('Controller.beforeRender', $this->Controller);
  858. Router::setRequestInfo([
  859. ['plugin' => null, 'controller' => 'accounts', 'action' => 'index', 'pass' => []],
  860. ['base' => '', 'here' => '/accounts/', 'webroot' => '/']
  861. ]);
  862. $RequestHandler = new RequestHandlerComponent($this->Controller->components());
  863. $RequestHandler->request = new Request('posts/index');
  864. $RequestHandler->response = $this->Controller->response;
  865. ob_start();
  866. $RequestHandler->beforeRedirect(
  867. $event,
  868. ['controller' => 'RequestHandlerTest', 'action' => 'param_method', 'first', 'second'],
  869. $this->Controller->response
  870. );
  871. $result = ob_get_clean();
  872. $this->assertEquals('one: first two: second', $result);
  873. }
  874. /**
  875. * testAddInputTypeException method
  876. *
  877. * @expectedException \Cake\Core\Exception\Exception
  878. * @return void
  879. */
  880. public function testAddInputTypeException()
  881. {
  882. $restore = error_reporting(E_ALL & ~E_USER_DEPRECATED);
  883. $this->RequestHandler->addInputType('csv', ['I am not callable']);
  884. error_reporting($restore);
  885. }
  886. /**
  887. * Test checkNotModified method
  888. *
  889. * @return void
  890. * @triggers Controller.beforeRender $this->Controller
  891. */
  892. public function testCheckNotModifiedByEtagStar()
  893. {
  894. $_SERVER['HTTP_IF_NONE_MATCH'] = '*';
  895. $event = new Event('Controller.beforeRender', $this->Controller);
  896. $RequestHandler = new RequestHandlerComponent($this->Controller->components());
  897. $RequestHandler->response = $this->getMock('Cake\Network\Response', ['notModified', 'stop']);
  898. $RequestHandler->response->etag('something');
  899. $RequestHandler->response->expects($this->once())->method('notModified');
  900. $this->assertFalse($RequestHandler->beforeRender($event));
  901. }
  902. /**
  903. * Test checkNotModified method
  904. *
  905. * @return void
  906. * @triggers Controller.beforeRender
  907. */
  908. public function testCheckNotModifiedByEtagExact()
  909. {
  910. $_SERVER['HTTP_IF_NONE_MATCH'] = 'W/"something", "other"';
  911. $event = new Event('Controller.beforeRender');
  912. $RequestHandler = new RequestHandlerComponent($this->Controller->components());
  913. $RequestHandler->response = $this->getMock('Cake\Network\Response', ['notModified', 'stop']);
  914. $RequestHandler->response->etag('something', true);
  915. $RequestHandler->response->expects($this->once())->method('notModified');
  916. $this->assertFalse($RequestHandler->beforeRender($event));
  917. }
  918. /**
  919. * Test checkNotModified method
  920. *
  921. * @return void
  922. * @triggers Controller.beforeRender $this->Controller
  923. */
  924. public function testCheckNotModifiedByEtagAndTime()
  925. {
  926. $_SERVER['HTTP_IF_NONE_MATCH'] = 'W/"something", "other"';
  927. $_SERVER['HTTP_IF_MODIFIED_SINCE'] = '2012-01-01 00:00:00';
  928. $event = new Event('Controller.beforeRender', $this->Controller);
  929. $RequestHandler = new RequestHandlerComponent($this->Controller->components());
  930. $RequestHandler->response = $this->getMock('Cake\Network\Response', ['notModified', 'stop']);
  931. $RequestHandler->response->etag('something', true);
  932. $RequestHandler->response->modified('2012-01-01 00:00:00');
  933. $RequestHandler->response->expects($this->once())->method('notModified');
  934. $this->assertFalse($RequestHandler->beforeRender($event));
  935. }
  936. /**
  937. * Test checkNotModified method
  938. *
  939. * @return void
  940. * @triggers Controller.beforeRender $this->Controller
  941. */
  942. public function testCheckNotModifiedNoInfo()
  943. {
  944. $event = new Event('Controller.beforeRender', $this->Controller);
  945. $RequestHandler = new RequestHandlerComponent($this->Controller->components());
  946. $RequestHandler->response = $this->getMock('Cake\Network\Response', ['notModified', 'stop']);
  947. $RequestHandler->response->expects($this->never())->method('notModified');
  948. $this->assertNull($RequestHandler->beforeRender($event, '', $RequestHandler->response));
  949. }
  950. /**
  951. * Test default options in construction
  952. *
  953. * @return void
  954. */
  955. public function testConstructDefaultOptions()
  956. {
  957. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  958. $viewClass = $requestHandler->config('viewClassMap');
  959. $expected = [
  960. 'json' => 'Json',
  961. 'xml' => 'Xml',
  962. 'ajax' => 'Ajax',
  963. ];
  964. $this->assertEquals($expected, $viewClass);
  965. $inputs = $requestHandler->config('inputTypeMap');
  966. $this->assertArrayHasKey('json', $inputs);
  967. $this->assertArrayHasKey('xml', $inputs);
  968. }
  969. /**
  970. * Test options in constructor replace defaults
  971. *
  972. * @return void
  973. */
  974. public function testConstructReplaceOptions()
  975. {
  976. $requestHandler = new RequestHandlerComponent(
  977. $this->Controller->components(),
  978. [
  979. 'viewClassMap' => ['json' => 'Json'],
  980. 'inputTypeMap' => ['json' => ['json_decode', true]]
  981. ]
  982. );
  983. $viewClass = $requestHandler->config('viewClassMap');
  984. $expected = [
  985. 'json' => 'Json',
  986. ];
  987. $this->assertEquals($expected, $viewClass);
  988. $inputs = $requestHandler->config('inputTypeMap');
  989. $this->assertArrayHasKey('json', $inputs);
  990. $this->assertCount(1, $inputs);
  991. }
  992. }