RequestHandlerComponentTest.php 54 KB

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