RequestHandlerComponentTest.php 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363
  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 mapping a new type and having startup process it.
  561. *
  562. * @group deprecated
  563. * @return void
  564. * @triggers Controller.startup $this->Controller
  565. */
  566. public function testStartupCustomTypeProcess()
  567. {
  568. $this->deprecated(function () {
  569. $this->Controller->request = new ServerRequest([
  570. 'input' => '"A","csv","string"',
  571. 'environment' => [
  572. 'REQUEST_METHOD' => 'POST',
  573. 'CONTENT_TYPE' => 'text/csv'
  574. ]
  575. ]);
  576. $this->RequestHandler->addInputType('csv', ['str_getcsv']);
  577. $event = new Event('Controller.startup', $this->Controller);
  578. $this->RequestHandler->startup($event);
  579. $expected = [
  580. 'A', 'csv', 'string'
  581. ];
  582. $this->assertEquals($expected, $this->Controller->request->getData());
  583. });
  584. }
  585. /**
  586. * test beforeRedirect when disabled.
  587. *
  588. * @return void
  589. * @triggers Controller.startup $this->Controller
  590. */
  591. public function testBeforeRedirectDisabled()
  592. {
  593. static::setAppNamespace();
  594. Router::connect('/:controller/:action');
  595. $this->Controller->request = $this->Controller->request->withHeader('X-Requested-With', 'XMLHttpRequest');
  596. $event = new Event('Controller.startup', $this->Controller);
  597. $this->RequestHandler->initialize([]);
  598. $this->RequestHandler->setConfig('enableBeforeRedirect', false);
  599. $this->RequestHandler->startup($event);
  600. $this->assertNull($this->RequestHandler->beforeRedirect($event, '/posts/index', $this->Controller->response));
  601. }
  602. /**
  603. * testNonAjaxRedirect method
  604. *
  605. * @group deprecated
  606. * @return void
  607. * @triggers Controller.startup $this->Controller
  608. */
  609. public function testNonAjaxRedirect()
  610. {
  611. $this->deprecated(function () {
  612. $event = new Event('Controller.startup', $this->Controller);
  613. $this->RequestHandler->initialize([]);
  614. $this->RequestHandler->startup($event);
  615. $this->assertNull($this->RequestHandler->beforeRedirect($event, '/', $this->Controller->response));
  616. });
  617. }
  618. /**
  619. * test that redirects with ajax and no URL don't do anything.
  620. *
  621. * @group deprecated
  622. * @return void
  623. * @triggers Controller.startup $this->Controller
  624. */
  625. public function testAjaxRedirectWithNoUrl()
  626. {
  627. $this->deprecated(function () {
  628. $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
  629. $event = new Event('Controller.startup', $this->Controller);
  630. $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  631. $this->Controller->response->expects($this->never())
  632. ->method('body');
  633. $this->RequestHandler->initialize([]);
  634. $this->RequestHandler->startup($event);
  635. $this->assertNull($this->RequestHandler->beforeRedirect($event, null, $this->Controller->response));
  636. });
  637. }
  638. /**
  639. * testRenderAs method
  640. *
  641. * @return void
  642. */
  643. public function testRenderAs()
  644. {
  645. $this->RequestHandler->renderAs($this->Controller, 'rss');
  646. $this->Controller->viewBuilder()->templatePath('request_handler_test\\rss');
  647. $this->RequestHandler->renderAs($this->Controller, 'js');
  648. $this->assertEquals('request_handler_test' . DS . 'js', $this->Controller->viewBuilder()->templatePath());
  649. }
  650. /**
  651. * test that attachment headers work with renderAs
  652. *
  653. * @return void
  654. */
  655. public function testRenderAsWithAttachment()
  656. {
  657. $this->Controller->request = $this->request->withHeader('Accept', 'application/xml;q=1.0');
  658. $this->RequestHandler->renderAs($this->Controller, 'xml', ['attachment' => 'myfile.xml']);
  659. $this->assertEquals('Cake\View\XmlView', $this->Controller->viewClass);
  660. $this->assertEquals('application/xml', $this->Controller->response->getType());
  661. $this->assertEquals('UTF-8', $this->Controller->response->getCharset());
  662. $this->assertContains('myfile.xml', $this->Controller->response->getHeaderLine('Content-Disposition'));
  663. }
  664. /**
  665. * test that respondAs works as expected.
  666. *
  667. * @return void
  668. */
  669. public function testRespondAs()
  670. {
  671. $result = $this->RequestHandler->respondAs('json');
  672. $this->assertTrue($result);
  673. $this->assertEquals('application/json', $this->Controller->response->getType());
  674. $result = $this->RequestHandler->respondAs('text/xml');
  675. $this->assertTrue($result);
  676. $this->assertEquals('text/xml', $this->Controller->response->getType());
  677. }
  678. /**
  679. * test that attachment headers work with respondAs
  680. *
  681. * @return void
  682. */
  683. public function testRespondAsWithAttachment()
  684. {
  685. $result = $this->RequestHandler->respondAs('xml', ['attachment' => 'myfile.xml']);
  686. $this->assertTrue($result);
  687. $response = $this->Controller->response;
  688. $this->assertContains('myfile.xml', $response->getHeaderLine('Content-Disposition'));
  689. $this->assertContains('application/xml', $response->getType());
  690. }
  691. /**
  692. * test that calling renderAs() more than once continues to work.
  693. *
  694. * @link #6466
  695. * @return void
  696. */
  697. public function testRenderAsCalledTwice()
  698. {
  699. $this->Controller->getEventManager()->on('Controller.beforeRender', function (\Cake\Event\Event $e) {
  700. return $e->getSubject()->response;
  701. });
  702. $this->Controller->render();
  703. $this->RequestHandler->renderAs($this->Controller, 'print');
  704. $this->assertEquals('RequestHandlerTest' . DS . 'print', $this->Controller->viewBuilder()->templatePath());
  705. $this->assertEquals('print', $this->Controller->viewBuilder()->layoutPath());
  706. $this->RequestHandler->renderAs($this->Controller, 'js');
  707. $this->assertEquals('RequestHandlerTest' . DS . 'js', $this->Controller->viewBuilder()->templatePath());
  708. $this->assertEquals('js', $this->Controller->viewBuilder()->layoutPath());
  709. }
  710. /**
  711. * testRequestContentTypes method
  712. *
  713. * @return void
  714. */
  715. public function testRequestContentTypes()
  716. {
  717. $this->Controller->request = $this->request->withEnv('REQUEST_METHOD', 'GET');
  718. $this->assertNull($this->RequestHandler->requestedWith());
  719. $this->Controller->request = $this->request->withEnv('REQUEST_METHOD', 'POST')
  720. ->withEnv('CONTENT_TYPE', 'application/json');
  721. $this->assertEquals('json', $this->RequestHandler->requestedWith());
  722. $result = $this->RequestHandler->requestedWith(['json', 'xml']);
  723. $this->assertEquals('json', $result);
  724. $result = $this->RequestHandler->requestedWith(['rss', 'atom']);
  725. $this->assertFalse($result);
  726. $this->Controller->request = $this->request
  727. ->withEnv('REQUEST_METHOD', 'PATCH')
  728. ->withEnv('CONTENT_TYPE', 'application/json');
  729. $this->assertEquals('json', $this->RequestHandler->requestedWith());
  730. $this->Controller->request = $this->request
  731. ->withEnv('REQUEST_METHOD', 'DELETE')
  732. ->withEnv('CONTENT_TYPE', 'application/json');
  733. $this->assertEquals('json', $this->RequestHandler->requestedWith());
  734. $this->Controller->request = $this->request
  735. ->withEnv('REQUEST_METHOD', 'POST')
  736. ->withEnv('CONTENT_TYPE', 'application/json');
  737. $result = $this->RequestHandler->requestedWith(['json', 'xml']);
  738. $this->assertEquals('json', $result);
  739. $result = $this->RequestHandler->requestedWith(['rss', 'atom']);
  740. $this->assertFalse($result);
  741. $this->Controller->request = $this->request->withHeader(
  742. 'Accept',
  743. 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  744. );
  745. $this->assertTrue($this->RequestHandler->isXml());
  746. $this->assertFalse($this->RequestHandler->isAtom());
  747. $this->assertFalse($this->RequestHandler->isRSS());
  748. $this->Controller->request = $this->request->withHeader(
  749. 'Accept',
  750. 'application/atom+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  751. );
  752. $this->assertTrue($this->RequestHandler->isAtom());
  753. $this->assertFalse($this->RequestHandler->isRSS());
  754. $this->Controller->request = $this->request->withHeader(
  755. 'Accept',
  756. 'application/rss+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  757. );
  758. $this->assertFalse($this->RequestHandler->isAtom());
  759. $this->assertTrue($this->RequestHandler->isRSS());
  760. $this->assertFalse($this->RequestHandler->isWap());
  761. $this->Controller->request = $this->request->withHeader(
  762. 'Accept',
  763. 'text/vnd.wap.wml,text/html,text/plain,image/png,*/*'
  764. );
  765. $this->assertTrue($this->RequestHandler->isWap());
  766. }
  767. /**
  768. * testResponseContentType method
  769. *
  770. * @return void
  771. */
  772. public function testResponseContentType()
  773. {
  774. $this->assertEquals('html', $this->RequestHandler->responseType());
  775. $this->assertTrue($this->RequestHandler->respondAs('atom'));
  776. $this->assertEquals('atom', $this->RequestHandler->responseType());
  777. }
  778. /**
  779. * testMobileDeviceDetection method
  780. *
  781. * @return void
  782. */
  783. public function testMobileDeviceDetection()
  784. {
  785. $request = $this->getMockBuilder('Cake\Http\ServerRequest')
  786. ->setMethods(['is'])
  787. ->getMock();
  788. $request->expects($this->once())->method('is')
  789. ->with('mobile')
  790. ->will($this->returnValue(true));
  791. $this->Controller->request = $request;
  792. $this->assertTrue($this->RequestHandler->isMobile());
  793. }
  794. /**
  795. * test that map alias converts aliases to content types.
  796. *
  797. * @return void
  798. */
  799. public function testMapAlias()
  800. {
  801. $result = $this->RequestHandler->mapAlias('xml');
  802. $this->assertEquals('application/xml', $result);
  803. $result = $this->RequestHandler->mapAlias('text/html');
  804. $this->assertNull($result);
  805. $result = $this->RequestHandler->mapAlias('wap');
  806. $this->assertEquals('text/vnd.wap.wml', $result);
  807. $result = $this->RequestHandler->mapAlias(['xml', 'js', 'json']);
  808. $expected = ['application/xml', 'application/javascript', 'application/json'];
  809. $this->assertEquals($expected, $result);
  810. }
  811. /**
  812. * test accepts() on the component
  813. *
  814. * @return void
  815. */
  816. public function testAccepts()
  817. {
  818. $this->Controller->request = $this->request->withHeader(
  819. 'Accept',
  820. 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'
  821. );
  822. $this->assertTrue($this->RequestHandler->accepts(['js', 'xml', 'html']));
  823. $this->assertFalse($this->RequestHandler->accepts(['gif', 'jpeg', 'foo']));
  824. $this->Controller->request = $this->request->withHeader('Accept', '*/*;q=0.5');
  825. $this->assertFalse($this->RequestHandler->accepts('rss'));
  826. }
  827. /**
  828. * test accepts and prefers methods.
  829. *
  830. * @return void
  831. */
  832. public function testPrefers()
  833. {
  834. $this->Controller->request = $this->request->withHeader(
  835. 'Accept',
  836. 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*'
  837. );
  838. $this->assertNotEquals('rss', $this->RequestHandler->prefers());
  839. $this->RequestHandler->ext = 'rss';
  840. $this->assertEquals('rss', $this->RequestHandler->prefers());
  841. $this->assertFalse($this->RequestHandler->prefers('xml'));
  842. $this->assertEquals('xml', $this->RequestHandler->prefers(['js', 'xml', 'xhtml']));
  843. $this->assertFalse($this->RequestHandler->prefers(['red', 'blue']));
  844. $this->assertEquals('xhtml', $this->RequestHandler->prefers(['js', 'json', 'xhtml']));
  845. $this->assertTrue($this->RequestHandler->prefers(['rss']), 'Should return true if input matches ext.');
  846. $this->assertFalse($this->RequestHandler->prefers(['html']), 'No match with ext, return false.');
  847. $this->_init();
  848. $this->Controller->request = $this->request->withHeader(
  849. 'Accept',
  850. 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'
  851. );
  852. $this->assertEquals('xml', $this->RequestHandler->prefers());
  853. $this->Controller->request = $this->request->withHeader('Accept', '*/*;q=0.5');
  854. $this->assertEquals('html', $this->RequestHandler->prefers());
  855. $this->assertFalse($this->RequestHandler->prefers('rss'));
  856. $this->Controller->request = $this->request->withEnv('HTTP_ACCEPT', null);
  857. $this->RequestHandler->ext = 'json';
  858. $this->assertFalse($this->RequestHandler->prefers('xml'));
  859. }
  860. /**
  861. * test that AJAX requests involving redirects trigger requestAction instead.
  862. *
  863. * @group deprecated
  864. * @return void
  865. * @triggers Controller.beforeRedirect $this->Controller
  866. */
  867. public function testAjaxRedirectAsRequestAction()
  868. {
  869. $this->deprecated(function () {
  870. static::setAppNamespace();
  871. Router::connect('/:controller/:action');
  872. $event = new Event('Controller.beforeRedirect', $this->Controller);
  873. $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
  874. $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
  875. ->setMethods(['is'])
  876. ->getMock();
  877. $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
  878. ->setMethods(['_sendHeader', 'stop'])
  879. ->getMock();
  880. $this->Controller->request->expects($this->any())
  881. ->method('is')
  882. ->will($this->returnValue(true));
  883. $response = $this->RequestHandler->beforeRedirect(
  884. $event,
  885. ['controller' => 'RequestHandlerTest', 'action' => 'destination'],
  886. $this->Controller->response
  887. );
  888. $this->assertRegExp('/posts index/', $response->body(), 'RequestAction redirect failed.');
  889. });
  890. }
  891. /**
  892. * Test that AJAX requests involving redirects handle querystrings
  893. *
  894. * @group deprecated
  895. * @return void
  896. * @triggers Controller.beforeRedirect $this->Controller
  897. */
  898. public function testAjaxRedirectAsRequestActionWithQueryString()
  899. {
  900. $this->deprecated(function () {
  901. static::setAppNamespace();
  902. Router::connect('/:controller/:action');
  903. $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
  904. $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
  905. ->setMethods(['is'])
  906. ->getMock();
  907. $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
  908. ->setMethods(['_sendHeader', 'stop'])
  909. ->getMock();
  910. $this->Controller->request->expects($this->any())
  911. ->method('is')
  912. ->with('ajax')
  913. ->will($this->returnValue(true));
  914. $event = new Event('Controller.beforeRedirect', $this->Controller);
  915. $response = $this->RequestHandler->beforeRedirect(
  916. $event,
  917. '/request_action/params_pass?a=b&x=y?ish',
  918. $this->Controller->response
  919. );
  920. $data = json_decode($response, true);
  921. $this->assertEquals('/request_action/params_pass', $data['here']);
  922. $response = $this->RequestHandler->beforeRedirect(
  923. $event,
  924. '/request_action/query_pass?a=b&x=y?ish',
  925. $this->Controller->response
  926. );
  927. $data = json_decode($response, true);
  928. $this->assertEquals('y?ish', $data['x']);
  929. });
  930. }
  931. /**
  932. * Test that AJAX requests involving redirects handle cookie data
  933. *
  934. * @group deprecated
  935. * @return void
  936. * @triggers Controller.beforeRedirect $this->Controller
  937. */
  938. public function testAjaxRedirectAsRequestActionWithCookieData()
  939. {
  940. $this->deprecated(function () {
  941. static::setAppNamespace();
  942. Router::connect('/:controller/:action');
  943. $event = new Event('Controller.beforeRedirect', $this->Controller);
  944. $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
  945. $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
  946. ->setMethods(['is'])
  947. ->getMock();
  948. $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
  949. ->setMethods(['_sendHeader', 'stop'])
  950. ->getMock();
  951. $this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true));
  952. $cookies = [
  953. 'foo' => 'bar'
  954. ];
  955. $this->Controller->request->cookies = $cookies;
  956. $response = $this->RequestHandler->beforeRedirect(
  957. $event,
  958. '/request_action/cookie_pass',
  959. $this->Controller->response
  960. );
  961. $data = json_decode($response, true);
  962. $this->assertEquals($cookies, $data);
  963. });
  964. }
  965. /**
  966. * Tests that AJAX requests involving redirects don't let the status code bleed through.
  967. *
  968. * @group deprecated
  969. * @return void
  970. * @triggers Controller.beforeRedirect $this->Controller
  971. */
  972. public function testAjaxRedirectAsRequestActionStatusCode()
  973. {
  974. $this->deprecated(function () {
  975. static::setAppNamespace();
  976. Router::connect('/:controller/:action');
  977. $event = new Event('Controller.beforeRedirect', $this->Controller);
  978. $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
  979. $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
  980. ->setMethods(['is'])
  981. ->getMock();
  982. $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
  983. ->setMethods(['_sendHeader', 'stop'])
  984. ->getMock();
  985. $this->Controller->response->statusCode(302);
  986. $this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true));
  987. $response = $this->RequestHandler->beforeRedirect(
  988. $event,
  989. ['controller' => 'RequestHandlerTest', 'action' => 'destination'],
  990. $this->Controller->response
  991. );
  992. $this->assertRegExp('/posts index/', $response->body(), 'RequestAction redirect failed.');
  993. $this->assertSame(200, $response->statusCode());
  994. });
  995. }
  996. /**
  997. * test that ajax requests involving redirects don't force no layout
  998. * this would cause the ajax layout to not be rendered.
  999. *
  1000. * @group deprecated
  1001. * @return void
  1002. * @triggers Controller.beforeRedirect $this->Controller
  1003. */
  1004. public function testAjaxRedirectAsRequestActionStillRenderingLayout()
  1005. {
  1006. $this->deprecated(function () {
  1007. static::setAppNamespace();
  1008. Router::connect('/:controller/:action');
  1009. $event = new Event('Controller.beforeRedirect', $this->Controller);
  1010. $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
  1011. $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
  1012. ->setMethods(['is'])
  1013. ->getMock();
  1014. $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
  1015. ->setMethods(['_sendHeader', 'stop'])
  1016. ->getMock();
  1017. $this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true));
  1018. $response = $this->RequestHandler->beforeRedirect(
  1019. $event,
  1020. ['controller' => 'RequestHandlerTest', 'action' => 'ajax2_layout'],
  1021. $this->Controller->response
  1022. );
  1023. $this->assertRegExp('/posts index/', $response->body(), 'RequestAction redirect failed.');
  1024. $this->assertRegExp('/Ajax!/', $response->body(), 'Layout was not rendered.');
  1025. });
  1026. }
  1027. /**
  1028. * test that the beforeRedirect callback properly converts
  1029. * array URLs into their correct string ones, and adds base => false so
  1030. * the correct URLs are generated.
  1031. *
  1032. * @group deprecated
  1033. * @return void
  1034. * @triggers Controller.beforeRender $this->Controller
  1035. */
  1036. public function testBeforeRedirectCallbackWithArrayUrl()
  1037. {
  1038. $this->deprecated(function () {
  1039. static::setAppNamespace();
  1040. Router::connect('/:controller/:action/*');
  1041. $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
  1042. $event = new Event('Controller.beforeRender', $this->Controller);
  1043. Router::setRequestInfo([
  1044. ['plugin' => null, 'controller' => 'accounts', 'action' => 'index', 'pass' => []],
  1045. ['base' => '', 'here' => '/accounts/', 'webroot' => '/']
  1046. ]);
  1047. $RequestHandler = new RequestHandlerComponent($this->Controller->components());
  1048. $this->Controller->request = new ServerRequest('posts/index');
  1049. ob_start();
  1050. $RequestHandler->beforeRedirect(
  1051. $event,
  1052. ['controller' => 'RequestHandlerTest', 'action' => 'param_method', 'first', 'second'],
  1053. $this->Controller->response
  1054. );
  1055. $result = ob_get_clean();
  1056. $this->assertEquals('one: first two: second', $result);
  1057. });
  1058. }
  1059. /**
  1060. * testAddInputTypeException method
  1061. *
  1062. * @group deprecated
  1063. * @return void
  1064. */
  1065. public function testAddInputTypeException()
  1066. {
  1067. $this->expectException(\Cake\Core\Exception\Exception::class);
  1068. $this->deprecated(function () {
  1069. $this->RequestHandler->addInputType('csv', ['I am not callable']);
  1070. });
  1071. }
  1072. /**
  1073. * Test checkNotModified method
  1074. *
  1075. * @return void
  1076. * @triggers Controller.beforeRender $this->Controller
  1077. */
  1078. public function testCheckNotModifiedByEtagStar()
  1079. {
  1080. $response = new Response();
  1081. $response = $response->withEtag('something')
  1082. ->withHeader('Content-Type', 'text/plain')
  1083. ->withStringBody('keeper');
  1084. $this->Controller->response = $response;
  1085. $this->Controller->request = $this->request->withHeader('If-None-Match', '*');
  1086. $event = new Event('Controller.beforeRender', $this->Controller);
  1087. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  1088. $this->assertFalse($requestHandler->beforeRender($event));
  1089. $this->assertEquals(304, $this->Controller->response->getStatusCode());
  1090. $this->assertEquals('', (string)$this->Controller->response->getBody());
  1091. $this->assertFalse($this->Controller->response->hasHeader('Content-Type'), 'header should not be removed.');
  1092. }
  1093. /**
  1094. * Test checkNotModified method
  1095. *
  1096. * @return void
  1097. * @triggers Controller.beforeRender
  1098. */
  1099. public function testCheckNotModifiedByEtagExact()
  1100. {
  1101. $response = new Response();
  1102. $response = $response->withEtag('something', true)
  1103. ->withHeader('Content-Type', 'text/plain')
  1104. ->withStringBody('keeper');
  1105. $this->Controller->response = $response;
  1106. $this->Controller->request = $this->request->withHeader('If-None-Match', 'W/"something", "other"');
  1107. $event = new Event('Controller.beforeRender', $this->Controller);
  1108. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  1109. $this->assertFalse($requestHandler->beforeRender($event));
  1110. $this->assertEquals(304, $this->Controller->response->getStatusCode());
  1111. $this->assertEquals('', (string)$this->Controller->response->getBody());
  1112. $this->assertFalse($this->Controller->response->hasHeader('Content-Type'));
  1113. }
  1114. /**
  1115. * Test checkNotModified method
  1116. *
  1117. * @return void
  1118. * @triggers Controller.beforeRender $this->Controller
  1119. */
  1120. public function testCheckNotModifiedByEtagAndTime()
  1121. {
  1122. $this->Controller->request = $this->request
  1123. ->withHeader('If-None-Match', 'W/"something", "other"')
  1124. ->withHeader('If-Modified-Since', '2012-01-01 00:00:00');
  1125. $response = new Response();
  1126. $response = $response->withEtag('something', true)
  1127. ->withHeader('Content-type', 'text/plain')
  1128. ->withStringBody('should be removed')
  1129. ->withModified('2012-01-01 00:00:00');
  1130. $this->Controller->response = $response;
  1131. $event = new Event('Controller.beforeRender', $this->Controller);
  1132. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  1133. $this->assertFalse($requestHandler->beforeRender($event));
  1134. $this->assertEquals(304, $this->Controller->response->getStatusCode());
  1135. $this->assertEquals('', (string)$this->Controller->response->getBody());
  1136. $this->assertFalse($this->Controller->response->hasHeader('Content-type'));
  1137. }
  1138. /**
  1139. * Test checkNotModified method
  1140. *
  1141. * @return void
  1142. * @triggers Controller.beforeRender $this->Controller
  1143. */
  1144. public function testCheckNotModifiedNoInfo()
  1145. {
  1146. $response = $this->getMockBuilder('Cake\Http\Response')
  1147. ->setMethods(['notModified', 'stop'])
  1148. ->getMock();
  1149. $response->expects($this->never())->method('notModified');
  1150. $this->Controller->response = $response;
  1151. $event = new Event('Controller.beforeRender', $this->Controller);
  1152. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  1153. $this->assertNull($requestHandler->beforeRender($event));
  1154. }
  1155. /**
  1156. * Test default options in construction
  1157. *
  1158. * @return void
  1159. */
  1160. public function testConstructDefaultOptions()
  1161. {
  1162. $requestHandler = new RequestHandlerComponent($this->Controller->components());
  1163. $viewClass = $requestHandler->getConfig('viewClassMap');
  1164. $expected = [
  1165. 'json' => 'Json',
  1166. 'xml' => 'Xml',
  1167. 'ajax' => 'Ajax',
  1168. ];
  1169. $this->assertEquals($expected, $viewClass);
  1170. $inputs = $requestHandler->getConfig('inputTypeMap');
  1171. $this->assertArrayHasKey('json', $inputs);
  1172. $this->assertArrayHasKey('xml', $inputs);
  1173. }
  1174. /**
  1175. * Test options in constructor replace defaults
  1176. *
  1177. * @return void
  1178. */
  1179. public function testConstructReplaceOptions()
  1180. {
  1181. $requestHandler = new RequestHandlerComponent(
  1182. $this->Controller->components(),
  1183. [
  1184. 'viewClassMap' => ['json' => 'Json'],
  1185. 'inputTypeMap' => ['json' => ['json_decode', true]]
  1186. ]
  1187. );
  1188. $viewClass = $requestHandler->getConfig('viewClassMap');
  1189. $expected = [
  1190. 'json' => 'Json',
  1191. ];
  1192. $this->assertEquals($expected, $viewClass);
  1193. $inputs = $requestHandler->getConfig('inputTypeMap');
  1194. $this->assertArrayHasKey('json', $inputs);
  1195. $this->assertCount(1, $inputs);
  1196. }
  1197. /**
  1198. * test beforeRender() doesn't override response type set in controller action
  1199. *
  1200. * @return void
  1201. */
  1202. public function testBeforeRender()
  1203. {
  1204. $this->Controller->set_response_type();
  1205. $event = new Event('Controller.beforeRender', $this->Controller);
  1206. $this->RequestHandler->beforeRender($event);
  1207. $this->assertEquals('text/plain', $this->Controller->response->getType());
  1208. }
  1209. /**
  1210. * tests beforeRender automatically uses renderAs when a supported extension is found
  1211. *
  1212. * @return void
  1213. */
  1214. public function testBeforeRenderAutoRenderAs()
  1215. {
  1216. $this->Controller->setRequest($this->request->withParam('_ext', 'csv'));
  1217. $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller));
  1218. $event = new Event('Controller.beforeRender', $this->Controller);
  1219. $this->RequestHandler->beforeRender($event);
  1220. $this->assertEquals('text/csv', $this->Controller->response->getType());
  1221. }
  1222. }