RequestHandlerComponentTest.php 43 KB

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