RequestHandlerComponentTest.php 48 KB

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