RequestHandlerComponentTest.php 52 KB

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