RequestHandlerComponentTest.php 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527
  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\RouteBuilder;
  23. use Cake\Routing\Router;
  24. use Cake\TestSuite\TestCase;
  25. use Cake\View\AjaxView;
  26. use Cake\View\JsonView;
  27. use Cake\View\XmlView;
  28. use TestApp\Controller\RequestHandlerTestController;
  29. use Zend\Diactoros\Stream;
  30. /**
  31. * RequestHandlerComponentTest class
  32. */
  33. class RequestHandlerComponentTest extends TestCase
  34. {
  35. /**
  36. * @var RequestHandlerTestController
  37. */
  38. public $Controller;
  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 (RouteBuilder $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. $result = $this->RequestHandler->viewClassMap();
  344. $expected = [
  345. 'json' => 'CustomJson',
  346. 'xml' => 'Xml',
  347. 'ajax' => 'Ajax'
  348. ];
  349. $this->assertEquals($expected, $result);
  350. $result = $this->RequestHandler->viewClassMap('xls', 'Excel.Excel');
  351. $expected = [
  352. 'json' => 'CustomJson',
  353. 'xml' => 'Xml',
  354. 'ajax' => 'Ajax',
  355. 'xls' => 'Excel.Excel'
  356. ];
  357. $this->assertEquals($expected, $result);
  358. $this->RequestHandler->renderAs($this->Controller, 'json');
  359. $this->assertEquals('TestApp\View\CustomJsonView', $this->Controller->viewBuilder()->getClassName());
  360. });
  361. }
  362. /**
  363. * Verify that isAjax is set on the request params for ajax requests
  364. *
  365. * @return void
  366. * @triggers Controller.startup $this->Controller
  367. */
  368. public function testIsAjaxParams()
  369. {
  370. $this->Controller->request = $this->request->withHeader('X-Requested-With', 'XMLHttpRequest');
  371. $event = new Event('Controller.startup', $this->Controller);
  372. $this->Controller->beforeFilter($event);
  373. $this->RequestHandler->startup($event);
  374. $this->assertTrue($this->Controller->request->getParam('isAjax'));
  375. }
  376. /**
  377. * testAutoAjaxLayout method
  378. *
  379. * @return void
  380. * @triggers Controller.startup $this->Controller
  381. */
  382. public function testAutoAjaxLayout()
  383. {
  384. $event = new Event('Controller.startup', $this->Controller);
  385. $this->Controller->request = $this->request->withHeader('X-Requested-With', 'XMLHttpRequest');
  386. $this->RequestHandler->startup($event);
  387. $event = new Event('Controller.beforeRender', $this->Controller);
  388. $this->RequestHandler->beforeRender($event);
  389. $view = $this->Controller->createView();
  390. $this->assertInstanceOf(AjaxView::class, $view);
  391. $this->assertEquals('ajax', $view->getLayout());
  392. $this->_init();
  393. $this->Controller->request = $this->Controller->request->withParam('_ext', 'js');
  394. $this->RequestHandler->startup($event);
  395. $this->assertNotEquals(AjaxView::class, $this->Controller->viewBuilder()->getClassName());
  396. }
  397. /**
  398. * test custom JsonView class is loaded and correct.
  399. *
  400. * @return void
  401. * @triggers Controller.startup $this->Controller
  402. */
  403. public function testJsonViewLoaded()
  404. {
  405. Router::extensions(['json', 'xml', 'ajax'], false);
  406. $this->Controller->request = $this->Controller->request->withParam('_ext', 'json');
  407. $event = new Event('Controller.startup', $this->Controller);
  408. $this->RequestHandler->startup($event);
  409. $event = new Event('Controller.beforeRender', $this->Controller);
  410. $this->RequestHandler->beforeRender($event);
  411. $view = $this->Controller->createView();
  412. $this->assertInstanceOf(JsonView::class, $view);
  413. $this->assertEquals('json', $view->getLayoutPath());
  414. $this->assertEquals('json', $view->getSubDir());
  415. }
  416. /**
  417. * test custom XmlView class is loaded and correct.
  418. *
  419. * @return void
  420. * @triggers Controller.startup $this->Controller
  421. */
  422. public function testXmlViewLoaded()
  423. {
  424. Router::extensions(['json', 'xml', 'ajax'], false);
  425. $this->Controller->request = $this->Controller->request->withParam('_ext', 'xml');
  426. $event = new Event('Controller.startup', $this->Controller);
  427. $this->RequestHandler->startup($event);
  428. $event = new Event('Controller.beforeRender', $this->Controller);
  429. $this->RequestHandler->beforeRender($event);
  430. $view = $this->Controller->createView();
  431. $this->assertInstanceOf(XmlView::class, $view);
  432. $this->assertEquals('xml', $view->getLayoutPath());
  433. $this->assertEquals('xml', $view->getSubDir());
  434. }
  435. /**
  436. * test custom AjaxView class is loaded and correct.
  437. *
  438. * @return void
  439. * @triggers Controller.startup $this->Controller
  440. */
  441. public function testAjaxViewLoaded()
  442. {
  443. Router::extensions(['json', 'xml', 'ajax'], false);
  444. $this->Controller->request = $this->Controller->request->withParam('_ext', 'ajax');
  445. $event = new Event('Controller.startup', $this->Controller);
  446. $this->RequestHandler->startup($event);
  447. $event = new Event('Controller.beforeRender', $this->Controller);
  448. $this->RequestHandler->beforeRender($event);
  449. $view = $this->Controller->createView();
  450. $this->assertInstanceOf(AjaxView::class, $view);
  451. $this->assertEquals('ajax', $view->getLayout());
  452. }
  453. /**
  454. * test configured extension but no view class set.
  455. *
  456. * @return void
  457. * @triggers Controller.beforeRender $this->Controller
  458. */
  459. public function testNoViewClassExtension()
  460. {
  461. Router::extensions(['json', 'xml', 'ajax', 'csv'], false);
  462. $this->Controller->request = $this->Controller->request->withParam('_ext', 'csv');
  463. $event = new Event('Controller.startup', $this->Controller);
  464. $this->RequestHandler->startup($event);
  465. $this->Controller->getEventManager()->on('Controller.beforeRender', function () {
  466. return $this->Controller->response;
  467. });
  468. $this->Controller->render();
  469. $this->assertEquals('RequestHandlerTest' . DS . 'csv', $this->Controller->viewBuilder()->getTemplatePath());
  470. $this->assertEquals('csv', $this->Controller->viewBuilder()->getLayoutPath());
  471. }
  472. /**
  473. * Tests that configured extensions that have no configured mimetype do not silently fallback to HTML.
  474. *
  475. * @return void
  476. * @expectedException \Cake\Http\Exception\NotFoundException
  477. * @expectedExceptionMessage Invoked extension not recognized/configured: foo
  478. */
  479. public function testUnrecognizedExtensionFailure()
  480. {
  481. Router::extensions(['json', 'foo'], false);
  482. $this->Controller->setRequest($this->Controller->getRequest()->withParam('_ext', 'foo'));
  483. $event = new Event('Controller.startup', $this->Controller);
  484. $this->RequestHandler->startup($event);
  485. $this->Controller->getEventManager()->on('Controller.beforeRender', function () {
  486. return $this->Controller->getResponse();
  487. });
  488. $this->Controller->render();
  489. $this->assertEquals('RequestHandlerTest' . DS . 'csv', $this->Controller->viewBuilder()->getTemplatePath());
  490. }
  491. /**
  492. * testStartupCallback method
  493. *
  494. * @return void
  495. * @triggers Controller.beforeRender $this->Controller
  496. */
  497. public function testStartupCallback()
  498. {
  499. $event = new Event('Controller.beforeRender', $this->Controller);
  500. $_SERVER['REQUEST_METHOD'] = 'PUT';
  501. $_SERVER['CONTENT_TYPE'] = 'application/xml';
  502. $this->Controller->request = new ServerRequest();
  503. $this->RequestHandler->beforeRender($event);
  504. $this->assertInternalType('array', $this->Controller->request->getData());
  505. $this->assertNotInternalType('object', $this->Controller->request->getData());
  506. }
  507. /**
  508. * testStartupCallback with charset.
  509. *
  510. * @return void
  511. * @triggers Controller.startup $this->Controller
  512. */
  513. public function testStartupCallbackCharset()
  514. {
  515. $event = new Event('Controller.startup', $this->Controller);
  516. $_SERVER['REQUEST_METHOD'] = 'PUT';
  517. $_SERVER['CONTENT_TYPE'] = 'application/xml; charset=UTF-8';
  518. $this->Controller->request = new ServerRequest();
  519. $this->RequestHandler->startup($event);
  520. $this->assertInternalType('array', $this->Controller->request->getData());
  521. $this->assertNotInternalType('object', $this->Controller->request->getData());
  522. }
  523. /**
  524. * Test that processing data results in an array.
  525. *
  526. * @return void
  527. * @triggers Controller.startup $this->Controller
  528. */
  529. public function testStartupProcessDataInvalid()
  530. {
  531. $this->Controller->request = new ServerRequest([
  532. 'environment' => [
  533. 'REQUEST_METHOD' => 'POST',
  534. 'CONTENT_TYPE' => 'application/json'
  535. ]
  536. ]);
  537. $event = new Event('Controller.startup', $this->Controller);
  538. $this->RequestHandler->startup($event);
  539. $this->assertEquals([], $this->Controller->request->getData());
  540. $stream = new Stream('php://memory', 'w');
  541. $stream->write('"invalid"');
  542. $this->Controller->request = $this->Controller->request->withBody($stream);
  543. $this->RequestHandler->startup($event);
  544. $this->assertEquals(['invalid'], $this->Controller->request->getData());
  545. }
  546. /**
  547. * Test that processing data results in an array.
  548. *
  549. * @return void
  550. * @triggers Controller.startup $this->Controller
  551. */
  552. public function testStartupProcessData()
  553. {
  554. $this->Controller->request = new ServerRequest([
  555. 'environment' => [
  556. 'REQUEST_METHOD' => 'POST',
  557. 'CONTENT_TYPE' => 'application/json'
  558. ]
  559. ]);
  560. $stream = new Stream('php://memory', 'w');
  561. $stream->write('{"valid":true}');
  562. $this->Controller->request = $this->Controller->request->withBody($stream);
  563. $event = new Event('Controller.startup', $this->Controller);
  564. $this->RequestHandler->startup($event);
  565. $this->assertEquals(['valid' => true], $this->Controller->request->getData());
  566. }
  567. /**
  568. * Test that file handles are ignored as XML data.
  569. *
  570. * @return void
  571. * @triggers Controller.startup $this->Controller
  572. */
  573. public function testStartupIgnoreFileAsXml()
  574. {
  575. $this->Controller->request = new ServerRequest([
  576. 'input' => '/dev/random',
  577. 'environment' => [
  578. 'REQUEST_METHOD' => 'POST',
  579. 'CONTENT_TYPE' => 'application/xml'
  580. ]
  581. ]);
  582. $event = new Event('Controller.startup', $this->Controller);
  583. $this->RequestHandler->startup($event);
  584. $this->assertEquals([], $this->Controller->request->getData());
  585. }
  586. /**
  587. * Test that input xml is parsed
  588. *
  589. * @return void
  590. */
  591. public function testStartupConvertXmlDataWrapper()
  592. {
  593. $xml = <<<XML
  594. <?xml version="1.0" encoding="utf-8"?>
  595. <data>
  596. <article id="1" title="first"></article>
  597. </data>
  598. XML;
  599. $this->Controller->request = new ServerRequest(['input' => $xml]);
  600. $this->Controller->request = $this->Controller->request
  601. ->withEnv('REQUEST_METHOD', 'POST')
  602. ->withEnv('CONTENT_TYPE', 'application/xml');
  603. $event = new Event('Controller.startup', $this->Controller);
  604. $this->RequestHandler->startup($event);
  605. $expected = [
  606. 'data' => [
  607. 'article' => [
  608. '@id' => 1,
  609. '@title' => 'first'
  610. ]
  611. ]
  612. ];
  613. $this->assertEquals($expected, $this->Controller->request->getData());
  614. }
  615. /**
  616. * Test that input xml is parsed
  617. *
  618. * @return void
  619. */
  620. public function testStartupConvertXmlElements()
  621. {
  622. $xml = <<<XML
  623. <?xml version="1.0" encoding="utf-8"?>
  624. <article>
  625. <id>1</id>
  626. <title><![CDATA[first]]></title>
  627. </article>
  628. XML;
  629. $this->Controller->request = new ServerRequest(['input' => $xml]);
  630. $this->Controller->request = $this->Controller->request
  631. ->withEnv('REQUEST_METHOD', 'POST')
  632. ->withEnv('CONTENT_TYPE', 'application/xml');
  633. $event = new Event('Controller.startup', $this->Controller);
  634. $this->RequestHandler->startup($event);
  635. $expected = [
  636. 'article' => [
  637. 'id' => 1,
  638. 'title' => 'first'
  639. ]
  640. ];
  641. $this->assertEquals($expected, $this->Controller->request->getData());
  642. }
  643. /**
  644. * Test that input xml is parsed
  645. *
  646. * @return void
  647. */
  648. public function testStartupConvertXmlIgnoreEntities()
  649. {
  650. $xml = <<<XML
  651. <?xml version="1.0" encoding="UTF-8"?>
  652. <!DOCTYPE item [
  653. <!ENTITY item "item">
  654. <!ENTITY item1 "&item;&item;&item;&item;&item;&item;">
  655. <!ENTITY item2 "&item1;&item1;&item1;&item1;&item1;&item1;&item1;&item1;&item1;">
  656. <!ENTITY item3 "&item2;&item2;&item2;&item2;&item2;&item2;&item2;&item2;&item2;">
  657. <!ENTITY item4 "&item3;&item3;&item3;&item3;&item3;&item3;&item3;&item3;&item3;">
  658. <!ENTITY item5 "&item4;&item4;&item4;&item4;&item4;&item4;&item4;&item4;&item4;">
  659. <!ENTITY item6 "&item5;&item5;&item5;&item5;&item5;&item5;&item5;&item5;&item5;">
  660. <!ENTITY item7 "&item6;&item6;&item6;&item6;&item6;&item6;&item6;&item6;&item6;">
  661. <!ENTITY item8 "&item7;&item7;&item7;&item7;&item7;&item7;&item7;&item7;&item7;">
  662. ]>
  663. <item>
  664. <description>&item8;</description>
  665. </item>
  666. XML;
  667. $this->Controller->request = new ServerRequest(['input' => $xml]);
  668. $this->Controller->request = $this->Controller->request
  669. ->withEnv('REQUEST_METHOD', 'POST')
  670. ->withEnv('CONTENT_TYPE', 'application/xml');
  671. $event = new Event('Controller.startup', $this->Controller);
  672. $this->RequestHandler->startup($event);
  673. $this->assertEquals([], $this->Controller->request->getData());
  674. }
  675. /**
  676. * Test mapping a new type and having startup process it.
  677. *
  678. * @group deprecated
  679. * @return void
  680. * @triggers Controller.startup $this->Controller
  681. */
  682. public function testStartupCustomTypeProcess()
  683. {
  684. $this->deprecated(function () {
  685. $this->Controller->request = new ServerRequest([
  686. 'input' => '"A","csv","string"',
  687. 'environment' => [
  688. 'REQUEST_METHOD' => 'POST',
  689. 'CONTENT_TYPE' => 'text/csv'
  690. ]
  691. ]);
  692. $this->RequestHandler->addInputType('csv', ['str_getcsv']);
  693. $event = new Event('Controller.startup', $this->Controller);
  694. $this->RequestHandler->startup($event);
  695. $expected = [
  696. 'A', 'csv', 'string'
  697. ];
  698. $this->assertEquals($expected, $this->Controller->request->getData());
  699. });
  700. }
  701. /**
  702. * Test that data isn't processed when parsed data already exists.
  703. *
  704. * @return void
  705. * @triggers Controller.startup $this->Controller
  706. */
  707. public function testStartupSkipDataProcess()
  708. {
  709. $this->Controller->request = new ServerRequest([
  710. 'environment' => [
  711. 'REQUEST_METHOD' => 'POST',
  712. 'CONTENT_TYPE' => 'application/json'
  713. ]
  714. ]);
  715. $event = new Event('Controller.startup', $this->Controller);
  716. $this->RequestHandler->startup($event);
  717. $this->assertEquals([], $this->Controller->request->getData());
  718. $stream = new Stream('php://memory', 'w');
  719. $stream->write('{"new": "data"}');
  720. $this->Controller->request = $this->Controller->request
  721. ->withBody($stream)
  722. ->withParsedBody(['old' => 'news']);
  723. $this->RequestHandler->startup($event);
  724. $this->assertEquals(['old' => 'news'], $this->Controller->request->getData());
  725. }
  726. /**
  727. * test beforeRedirect when disabled.
  728. *
  729. * @return void
  730. * @triggers Controller.startup $this->Controller
  731. */
  732. public function testBeforeRedirectDisabled()
  733. {
  734. static::setAppNamespace();
  735. Router::connect('/:controller/:action');
  736. $this->Controller->request = $this->Controller->request->withHeader('X-Requested-With', 'XMLHttpRequest');
  737. $event = new Event('Controller.startup', $this->Controller);
  738. $this->RequestHandler->setConfig('enableBeforeRedirect', false);
  739. $this->RequestHandler->startup($event);
  740. $this->assertNull($this->RequestHandler->beforeRedirect($event, '/posts/index', $this->Controller->response));
  741. }
  742. /**
  743. * testNonAjaxRedirect method
  744. *
  745. * @group deprecated
  746. * @return void
  747. * @triggers Controller.startup $this->Controller
  748. */
  749. public function testNonAjaxRedirect()
  750. {
  751. $this->deprecated(function () {
  752. $event = new Event('Controller.startup', $this->Controller);
  753. $this->RequestHandler->startup($event);
  754. $this->assertNull($this->RequestHandler->beforeRedirect($event, '/', $this->Controller->response));
  755. });
  756. }
  757. /**
  758. * test that redirects with ajax and no URL don't do anything.
  759. *
  760. * @group deprecated
  761. * @return void
  762. * @triggers Controller.startup $this->Controller
  763. */
  764. public function testAjaxRedirectWithNoUrl()
  765. {
  766. $this->deprecated(function () {
  767. $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
  768. $event = new Event('Controller.startup', $this->Controller);
  769. $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  770. $this->Controller->response->expects($this->never())
  771. ->method('body');
  772. $this->RequestHandler->startup($event);
  773. $this->assertNull($this->RequestHandler->beforeRedirect($event, null, $this->Controller->response));
  774. });
  775. }
  776. /**
  777. * testRenderAs method
  778. *
  779. * @return void
  780. */
  781. public function testRenderAs()
  782. {
  783. $this->RequestHandler->renderAs($this->Controller, 'rss');
  784. $this->Controller->viewBuilder()->setTemplatePath('request_handler_test\\rss');
  785. $this->RequestHandler->renderAs($this->Controller, 'js');
  786. $this->assertEquals('request_handler_test' . DS . 'js', $this->Controller->viewBuilder()->getTemplatePath());
  787. }
  788. /**
  789. * test that attachment headers work with renderAs
  790. *
  791. * @return void
  792. */
  793. public function testRenderAsWithAttachment()
  794. {
  795. $this->Controller->request = $this->request->withHeader('Accept', 'application/xml;q=1.0');
  796. $this->RequestHandler->renderAs($this->Controller, 'xml', ['attachment' => 'myfile.xml']);
  797. $this->assertEquals(XmlView::class, $this->Controller->viewBuilder()->getClassName());
  798. $this->assertEquals('application/xml', $this->Controller->response->getType());
  799. $this->assertEquals('UTF-8', $this->Controller->response->getCharset());
  800. $this->assertContains('myfile.xml', $this->Controller->response->getHeaderLine('Content-Disposition'));
  801. }
  802. /**
  803. * test that respondAs works as expected.
  804. *
  805. * @return void
  806. */
  807. public function testRespondAs()
  808. {
  809. $result = $this->RequestHandler->respondAs('json');
  810. $this->assertTrue($result);
  811. $this->assertEquals('application/json', $this->Controller->response->getType());
  812. $result = $this->RequestHandler->respondAs('text/xml');
  813. $this->assertTrue($result);
  814. $this->assertEquals('text/xml', $this->Controller->response->getType());
  815. }
  816. /**
  817. * test that attachment headers work with respondAs
  818. *
  819. * @return void
  820. */
  821. public function testRespondAsWithAttachment()
  822. {
  823. $result = $this->RequestHandler->respondAs('xml', ['attachment' => 'myfile.xml']);
  824. $this->assertTrue($result);
  825. $response = $this->Controller->response;
  826. $this->assertContains('myfile.xml', $response->getHeaderLine('Content-Disposition'));
  827. $this->assertContains('application/xml', $response->getType());
  828. }
  829. /**
  830. * test that calling renderAs() more than once continues to work.
  831. *
  832. * @link #6466
  833. * @return void
  834. */
  835. public function testRenderAsCalledTwice()
  836. {
  837. $this->Controller->getEventManager()->on('Controller.beforeRender', function (\Cake\Event\Event $e) {
  838. return $e->getSubject()->response;
  839. });
  840. $this->Controller->render();
  841. $this->RequestHandler->renderAs($this->Controller, 'print');
  842. $this->assertEquals('RequestHandlerTest' . DS . 'print', $this->Controller->viewBuilder()->getTemplatePath());
  843. $this->assertEquals('print', $this->Controller->viewBuilder()->getLayoutPath());
  844. $this->RequestHandler->renderAs($this->Controller, 'js');
  845. $this->assertEquals('RequestHandlerTest' . DS . 'js', $this->Controller->viewBuilder()->getTemplatePath());
  846. $this->assertEquals('js', $this->Controller->viewBuilder()->getLayoutPath());
  847. }
  848. /**
  849. * testRequestContentTypes method
  850. *
  851. * @return void
  852. */
  853. public function testRequestContentTypes()
  854. {
  855. $this->Controller->request = $this->request->withEnv('REQUEST_METHOD', 'GET');
  856. $this->assertNull($this->RequestHandler->requestedWith());
  857. $this->Controller->request = $this->request->withEnv('REQUEST_METHOD', 'POST')
  858. ->withEnv('CONTENT_TYPE', 'application/json');
  859. $this->assertEquals('json', $this->RequestHandler->requestedWith());
  860. $result = $this->RequestHandler->requestedWith(['json', 'xml']);
  861. $this->assertEquals('json', $result);
  862. $result = $this->RequestHandler->requestedWith(['rss', 'atom']);
  863. $this->assertFalse($result);
  864. $this->Controller->request = $this->request
  865. ->withEnv('REQUEST_METHOD', 'PATCH')
  866. ->withEnv('CONTENT_TYPE', 'application/json');
  867. $this->assertEquals('json', $this->RequestHandler->requestedWith());
  868. $this->Controller->request = $this->request
  869. ->withEnv('REQUEST_METHOD', 'DELETE')
  870. ->withEnv('CONTENT_TYPE', 'application/json');
  871. $this->assertEquals('json', $this->RequestHandler->requestedWith());
  872. $this->Controller->request = $this->request
  873. ->withEnv('REQUEST_METHOD', 'POST')
  874. ->withEnv('CONTENT_TYPE', 'application/json');
  875. $result = $this->RequestHandler->requestedWith(['json', 'xml']);
  876. $this->assertEquals('json', $result);
  877. $result = $this->RequestHandler->requestedWith(['rss', 'atom']);
  878. $this->assertFalse($result);
  879. $this->Controller->request = $this->request->withHeader(
  880. 'Accept',
  881. 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  882. );
  883. $this->deprecated(function () {
  884. $this->assertTrue($this->RequestHandler->isXml());
  885. $this->assertFalse($this->RequestHandler->isAtom());
  886. $this->assertFalse($this->RequestHandler->isRSS());
  887. });
  888. $this->Controller->request = $this->request->withHeader(
  889. 'Accept',
  890. 'application/atom+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  891. );
  892. $this->deprecated(function () {
  893. $this->assertTrue($this->RequestHandler->isAtom());
  894. $this->assertFalse($this->RequestHandler->isRSS());
  895. });
  896. $this->Controller->request = $this->request->withHeader(
  897. 'Accept',
  898. 'application/rss+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  899. );
  900. $this->deprecated(function () {
  901. $this->assertFalse($this->RequestHandler->isAtom());
  902. $this->assertTrue($this->RequestHandler->isRSS());
  903. });
  904. $this->deprecated(function () {
  905. $this->assertFalse($this->RequestHandler->isWap());
  906. });
  907. $this->Controller->request = $this->request->withHeader(
  908. 'Accept',
  909. 'text/vnd.wap.wml,text/html,text/plain,image/png,*/*'
  910. );
  911. $this->deprecated(function () {
  912. $this->assertTrue($this->RequestHandler->isWap());
  913. });
  914. }
  915. /**
  916. * testResponseContentType method
  917. *
  918. * @return void
  919. */
  920. public function testResponseContentType()
  921. {
  922. $this->deprecated(function () {
  923. $this->assertEquals('html', $this->RequestHandler->responseType());
  924. $this->assertTrue($this->RequestHandler->respondAs('atom'));
  925. $this->assertEquals('atom', $this->RequestHandler->responseType());
  926. });
  927. }
  928. /**
  929. * testMobileDeviceDetection method
  930. *
  931. * @return void
  932. */
  933. public function testMobileDeviceDetection()
  934. {
  935. $request = $this->getMockBuilder('Cake\Http\ServerRequest')
  936. ->setMethods(['is'])
  937. ->getMock();
  938. $request->expects($this->once())->method('is')
  939. ->with('mobile')
  940. ->will($this->returnValue(true));
  941. $this->Controller->request = $request;
  942. $this->deprecated(function () {
  943. $this->assertTrue($this->RequestHandler->isMobile());
  944. });
  945. }
  946. /**
  947. * test that map alias converts aliases to content types.
  948. *
  949. * @return void
  950. */
  951. public function testMapAlias()
  952. {
  953. $result = $this->RequestHandler->mapAlias('xml');
  954. $this->assertEquals('application/xml', $result);
  955. $result = $this->RequestHandler->mapAlias('text/html');
  956. $this->assertNull($result);
  957. $result = $this->RequestHandler->mapAlias('wap');
  958. $this->assertEquals('text/vnd.wap.wml', $result);
  959. $result = $this->RequestHandler->mapAlias(['xml', 'js', 'json']);
  960. $expected = ['application/xml', 'application/javascript', 'application/json'];
  961. $this->assertEquals($expected, $result);
  962. }
  963. /**
  964. * test accepts() on the component
  965. *
  966. * @return void
  967. */
  968. public function testAccepts()
  969. {
  970. $this->Controller->request = $this->request->withHeader(
  971. 'Accept',
  972. 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'
  973. );
  974. $this->assertTrue($this->RequestHandler->accepts(['js', 'xml', 'html']));
  975. $this->assertFalse($this->RequestHandler->accepts(['gif', 'jpeg', 'foo']));
  976. $this->Controller->request = $this->request->withHeader('Accept', '*/*;q=0.5');
  977. $this->assertFalse($this->RequestHandler->accepts('rss'));
  978. }
  979. /**
  980. * test accepts and prefers methods.
  981. *
  982. * @return void
  983. */
  984. public function testPrefers()
  985. {
  986. $this->Controller->request = $this->request->withHeader(
  987. 'Accept',
  988. 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  989. );
  990. $this->assertNotEquals('rss', $this->RequestHandler->prefers());
  991. $this->RequestHandler->ext = 'rss';
  992. $this->assertEquals('rss', $this->RequestHandler->prefers());
  993. $this->assertFalse($this->RequestHandler->prefers('xml'));
  994. $this->assertEquals('xml', $this->RequestHandler->prefers(['js', 'xml', 'xhtml']));
  995. $this->assertFalse($this->RequestHandler->prefers(['red', 'blue']));
  996. $this->assertEquals('xhtml', $this->RequestHandler->prefers(['js', 'json', 'xhtml']));
  997. $this->assertTrue($this->RequestHandler->prefers(['rss']), 'Should return true if input matches ext.');
  998. $this->assertFalse($this->RequestHandler->prefers(['html']), 'No match with ext, return false.');
  999. $this->_init();
  1000. $this->Controller->request = $this->request->withHeader(
  1001. 'Accept',
  1002. 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'
  1003. );
  1004. $this->assertEquals('xml', $this->RequestHandler->prefers());
  1005. $this->Controller->request = $this->request->withHeader('Accept', '*/*;q=0.5');
  1006. $this->assertEquals('html', $this->RequestHandler->prefers());
  1007. $this->assertFalse($this->RequestHandler->prefers('rss'));
  1008. $this->Controller->request = $this->request->withEnv('HTTP_ACCEPT', null);
  1009. $this->RequestHandler->ext = 'json';
  1010. $this->assertFalse($this->RequestHandler->prefers('xml'));
  1011. }
  1012. /**
  1013. * test that AJAX requests involving redirects trigger requestAction instead.
  1014. *
  1015. * @group deprecated
  1016. * @return void
  1017. * @triggers Controller.beforeRedirect $this->Controller
  1018. */
  1019. public function testAjaxRedirectAsRequestAction()
  1020. {
  1021. $this->deprecated(function () {
  1022. static::setAppNamespace();
  1023. Router::connect('/:controller/:action');
  1024. $event = new Event('Controller.beforeRedirect', $this->Controller);
  1025. $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
  1026. $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
  1027. ->setMethods(['is'])
  1028. ->getMock();
  1029. $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
  1030. ->setMethods(['_sendHeader', 'stop'])
  1031. ->getMock();
  1032. $this->Controller->request->expects($this->any())
  1033. ->method('is')
  1034. ->will($this->returnValue(true));
  1035. $response = $this->RequestHandler->beforeRedirect(
  1036. $event,
  1037. ['controller' => 'RequestHandlerTest', 'action' => 'destination'],
  1038. $this->Controller->response
  1039. );
  1040. $this->assertRegExp('/posts index/', $response->body(), 'RequestAction redirect failed.');
  1041. });
  1042. }
  1043. /**
  1044. * Test that AJAX requests involving redirects handle querystrings
  1045. *
  1046. * @group deprecated
  1047. * @return void
  1048. * @triggers Controller.beforeRedirect $this->Controller
  1049. */
  1050. public function testAjaxRedirectAsRequestActionWithQueryString()
  1051. {
  1052. $this->deprecated(function () {
  1053. static::setAppNamespace();
  1054. Router::connect('/:controller/:action');
  1055. $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
  1056. $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
  1057. ->setMethods(['is'])
  1058. ->getMock();
  1059. $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
  1060. ->setMethods(['_sendHeader', 'stop'])
  1061. ->getMock();
  1062. $this->Controller->request->expects($this->any())
  1063. ->method('is')
  1064. ->with('ajax')
  1065. ->will($this->returnValue(true));
  1066. $event = new Event('Controller.beforeRedirect', $this->Controller);
  1067. $response = $this->RequestHandler->beforeRedirect(
  1068. $event,
  1069. '/request_action/params_pass?a=b&x=y?ish',
  1070. $this->Controller->response
  1071. );
  1072. $data = json_decode($response, true);
  1073. $this->assertEquals('/request_action/params_pass', $data['here']);
  1074. $response = $this->RequestHandler->beforeRedirect(
  1075. $event,
  1076. '/request_action/query_pass?a=b&x=y?ish',
  1077. $this->Controller->response
  1078. );
  1079. $data = json_decode($response, true);
  1080. $this->assertEquals('y?ish', $data['x']);
  1081. });
  1082. }
  1083. /**
  1084. * Test that AJAX requests involving redirects handle cookie data
  1085. *
  1086. * @group deprecated
  1087. * @return void
  1088. * @triggers Controller.beforeRedirect $this->Controller
  1089. */
  1090. public function testAjaxRedirectAsRequestActionWithCookieData()
  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. $cookies = [
  1105. 'foo' => 'bar'
  1106. ];
  1107. $this->Controller->request->cookies = $cookies;
  1108. $response = $this->RequestHandler->beforeRedirect(
  1109. $event,
  1110. '/request_action/cookie_pass',
  1111. $this->Controller->response
  1112. );
  1113. $data = json_decode($response, true);
  1114. $this->assertEquals($cookies, $data);
  1115. });
  1116. }
  1117. /**
  1118. * Tests that AJAX requests involving redirects don't let the status code bleed through.
  1119. *
  1120. * @group deprecated
  1121. * @return void
  1122. * @triggers Controller.beforeRedirect $this->Controller
  1123. */
  1124. public function testAjaxRedirectAsRequestActionStatusCode()
  1125. {
  1126. $this->deprecated(function () {
  1127. static::setAppNamespace();
  1128. Router::connect('/:controller/:action');
  1129. $event = new Event('Controller.beforeRedirect', $this->Controller);
  1130. $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
  1131. $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
  1132. ->setMethods(['is'])
  1133. ->getMock();
  1134. $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
  1135. ->setMethods(['_sendHeader', 'stop'])
  1136. ->getMock();
  1137. $this->Controller->response->statusCode(302);
  1138. $this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true));
  1139. $response = $this->RequestHandler->beforeRedirect(
  1140. $event,
  1141. ['controller' => 'RequestHandlerTest', 'action' => 'destination'],
  1142. $this->Controller->response
  1143. );
  1144. $this->assertRegExp('/posts index/', $response->body(), 'RequestAction redirect failed.');
  1145. $this->assertSame(200, $response->statusCode());
  1146. });
  1147. }
  1148. /**
  1149. * test that ajax requests involving redirects don't force no layout
  1150. * this would cause the ajax layout to not be rendered.
  1151. *
  1152. * @group deprecated
  1153. * @return void
  1154. * @triggers Controller.beforeRedirect $this->Controller
  1155. */
  1156. public function testAjaxRedirectAsRequestActionStillRenderingLayout()
  1157. {
  1158. $this->deprecated(function () {
  1159. static::setAppNamespace();
  1160. Router::connect('/:controller/:action');
  1161. $event = new Event('Controller.beforeRedirect', $this->Controller);
  1162. $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
  1163. $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
  1164. ->setMethods(['is'])
  1165. ->getMock();
  1166. $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
  1167. ->setMethods(['_sendHeader', 'stop'])
  1168. ->getMock();
  1169. $this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true));
  1170. $response = $this->RequestHandler->beforeRedirect(
  1171. $event,
  1172. ['controller' => 'RequestHandlerTest', 'action' => 'ajax2_layout'],
  1173. $this->Controller->response
  1174. );
  1175. $this->assertRegExp('/posts index/', $response->body(), 'RequestAction redirect failed.');
  1176. $this->assertRegExp('/Ajax!/', $response->body(), 'Layout was not rendered.');
  1177. });
  1178. }
  1179. /**
  1180. * test that the beforeRedirect callback properly converts
  1181. * array URLs into their correct string ones, and adds base => false so
  1182. * the correct URLs are generated.
  1183. *
  1184. * @group deprecated
  1185. * @return void
  1186. * @triggers Controller.beforeRender $this->Controller
  1187. */
  1188. public function testBeforeRedirectCallbackWithArrayUrl()
  1189. {
  1190. $this->deprecated(function () {
  1191. static::setAppNamespace();
  1192. Router::connect('/:controller/:action/*');
  1193. $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
  1194. $event = new Event('Controller.beforeRender', $this->Controller);
  1195. Router::setRequestInfo([
  1196. ['plugin' => null, 'controller' => 'accounts', 'action' => 'index', 'pass' => []],
  1197. ['base' => '', 'here' => '/accounts/', 'webroot' => '/']
  1198. ]);
  1199. $RequestHandler = new RequestHandlerComponent($this->Controller->components());
  1200. $this->Controller->request = new ServerRequest('posts/index');
  1201. ob_start();
  1202. $RequestHandler->beforeRedirect(
  1203. $event,
  1204. ['controller' => 'RequestHandlerTest', 'action' => 'param_method', 'first', 'second'],
  1205. $this->Controller->response
  1206. );
  1207. $result = ob_get_clean();
  1208. $this->assertEquals('one: first two: second', $result);
  1209. });
  1210. }
  1211. /**
  1212. * testAddInputTypeException method
  1213. *
  1214. * @group deprecated
  1215. * @return void
  1216. */
  1217. public function testAddInputTypeException()
  1218. {
  1219. $this->expectException(\Cake\Core\Exception\Exception::class);
  1220. $this->deprecated(function () {
  1221. $this->RequestHandler->addInputType('csv', ['I am not callable']);
  1222. });
  1223. }
  1224. /**
  1225. * Test checkNotModified method
  1226. *
  1227. * @return void
  1228. * @triggers Controller.beforeRender $this->Controller
  1229. */
  1230. public function testCheckNotModifiedByEtagStar()
  1231. {
  1232. $response = new Response();
  1233. $response = $response->withEtag('something')
  1234. ->withHeader('Content-Type', 'text/plain')
  1235. ->withStringBody('keeper');
  1236. $this->Controller->response = $response;
  1237. $this->Controller->request = $this->request->withHeader('If-None-Match', '*');
  1238. $event = new Event('Controller.beforeRender', $this->Controller);
  1239. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  1240. $this->assertFalse($requestHandler->beforeRender($event));
  1241. $this->assertEquals(304, $this->Controller->response->getStatusCode());
  1242. $this->assertEquals('', (string)$this->Controller->response->getBody());
  1243. $this->assertFalse($this->Controller->response->hasHeader('Content-Type'), 'header should not be removed.');
  1244. }
  1245. /**
  1246. * Test checkNotModified method
  1247. *
  1248. * @return void
  1249. * @triggers Controller.beforeRender
  1250. */
  1251. public function testCheckNotModifiedByEtagExact()
  1252. {
  1253. $response = new Response();
  1254. $response = $response->withEtag('something', true)
  1255. ->withHeader('Content-Type', 'text/plain')
  1256. ->withStringBody('keeper');
  1257. $this->Controller->response = $response;
  1258. $this->Controller->request = $this->request->withHeader('If-None-Match', 'W/"something", "other"');
  1259. $event = new Event('Controller.beforeRender', $this->Controller);
  1260. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  1261. $this->assertFalse($requestHandler->beforeRender($event));
  1262. $this->assertEquals(304, $this->Controller->response->getStatusCode());
  1263. $this->assertEquals('', (string)$this->Controller->response->getBody());
  1264. $this->assertFalse($this->Controller->response->hasHeader('Content-Type'));
  1265. }
  1266. /**
  1267. * Test checkNotModified method
  1268. *
  1269. * @return void
  1270. * @triggers Controller.beforeRender $this->Controller
  1271. */
  1272. public function testCheckNotModifiedByEtagAndTime()
  1273. {
  1274. $this->Controller->request = $this->request
  1275. ->withHeader('If-None-Match', 'W/"something", "other"')
  1276. ->withHeader('If-Modified-Since', '2012-01-01 00:00:00');
  1277. $response = new Response();
  1278. $response = $response->withEtag('something', true)
  1279. ->withHeader('Content-type', 'text/plain')
  1280. ->withStringBody('should be removed')
  1281. ->withModified('2012-01-01 00:00:00');
  1282. $this->Controller->response = $response;
  1283. $event = new Event('Controller.beforeRender', $this->Controller);
  1284. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  1285. $this->assertFalse($requestHandler->beforeRender($event));
  1286. $this->assertEquals(304, $this->Controller->response->getStatusCode());
  1287. $this->assertEquals('', (string)$this->Controller->response->getBody());
  1288. $this->assertFalse($this->Controller->response->hasHeader('Content-type'));
  1289. }
  1290. /**
  1291. * Test checkNotModified method
  1292. *
  1293. * @return void
  1294. * @triggers Controller.beforeRender $this->Controller
  1295. */
  1296. public function testCheckNotModifiedNoInfo()
  1297. {
  1298. $response = $this->getMockBuilder('Cake\Http\Response')
  1299. ->setMethods(['notModified', 'stop'])
  1300. ->getMock();
  1301. $response->expects($this->never())->method('notModified');
  1302. $this->Controller->response = $response;
  1303. $event = new Event('Controller.beforeRender', $this->Controller);
  1304. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  1305. $this->assertNull($requestHandler->beforeRender($event));
  1306. }
  1307. /**
  1308. * Test default options in construction
  1309. *
  1310. * @return void
  1311. */
  1312. public function testConstructDefaultOptions()
  1313. {
  1314. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  1315. $viewClass = $requestHandler->getConfig('viewClassMap');
  1316. $expected = [
  1317. 'json' => 'Json',
  1318. 'xml' => 'Xml',
  1319. 'ajax' => 'Ajax',
  1320. ];
  1321. $this->assertEquals($expected, $viewClass);
  1322. $inputs = $requestHandler->getConfig('inputTypeMap');
  1323. $this->assertArrayHasKey('json', $inputs);
  1324. $this->assertArrayHasKey('xml', $inputs);
  1325. }
  1326. /**
  1327. * Test options in constructor replace defaults
  1328. *
  1329. * @return void
  1330. */
  1331. public function testConstructReplaceOptions()
  1332. {
  1333. $requestHandler = new RequestHandlerComponent(
  1334. $this->Controller->components(),
  1335. [
  1336. 'viewClassMap' => ['json' => 'Json'],
  1337. 'inputTypeMap' => ['json' => ['json_decode', true]]
  1338. ]
  1339. );
  1340. $viewClass = $requestHandler->getConfig('viewClassMap');
  1341. $expected = [
  1342. 'json' => 'Json',
  1343. ];
  1344. $this->assertEquals($expected, $viewClass);
  1345. $inputs = $requestHandler->getConfig('inputTypeMap');
  1346. $this->assertArrayHasKey('json', $inputs);
  1347. $this->assertCount(1, $inputs);
  1348. }
  1349. /**
  1350. * test beforeRender() doesn't override response type set in controller action
  1351. *
  1352. * @return void
  1353. */
  1354. public function testBeforeRender()
  1355. {
  1356. $this->Controller->set_response_type();
  1357. $event = new Event('Controller.beforeRender', $this->Controller);
  1358. $this->RequestHandler->beforeRender($event);
  1359. $this->assertEquals('text/plain', $this->Controller->response->getType());
  1360. }
  1361. /**
  1362. * tests beforeRender automatically uses renderAs when a supported extension is found
  1363. *
  1364. * @return void
  1365. */
  1366. public function testBeforeRenderAutoRenderAs()
  1367. {
  1368. $this->Controller->setRequest($this->request->withParam('_ext', 'csv'));
  1369. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  1370. $event = new Event('Controller.beforeRender', $this->Controller);
  1371. $this->RequestHandler->beforeRender($event);
  1372. $this->assertEquals('text/csv', $this->Controller->response->getType());
  1373. }
  1374. }