RequestHandlerComponentTest.php 52 KB

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