ViewTest.php 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 1.2.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\View;
  17. use Cake\Cache\Cache;
  18. use Cake\Controller\Controller;
  19. use Cake\Core\App;
  20. use Cake\Core\Configure;
  21. use Cake\Core\Plugin;
  22. use Cake\Event\EventInterface;
  23. use Cake\Http\ServerRequest;
  24. use Cake\TestSuite\TestCase;
  25. use Cake\View\View;
  26. use RuntimeException;
  27. use TestApp\Controller\ThemePostsController;
  28. use TestApp\Controller\ViewPostsController;
  29. use TestApp\View\Helper\TestBeforeAfterHelper;
  30. use TestApp\View\Object\TestObjectWithoutToString;
  31. use TestApp\View\Object\TestObjectWithToString;
  32. use TestApp\View\TestView;
  33. use TestApp\View\TestViewEventListenerInterface;
  34. /**
  35. * ViewTest class
  36. */
  37. class ViewTest extends TestCase
  38. {
  39. /**
  40. * Fixtures used in this test.
  41. *
  42. * @var array
  43. */
  44. public $fixtures = ['core.Posts', 'core.Users'];
  45. /**
  46. * @var \Cake\View\View
  47. */
  48. public $View;
  49. /**
  50. * @var \TestApp\Controller\ViewPostsController
  51. */
  52. public $PostsController;
  53. /**
  54. * @var \TestApp\Controller\ThemePostsController
  55. */
  56. public $ThemePostsController;
  57. /**
  58. * setUp method
  59. *
  60. * @return void
  61. */
  62. public function setUp(): void
  63. {
  64. parent::setUp();
  65. $request = new ServerRequest();
  66. $this->Controller = new Controller($request);
  67. $this->PostsController = new ViewPostsController($request);
  68. $this->PostsController->index();
  69. $this->View = $this->PostsController->createView();
  70. $this->View->setTemplatePath('Posts');
  71. $themeRequest = new ServerRequest(['url' => 'posts/index']);
  72. $this->ThemeController = new Controller($themeRequest);
  73. $this->ThemePostsController = new ThemePostsController($themeRequest);
  74. $this->ThemePostsController->index();
  75. $this->ThemeView = $this->ThemePostsController->createView();
  76. $this->ThemeView->setTemplatePath('Posts');
  77. $this->loadPlugins(['TestPlugin', 'PluginJs', 'TestTheme', 'Company/TestPluginThree']);
  78. Configure::write('debug', true);
  79. }
  80. /**
  81. * tearDown method
  82. *
  83. * @return void
  84. */
  85. public function tearDown(): void
  86. {
  87. parent::tearDown();
  88. $this->clearPlugins();
  89. unset($this->View);
  90. unset($this->PostsController);
  91. unset($this->Controller);
  92. unset($this->ThemeView);
  93. unset($this->ThemePostsController);
  94. unset($this->ThemeController);
  95. }
  96. /**
  97. * Test getTemplateFileName method
  98. *
  99. * @return void
  100. */
  101. public function testGetTemplate()
  102. {
  103. $viewOptions = [
  104. 'plugin' => null,
  105. 'name' => 'Pages',
  106. 'templatePath' => 'Pages',
  107. ];
  108. $ThemeView = new TestView(null, null, null, $viewOptions);
  109. $ThemeView->setTheme('TestTheme');
  110. $expected = TEST_APP . 'templates' . DS . 'Pages' . DS . 'home.php';
  111. $result = $ThemeView->getTemplateFileName('home');
  112. $this->assertPathEquals($expected, $result);
  113. $expected = Plugin::path('TestTheme') . 'templates' . DS . 'Posts' . DS . 'index.php';
  114. $result = $ThemeView->getTemplateFileName('/Posts/index');
  115. $this->assertPathEquals($expected, $result);
  116. $expected = Plugin::path('TestTheme') . 'templates' . DS . 'layout' . DS . 'default.php';
  117. $result = $ThemeView->getLayoutFileName();
  118. $this->assertPathEquals($expected, $result);
  119. $ThemeView->setLayoutPath('rss');
  120. $expected = TEST_APP . 'templates' . DS . 'layout' . DS . 'rss' . DS . 'default.php';
  121. $result = $ThemeView->getLayoutFileName();
  122. $this->assertPathEquals($expected, $result);
  123. $ThemeView->setLayoutPath('email' . DS . 'html');
  124. $expected = TEST_APP . 'templates' . DS . 'layout' . DS . 'email' . DS . 'html' . DS . 'default.php';
  125. $result = $ThemeView->getLayoutFileName();
  126. $this->assertPathEquals($expected, $result);
  127. $ThemeView = new TestView(null, null, null, $viewOptions);
  128. $ThemeView->setTheme('Company/TestPluginThree');
  129. $expected = Plugin::path('Company/TestPluginThree') . 'templates' . DS . 'layout' . DS . 'default.php';
  130. $result = $ThemeView->getLayoutFileName();
  131. $this->assertPathEquals($expected, $result);
  132. }
  133. /**
  134. * Test getLayoutFileName method on plugin
  135. *
  136. * @return void
  137. */
  138. public function testPluginGetTemplate()
  139. {
  140. $viewOptions = ['plugin' => 'TestPlugin',
  141. 'name' => 'TestPlugin',
  142. 'templatePath' => 'Tests',
  143. 'template' => 'index',
  144. ];
  145. $View = new TestView(null, null, null, $viewOptions);
  146. $expected = Plugin::path('TestPlugin') . 'templates' . DS . 'Tests' . DS . 'index.php';
  147. $result = $View->getTemplateFileName('index');
  148. $this->assertEquals($expected, $result);
  149. $expected = Plugin::path('TestPlugin') . 'templates' . DS . 'layout' . DS . 'default.php';
  150. $result = $View->getLayoutFileName();
  151. $this->assertEquals($expected, $result);
  152. }
  153. /**
  154. * Test that plugin files with absolute file paths are scoped
  155. * to the plugin and do now allow any file path.
  156. *
  157. * @return void
  158. */
  159. public function testPluginGetTemplateAbsoluteFail()
  160. {
  161. $this->expectException(\Cake\View\Exception\MissingTemplateException::class);
  162. $viewOptions = [
  163. 'plugin' => null,
  164. 'name' => 'Pages',
  165. 'viewPath' => 'Pages',
  166. ];
  167. $view = new TestView(null, null, null, $viewOptions);
  168. $expected = TEST_APP . 'Plugin' . DS . 'Company' . DS . 'TestPluginThree' . DS . 'templates' . DS . 'Pages' . DS . 'index.php';
  169. $result = $view->getTemplateFileName('Company/TestPluginThree./Pages/index');
  170. $this->assertPathEquals($expected, $result);
  171. $view->getTemplateFileName('Company/TestPluginThree./etc/passwd');
  172. }
  173. /**
  174. * Test getTemplateFileName method on plugin
  175. *
  176. * @return void
  177. */
  178. public function testPluginThemedGetTemplate()
  179. {
  180. $viewOptions = ['plugin' => 'TestPlugin',
  181. 'name' => 'TestPlugin',
  182. 'templatePath' => 'Tests',
  183. 'template' => 'index',
  184. 'theme' => 'TestTheme',
  185. ];
  186. $ThemeView = new TestView(null, null, null, $viewOptions);
  187. $themePath = Plugin::path('TestTheme') . 'templates' . DS;
  188. $expected = $themePath . 'plugin' . DS . 'TestPlugin' . DS . 'Tests' . DS . 'index.php';
  189. $result = $ThemeView->getTemplateFileName('index');
  190. $this->assertPathEquals($expected, $result);
  191. $expected = $themePath . 'plugin' . DS . 'TestPlugin' . DS . 'layout' . DS . 'plugin_default.php';
  192. $result = $ThemeView->getLayoutFileName('plugin_default');
  193. $this->assertPathEquals($expected, $result);
  194. $expected = $themePath . 'layout' . DS . 'default.php';
  195. $result = $ThemeView->getLayoutFileName('default');
  196. $this->assertPathEquals($expected, $result);
  197. }
  198. /**
  199. * Test that plugin/$plugin_name is only appended to the paths it should be.
  200. *
  201. * @return void
  202. */
  203. public function testPathPluginGeneration()
  204. {
  205. $viewOptions = ['plugin' => 'TestPlugin',
  206. 'name' => 'TestPlugin',
  207. 'viewPath' => 'Tests',
  208. 'view' => 'index',
  209. ];
  210. $View = new TestView(null, null, null, $viewOptions);
  211. $paths = $View->paths();
  212. $expected = array_merge(App::path('templates'), App::core('templates'));
  213. $this->assertEquals($expected, $paths);
  214. $paths = $View->paths('TestPlugin');
  215. $pluginPath = Plugin::path('TestPlugin');
  216. $expected = [
  217. TEST_APP . 'templates' . DS . 'plugin' . DS . 'TestPlugin' . DS,
  218. $pluginPath . 'templates' . DS,
  219. TEST_APP . 'templates' . DS,
  220. CORE_PATH . 'templates' . DS,
  221. ];
  222. $this->assertPathEquals($expected, $paths);
  223. }
  224. /**
  225. * Test that themed plugin paths are generated correctly.
  226. *
  227. * @return void
  228. */
  229. public function testPathThemedPluginGeneration()
  230. {
  231. $viewOptions = ['plugin' => 'TestPlugin',
  232. 'name' => 'TestPlugin',
  233. 'viewPath' => 'Tests',
  234. 'view' => 'index',
  235. 'theme' => 'TestTheme',
  236. ];
  237. $View = new TestView(null, null, null, $viewOptions);
  238. $paths = $View->paths('TestPlugin');
  239. $pluginPath = Plugin::path('TestPlugin');
  240. $themePath = Plugin::path('TestTheme');
  241. $expected = [
  242. $themePath . 'templates' . DS . 'plugin' . DS . 'TestPlugin' . DS,
  243. $themePath . 'templates' . DS,
  244. TEST_APP . 'templates' . DS . 'plugin' . DS . 'TestPlugin' . DS,
  245. $pluginPath . 'templates' . DS,
  246. TEST_APP . 'templates' . DS,
  247. CORE_PATH . 'templates' . DS,
  248. ];
  249. $this->assertPathEquals($expected, $paths);
  250. }
  251. /**
  252. * Test that multiple paths can be used in App.paths.templates.
  253. *
  254. * @return void
  255. */
  256. public function testMultipleAppPaths()
  257. {
  258. $viewOptions = ['plugin' => 'TestPlugin',
  259. 'name' => 'TestPlugin',
  260. 'viewPath' => 'Tests',
  261. 'view' => 'index',
  262. 'theme' => 'TestTheme',
  263. ];
  264. $paths = Configure::read('App.paths.templates');
  265. $paths[] = Plugin::path('TestPlugin') . 'templates' . DS;
  266. Configure::write('App.paths.templates', $paths);
  267. $View = new TestView(null, null, null, $viewOptions);
  268. $paths = $View->paths('TestPlugin');
  269. $pluginPath = Plugin::path('TestPlugin');
  270. $themePath = Plugin::path('TestTheme');
  271. $expected = [
  272. $themePath . 'templates' . DS . 'plugin' . DS . 'TestPlugin' . DS,
  273. $themePath . 'templates' . DS,
  274. TEST_APP . 'templates' . DS . 'plugin' . DS . 'TestPlugin' . DS,
  275. $pluginPath . 'templates' . DS . 'plugin' . DS . 'TestPlugin' . DS,
  276. $pluginPath . 'templates' . DS,
  277. TEST_APP . 'templates' . DS,
  278. TEST_APP . 'Plugin' . DS . 'TestPlugin' . DS . 'templates' . DS,
  279. CORE_PATH . 'templates' . DS,
  280. ];
  281. $this->assertPathEquals($expected, $paths);
  282. }
  283. /**
  284. * Test that CamelCase'd plugins still find their view files.
  285. *
  286. * @return void
  287. */
  288. public function testCamelCasePluginGetTemplate()
  289. {
  290. $viewOptions = ['plugin' => 'TestPlugin',
  291. 'name' => 'TestPlugin',
  292. 'templatePath' => 'Tests',
  293. 'template' => 'index',
  294. ];
  295. $View = new TestView(null, null, null, $viewOptions);
  296. $pluginPath = Plugin::path('TestPlugin');
  297. $expected = TEST_APP . 'Plugin' . DS . 'TestPlugin' . DS . 'templates' . DS .
  298. 'Tests' . DS . 'index.php';
  299. $result = $View->getTemplateFileName('index');
  300. $this->assertPathEquals($expected, $result);
  301. $expected = $pluginPath . 'templates' . DS . 'layout' . DS . 'default.php';
  302. $result = $View->getLayoutFileName();
  303. $this->assertPathEquals($expected, $result);
  304. }
  305. /**
  306. * Test getTemplateFileName method
  307. *
  308. * @return void
  309. */
  310. public function testGetViewFileNames()
  311. {
  312. $viewOptions = [
  313. 'plugin' => null,
  314. 'name' => 'Pages',
  315. 'templatePath' => 'Pages',
  316. ];
  317. $request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
  318. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  319. $View = new TestView(null, null, null, $viewOptions);
  320. $expected = TEST_APP . 'templates' . DS . 'Pages' . DS . 'home.php';
  321. $result = $View->getTemplateFileName('home');
  322. $this->assertPathEquals($expected, $result);
  323. $expected = TEST_APP . 'templates' . DS . 'Posts' . DS . 'index.php';
  324. $result = $View->getTemplateFileName('/Posts/index');
  325. $this->assertPathEquals($expected, $result);
  326. $expected = TEST_APP . 'templates' . DS . 'Posts' . DS . 'index.php';
  327. $result = $View->getTemplateFileName('../Posts/index');
  328. $this->assertPathEquals($expected, $result);
  329. $expected = TEST_APP . 'templates' . DS . 'Pages' . DS . 'page.home.php';
  330. $result = $View->getTemplateFileName('page.home');
  331. $this->assertPathEquals($expected, $result, 'Should not ruin files with dots.');
  332. $expected = TEST_APP . 'templates' . DS . 'Pages' . DS . 'home.php';
  333. $result = $View->getTemplateFileName('TestPlugin.home');
  334. $this->assertPathEquals($expected, $result, 'Plugin is missing the view, cascade to app.');
  335. $View->setTemplatePath('Tests');
  336. $expected = TEST_APP . 'Plugin' . DS . 'TestPlugin' . DS . 'templates' . DS .
  337. 'Tests' . DS . 'index.php';
  338. $result = $View->getTemplateFileName('TestPlugin.index');
  339. $this->assertPathEquals($expected, $result);
  340. }
  341. /**
  342. * Test that getTemplateFileName() protects against malicious directory traversal.
  343. *
  344. * @return void
  345. */
  346. public function testGetViewFileNameDirectoryTraversal()
  347. {
  348. $this->expectException(\InvalidArgumentException::class);
  349. $viewOptions = [
  350. 'plugin' => null,
  351. 'name' => 'Pages',
  352. 'templatePath' => 'Pages',
  353. ];
  354. $request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
  355. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  356. $view = new TestView(null, null, null, $viewOptions);
  357. $view->ext('.php');
  358. $view->getTemplateFileName('../../../bootstrap');
  359. }
  360. /**
  361. * Test getTemplateFileName doesn't re-apply existing subdirectories
  362. *
  363. * @return void
  364. */
  365. public function testGetViewFileNameSubDir()
  366. {
  367. $viewOptions = [
  368. 'plugin' => null,
  369. 'name' => 'Posts',
  370. 'templatePath' => 'Posts/json',
  371. 'layoutPath' => 'json',
  372. ];
  373. $view = new TestView(null, null, null, $viewOptions);
  374. $expected = TEST_APP . 'templates' . DS . 'Posts' . DS . 'json' . DS . 'index.php';
  375. $result = $view->getTemplateFileName('index');
  376. $this->assertPathEquals($expected, $result);
  377. $view->setSubDir('json');
  378. $result = $view->getTemplateFileName('index');
  379. $expected = TEST_APP . 'templates' . DS . 'Posts' . DS . 'json' . DS . 'index.php';
  380. $this->assertPathEquals($expected, $result);
  381. }
  382. /**
  383. * Test getTemplateFileName applies subdirectories on equal length names
  384. *
  385. * @return void
  386. */
  387. public function testGetViewFileNameSubDirLength()
  388. {
  389. $viewOptions = [
  390. 'plugin' => null,
  391. 'name' => 'Jobs',
  392. 'templatePath' => 'Jobs',
  393. 'layoutPath' => 'json',
  394. ];
  395. $view = new TestView(null, null, null, $viewOptions);
  396. $view->setSubDir('json');
  397. $result = $view->getTemplateFileName('index');
  398. $expected = TEST_APP . 'templates' . DS . 'Jobs' . DS . 'json' . DS . 'index.php';
  399. $this->assertPathEquals($expected, $result);
  400. }
  401. /**
  402. * Test getting layout filenames
  403. *
  404. * @return void
  405. */
  406. public function testGetLayoutFileName()
  407. {
  408. $viewOptions = ['plugin' => null,
  409. 'name' => 'Pages',
  410. 'viewPath' => 'Pages',
  411. 'action' => 'display',
  412. ];
  413. $View = new TestView(null, null, null, $viewOptions);
  414. $expected = TEST_APP . 'templates' . DS . 'layout' . DS . 'default.php';
  415. $result = $View->getLayoutFileName();
  416. $this->assertPathEquals($expected, $result);
  417. $View->setLayoutPath('rss');
  418. $expected = TEST_APP . 'templates' . DS . 'layout' . DS . 'rss' . DS . 'default.php';
  419. $result = $View->getLayoutFileName();
  420. $this->assertPathEquals($expected, $result);
  421. $View->setLayoutPath('email' . DS . 'html');
  422. $expected = TEST_APP . 'templates' . DS . 'layout' . DS . 'email' . DS . 'html' . DS . 'default.php';
  423. $result = $View->getLayoutFileName();
  424. $this->assertPathEquals($expected, $result);
  425. }
  426. /**
  427. * Test getting layout filenames for plugins.
  428. *
  429. * @return void
  430. */
  431. public function testGetLayoutFileNamePlugin()
  432. {
  433. $viewOptions = ['plugin' => null,
  434. 'name' => 'Pages',
  435. 'viewPath' => 'Pages',
  436. 'action' => 'display',
  437. ];
  438. $View = new TestView(null, null, null, $viewOptions);
  439. $expected = TEST_APP . 'Plugin' . DS . 'TestPlugin' . DS . 'templates' . DS .
  440. 'layout' . DS . 'default.php';
  441. $result = $View->getLayoutFileName('TestPlugin.default');
  442. $this->assertPathEquals($expected, $result);
  443. $View->setRequest($View->getRequest()->withParam('plugin', 'TestPlugin'));
  444. $expected = TEST_APP . 'Plugin' . DS . 'TestPlugin' . DS . 'templates' . DS .
  445. 'layout' . DS . 'default.php';
  446. $result = $View->getLayoutFileName('default');
  447. $this->assertPathEquals($expected, $result);
  448. }
  449. /**
  450. * Test getting layout filenames for prefix
  451. *
  452. * @return void
  453. */
  454. public function testGetLayoutFileNamePrefix()
  455. {
  456. $View = new TestView();
  457. // Prefix specific layout
  458. $View->setRequest($View->getRequest()->withParam('prefix', 'foo_prefix'));
  459. $expected = TEST_APP . 'templates' . DS .
  460. 'FooPrefix' . DS . 'layout' . DS . 'default.php';
  461. $result = $View->getLayoutFileName();
  462. $this->assertPathEquals($expected, $result);
  463. $View->setRequest($View->getRequest()->withParam('prefix', 'FooPrefix'));
  464. $result = $View->getLayoutFileName();
  465. $this->assertPathEquals($expected, $result);
  466. // Nested prefix layout
  467. $View->setRequest($View->getRequest()->withParam('prefix', 'foo_prefix/bar_prefix'));
  468. $expected = TEST_APP . 'templates' . DS .
  469. 'FooPrefix' . DS . 'BarPrefix' . DS . 'layout' . DS . 'default.php';
  470. $result = $View->getLayoutFileName();
  471. $this->assertPathEquals($expected, $result);
  472. $expected = TEST_APP . 'templates' . DS .
  473. 'FooPrefix' . DS . 'layout' . DS . 'nested_prefix_cascade.php';
  474. $result = $View->getLayoutFileName('nested_prefix_cascade');
  475. $this->assertPathEquals($expected, $result);
  476. // Fallback to app's layout
  477. $View->setRequest($View->getRequest()->withParam('prefix', 'Admin'));
  478. $expected = TEST_APP . 'templates' . DS .
  479. 'layout' . DS . 'default.php';
  480. $result = $View->getLayoutFileName();
  481. $this->assertPathEquals($expected, $result);
  482. }
  483. /**
  484. * Test that getLayoutFileName() protects against malicious directory traversal.
  485. *
  486. * @return void
  487. */
  488. public function testGetLayoutFileNameDirectoryTraversal()
  489. {
  490. $this->expectException(\InvalidArgumentException::class);
  491. $viewOptions = [
  492. 'plugin' => null,
  493. 'name' => 'Pages',
  494. 'viewPath' => 'Pages',
  495. ];
  496. $request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
  497. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  498. $view = new TestView(null, null, null, $viewOptions);
  499. $view->ext('.php');
  500. $view->getLayoutFileName('../../../bootstrap');
  501. }
  502. /**
  503. * Test for missing views
  504. *
  505. * @return void
  506. */
  507. public function testMissingTemplate()
  508. {
  509. $this->expectException(\Cake\View\Exception\MissingTemplateException::class);
  510. $this->expectExceptionMessage("Template file 'does_not_exist' could not be found");
  511. $this->expectExceptionMessage('The following paths were searched');
  512. $this->expectExceptionMessage('- ' . ROOT . DS . 'templates');
  513. $viewOptions = ['plugin' => null,
  514. 'name' => 'Pages',
  515. 'viewPath' => 'Pages',
  516. ];
  517. $request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
  518. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  519. $View = new TestView($request, $response, null, $viewOptions);
  520. $View->getTemplateFileName('does_not_exist');
  521. }
  522. /**
  523. * Test for missing layouts
  524. *
  525. * @return void
  526. */
  527. public function testMissingLayout()
  528. {
  529. $this->expectException(\Cake\View\Exception\MissingLayoutException::class);
  530. $this->expectExceptionMessage("Layout file 'whatever' could not be found");
  531. $this->expectExceptionMessage('The following paths were searched');
  532. $this->expectExceptionMessage('- ' . ROOT . DS . 'templates' . DS . 'layout');
  533. $viewOptions = ['plugin' => null,
  534. 'name' => 'Pages',
  535. 'viewPath' => 'Pages',
  536. 'layout' => 'whatever',
  537. ];
  538. $View = new TestView(null, null, null, $viewOptions);
  539. $View->getLayoutFileName();
  540. }
  541. /**
  542. * Test viewVars method
  543. *
  544. * @return void
  545. */
  546. public function testViewVars()
  547. {
  548. $this->assertEquals(['testData', 'test2', 'test3'], $this->View->getVars());
  549. }
  550. /**
  551. * Test elementExists method
  552. *
  553. * @return void
  554. */
  555. public function testElementExists()
  556. {
  557. $result = $this->View->elementExists('test_element');
  558. $this->assertTrue($result);
  559. $result = $this->View->elementExists('TestPlugin.plugin_element');
  560. $this->assertTrue($result);
  561. $result = $this->View->elementExists('non_existent_element');
  562. $this->assertFalse($result);
  563. $result = $this->View->elementExists('TestPlugin.element');
  564. $this->assertFalse($result);
  565. $this->View->setRequest($this->View->getRequest()->withParam('plugin', 'TestPlugin'));
  566. $result = $this->View->elementExists('plugin_element');
  567. $this->assertTrue($result);
  568. }
  569. /**
  570. * Test element method
  571. *
  572. * @return void
  573. */
  574. public function testElement()
  575. {
  576. $result = $this->View->element('test_element');
  577. $this->assertSame('this is the test element', $result);
  578. $result = $this->View->element('TestPlugin.plugin_element');
  579. $this->assertEquals("Element in the TestPlugin\n", $result);
  580. $this->View->setRequest($this->View->getRequest()->withParam('plugin', 'TestPlugin'));
  581. $result = $this->View->element('plugin_element');
  582. $this->assertEquals("Element in the TestPlugin\n", $result);
  583. $result = $this->View->element('plugin_element', [], ['plugin' => false]);
  584. $this->assertEquals("Plugin element overridden in app\n", $result);
  585. }
  586. /**
  587. * Test element method with a prefix
  588. *
  589. * @return void
  590. */
  591. public function testPrefixElement()
  592. {
  593. $this->View->setRequest($this->View->getRequest()->withParam('prefix', 'Admin'));
  594. $result = $this->View->element('prefix_element');
  595. $this->assertSame('this is a prefixed test element', $result);
  596. $result = $this->View->element('TestPlugin.plugin_element');
  597. $this->assertSame('this is the plugin prefixed element using params[plugin]', $result);
  598. $this->View->setRequest($this->View->getRequest()->withParam('plugin', 'TestPlugin'));
  599. $result = $this->View->element('test_plugin_element');
  600. $this->assertSame('this is the test set using View::$plugin plugin prefixed element', $result);
  601. $this->View->setRequest($this->View->getRequest()->withParam('prefix', 'FooPrefix/BarPrefix'));
  602. $result = $this->View->element('prefix_element');
  603. $this->assertSame('this is a nested prefixed test element', $result);
  604. $result = $this->View->element('prefix_element_in_parent');
  605. $this->assertSame('this is a nested prefixed test element in first level element', $result);
  606. }
  607. /**
  608. * Test loading missing view element
  609. *
  610. * @return void
  611. */
  612. public function testElementMissing()
  613. {
  614. $this->expectException(\Cake\View\Exception\MissingElementException::class);
  615. $this->expectExceptionMessage("Element file 'non_existent_element' could not be found");
  616. $this->View->element('non_existent_element');
  617. }
  618. /**
  619. * Test loading non-existent plugin view element
  620. *
  621. * @return void
  622. */
  623. public function testElementMissingPluginElement()
  624. {
  625. $this->expectException(\Cake\View\Exception\MissingElementException::class);
  626. $this->expectExceptionMessage("Element file 'TestPlugin.nope' could not be found");
  627. $this->View->element('TestPlugin.nope');
  628. }
  629. /**
  630. * Test that elements can have callbacks
  631. *
  632. * @return void
  633. */
  634. public function testElementCallbacks()
  635. {
  636. $count = 0;
  637. $callback = function (EventInterface $event, $file) use (&$count) {
  638. $count++;
  639. };
  640. $events = $this->View->getEventManager();
  641. $events->on('View.beforeRender', $callback);
  642. $events->on('View.afterRender', $callback);
  643. $this->View->element('test_element', [], ['callbacks' => true]);
  644. $this->assertEquals(2, $count);
  645. }
  646. /**
  647. * Test that additional element viewVars don't get overwritten with helpers.
  648. *
  649. * @return void
  650. */
  651. public function testElementParamsDontOverwriteHelpers()
  652. {
  653. $Controller = new ViewPostsController();
  654. $View = $Controller->createView();
  655. $result = $View->element('type_check', ['form' => 'string'], ['callbacks' => true]);
  656. $this->assertSame('string', $result);
  657. $View->set('form', 'string');
  658. $result = $View->element('type_check', [], ['callbacks' => true]);
  659. $this->assertSame('string', $result);
  660. }
  661. /**
  662. * Test elementCacheHelperNoCache method
  663. *
  664. * @return void
  665. */
  666. public function testElementCacheHelperNoCache()
  667. {
  668. $Controller = new ViewPostsController();
  669. $View = $Controller->createView();
  670. $result = $View->element('test_element', ['ram' => 'val', 'test' => ['foo', 'bar']]);
  671. $this->assertSame('this is the test element', $result);
  672. }
  673. /**
  674. * Test elementCache method
  675. *
  676. * @return void
  677. */
  678. public function testElementCache()
  679. {
  680. Cache::drop('test_view');
  681. Cache::setConfig('test_view', [
  682. 'engine' => 'File',
  683. 'duration' => '+1 day',
  684. 'path' => CACHE . 'views/',
  685. 'prefix' => '',
  686. ]);
  687. Cache::clear('test_view');
  688. $View = $this->PostsController->createView();
  689. $View->setElementCache('test_view');
  690. $result = $View->element('test_element', [], ['cache' => true]);
  691. $expected = 'this is the test element';
  692. $this->assertEquals($expected, $result);
  693. $result = Cache::read('element__test_element', 'test_view');
  694. $this->assertEquals($expected, $result);
  695. $result = $View->element('test_element', ['param' => 'one', 'foo' => 'two'], ['cache' => true]);
  696. $this->assertEquals($expected, $result);
  697. $result = Cache::read('element__test_element_param_foo', 'test_view');
  698. $this->assertEquals($expected, $result);
  699. $View->element('test_element', [
  700. 'param' => 'one',
  701. 'foo' => 'two',
  702. ], [
  703. 'cache' => ['key' => 'custom_key'],
  704. ]);
  705. $result = Cache::read('element_custom_key', 'test_view');
  706. $this->assertEquals($expected, $result);
  707. $View->setElementCache('default');
  708. $View->element('test_element', [
  709. 'param' => 'one',
  710. 'foo' => 'two',
  711. ], [
  712. 'cache' => ['config' => 'test_view'],
  713. ]);
  714. $result = Cache::read('element__test_element_param_foo', 'test_view');
  715. $this->assertEquals($expected, $result);
  716. Cache::clear('test_view');
  717. Cache::drop('test_view');
  718. }
  719. /**
  720. * Test element events
  721. *
  722. * @return void
  723. */
  724. public function testViewEvent()
  725. {
  726. $View = $this->PostsController->createView();
  727. $View->setTemplatePath($this->PostsController->getName());
  728. $View->enableAutoLayout(false);
  729. $listener = new TestViewEventListenerInterface();
  730. $View->getEventManager()->on($listener);
  731. $View->render('index');
  732. $this->assertEquals(View::TYPE_TEMPLATE, $listener->beforeRenderViewType);
  733. $this->assertEquals(View::TYPE_TEMPLATE, $listener->afterRenderViewType);
  734. $this->assertEquals($View->getCurrentType(), View::TYPE_TEMPLATE);
  735. $View->element('test_element', [], ['callbacks' => true]);
  736. $this->assertEquals($View->getCurrentType(), View::TYPE_TEMPLATE);
  737. $this->assertEquals(View::TYPE_ELEMENT, $listener->beforeRenderViewType);
  738. $this->assertEquals(View::TYPE_ELEMENT, $listener->afterRenderViewType);
  739. }
  740. /**
  741. * Test loading helper using loadHelper().
  742. *
  743. * @return void
  744. */
  745. public function testLoadHelper()
  746. {
  747. $View = new View();
  748. $View->loadHelper('Html', ['foo' => 'bar']);
  749. $this->assertInstanceOf('Cake\View\Helper\HtmlHelper', $View->Html);
  750. $config = $View->Html->getConfig();
  751. $this->assertSame('bar', $config['foo']);
  752. }
  753. /**
  754. * Test loading helper when duplicate.
  755. *
  756. * @return void
  757. */
  758. public function testLoadHelperDuplicate()
  759. {
  760. $View = new View();
  761. $this->assertNotEmpty($View->loadHelper('Html', ['foo' => 'bar']));
  762. try {
  763. $View->loadHelper('Html', ['test' => 'value']);
  764. $this->fail('No exception');
  765. } catch (\RuntimeException $e) {
  766. $this->assertStringContainsString('The "Html" alias has already been loaded', $e->getMessage());
  767. }
  768. }
  769. /**
  770. * Test loadHelpers method
  771. *
  772. * @return void
  773. */
  774. public function testLoadHelpers()
  775. {
  776. $View = new View(null, null, null, [
  777. 'helpers' => ['Html' => ['foo' => 'bar'], 'Form' => ['foo' => 'baz']],
  778. ]);
  779. $result = $View->loadHelpers();
  780. $this->assertSame($View, $result);
  781. $this->assertInstanceOf('Cake\View\Helper\HtmlHelper', $View->Html, 'Object type is wrong.');
  782. $this->assertInstanceOf('Cake\View\Helper\FormHelper', $View->Form, 'Object type is wrong.');
  783. $config = $View->Html->getConfig();
  784. $this->assertSame('bar', $config['foo']);
  785. $config = $View->Form->getConfig();
  786. $this->assertSame('baz', $config['foo']);
  787. }
  788. /**
  789. * Test lazy loading helpers
  790. *
  791. * @return void
  792. */
  793. public function testLazyLoadHelpers()
  794. {
  795. $View = new View();
  796. $this->assertInstanceOf('Cake\View\Helper\HtmlHelper', $View->Html, 'Object type is wrong.');
  797. $this->assertInstanceOf('Cake\View\Helper\FormHelper', $View->Form, 'Object type is wrong.');
  798. }
  799. /**
  800. * Test manipulating class properties in initialize()
  801. *
  802. * @return void
  803. */
  804. public function testInitialize()
  805. {
  806. $View = new TestView();
  807. $config = $View->Html->getConfig();
  808. $this->assertSame('myval', $config['mykey']);
  809. }
  810. /**
  811. * Test the correct triggering of helper callbacks
  812. *
  813. * @return void
  814. */
  815. public function testHelperCallbackTriggering()
  816. {
  817. $View = $this->PostsController->createView();
  818. $View->setTemplatePath($this->PostsController->getName());
  819. $manager = $this->getMockBuilder('Cake\Event\EventManager')->getMock();
  820. $View->setEventManager($manager);
  821. $manager->expects($this->at(0))
  822. ->method('dispatch')
  823. ->with($this->callback(function (EventInterface $event) {
  824. return $event->getName() === 'View.beforeRender';
  825. }));
  826. $manager->expects($this->at(1))
  827. ->method('dispatch')
  828. ->with($this->callback(function (EventInterface $event) {
  829. return $event->getName() === 'View.beforeRenderFile';
  830. }));
  831. $manager->expects($this->at(2))
  832. ->method('dispatch')
  833. ->with($this->callback(function (EventInterface $event) {
  834. return $event->getName() === 'View.afterRenderFile';
  835. }));
  836. $manager->expects($this->at(3))
  837. ->method('dispatch')
  838. ->with($this->callback(function (EventInterface $event) {
  839. return $event->getName() === 'View.afterRender';
  840. }));
  841. $manager->expects($this->at(4))
  842. ->method('dispatch')
  843. ->with($this->callback(function (EventInterface $event) {
  844. return $event->getName() === 'View.beforeLayout';
  845. }));
  846. $manager->expects($this->at(5))
  847. ->method('dispatch')
  848. ->with($this->callback(function (EventInterface $event) {
  849. return $event->getName() === 'View.beforeRenderFile';
  850. }));
  851. $manager->expects($this->at(6))
  852. ->method('dispatch')
  853. ->with($this->callback(function (EventInterface $event) {
  854. return $event->getName() === 'View.afterRenderFile';
  855. }));
  856. $manager->expects($this->at(7))
  857. ->method('dispatch')
  858. ->with($this->callback(function (EventInterface $event) {
  859. return $event->getName() === 'View.afterLayout';
  860. }));
  861. $View->render('index');
  862. }
  863. /**
  864. * Test beforeLayout method
  865. *
  866. * @return void
  867. */
  868. public function testBeforeLayout()
  869. {
  870. $this->PostsController->viewBuilder()->setHelpers([
  871. 'TestBeforeAfter' => ['className' => TestBeforeAfterHelper::class],
  872. 'Html',
  873. ]);
  874. $View = $this->PostsController->createView();
  875. $View->setTemplatePath($this->PostsController->getName());
  876. $View->render('index');
  877. $this->assertSame('Valuation', $View->helpers()->TestBeforeAfter->property);
  878. }
  879. /**
  880. * Test afterLayout method
  881. *
  882. * @return void
  883. */
  884. public function testAfterLayout()
  885. {
  886. $this->PostsController->viewBuilder()->setHelpers([
  887. 'TestBeforeAfter' => ['className' => TestBeforeAfterHelper::class],
  888. 'Html',
  889. ]);
  890. $this->PostsController->set('variable', 'values');
  891. $View = $this->PostsController->createView();
  892. $View->setTemplatePath($this->PostsController->getName());
  893. $content = 'This is my view output';
  894. $result = $View->renderLayout($content, 'default');
  895. $this->assertRegExp('/modified in the afterlife/', $result);
  896. $this->assertRegExp('/This is my view output/', $result);
  897. }
  898. /**
  899. * Test renderLoadHelper method
  900. *
  901. * @return void
  902. */
  903. public function testRenderLoadHelper()
  904. {
  905. $this->PostsController->viewBuilder()->setHelpers(['Form', 'Number']);
  906. $View = $this->PostsController->createView(TestView::class);
  907. $View->setTemplatePath($this->PostsController->getName());
  908. $result = $View->render('index', false);
  909. $this->assertSame('posts index', $result);
  910. $attached = $View->helpers()->loaded();
  911. // HtmlHelper is loaded in TestView::initialize()
  912. $this->assertEquals(['Html', 'Form', 'Number'], $attached);
  913. $this->PostsController->viewBuilder()->setHelpers(
  914. ['Html', 'Form', 'Number', 'TestPlugin.PluggedHelper']
  915. );
  916. $View = $this->PostsController->createView(TestView::class);
  917. $View->setTemplatePath($this->PostsController->getName());
  918. $result = $View->render('index', false);
  919. $this->assertSame('posts index', $result);
  920. $attached = $View->helpers()->loaded();
  921. $expected = ['Html', 'Form', 'Number', 'PluggedHelper'];
  922. $this->assertEquals($expected, $attached, 'Attached helpers are wrong.');
  923. }
  924. /**
  925. * Test render method
  926. *
  927. * @return void
  928. */
  929. public function testRender()
  930. {
  931. $View = $this->PostsController->createView(TestView::class);
  932. $View->setTemplatePath($this->PostsController->getName());
  933. $result = $View->render('index');
  934. $this->assertRegExp("/<meta charset=\"utf-8\"\/>\s*<title>/", $result);
  935. $this->assertRegExp("/<div id=\"content\">\s*posts index\s*<\/div>/", $result);
  936. $this->assertRegExp("/<div id=\"content\">\s*posts index\s*<\/div>/", $result);
  937. $this->PostsController->viewBuilder()->setHelpers(['Html']);
  938. $this->PostsController->setRequest(
  939. $this->PostsController->getRequest()->withParam('action', 'index')
  940. );
  941. Configure::write('Cache.check', true);
  942. $View = $this->PostsController->createView(TestView::class);
  943. $View->setTemplatePath($this->PostsController->getName());
  944. $result = $View->render('index');
  945. $this->assertRegExp("/<meta charset=\"utf-8\"\/>\s*<title>/", $result);
  946. $this->assertRegExp("/<div id=\"content\">\s*posts index\s*<\/div>/", $result);
  947. }
  948. /**
  949. * Test that View::$view works
  950. *
  951. * @return void
  952. */
  953. public function testRenderUsingViewProperty()
  954. {
  955. $View = $this->PostsController->createView(TestView::class);
  956. $View->setTemplatePath($this->PostsController->getName());
  957. $View->setTemplate('cache_form');
  958. $this->assertSame('cache_form', $View->getTemplate());
  959. $result = $View->render();
  960. $this->assertRegExp('/Add User/', $result);
  961. }
  962. /**
  963. * Test that layout set from view file takes precedence over layout set
  964. * as argument to render().
  965. *
  966. * @return void
  967. */
  968. public function testRenderUsingLayoutArgument()
  969. {
  970. $error = new \PDOException();
  971. $error->queryString = 'this is sql string';
  972. $message = 'it works';
  973. $View = $this->PostsController->createView(TestView::class);
  974. $View->set(compact('error', 'message'));
  975. $View->setTemplatePath('Error');
  976. $result = $View->render('pdo_error', 'error');
  977. $this->assertRegExp('/this is sql string/', $result);
  978. $this->assertRegExp('/it works/', $result);
  979. }
  980. /**
  981. * Test renderLayout()
  982. *
  983. * @return void
  984. */
  985. public function testRenderLayout()
  986. {
  987. $View = $this->PostsController->createView(TestView::class);
  988. $result = $View->renderLayout('', 'ajax2');
  989. $this->assertRegExp('/Ajax\!/', $result);
  990. }
  991. /**
  992. * Test render()ing a file in a subdir from a custom viewPath
  993. * in a plugin.
  994. *
  995. * @return void
  996. */
  997. public function testGetTemplateFileNameSubdirWithPluginAndViewPath()
  998. {
  999. $this->PostsController->setPlugin('TestPlugin');
  1000. $this->PostsController->setName('Posts');
  1001. /** @var \TestApp\View\TestView $View */
  1002. $View = $this->PostsController->createView(TestView::class);
  1003. $View->setTemplatePath('element');
  1004. $pluginPath = TEST_APP . 'Plugin' . DS . 'TestPlugin' . DS;
  1005. $result = $View->getTemplateFileName('sub_dir/sub_element');
  1006. $expected = $pluginPath . 'templates' . DS . 'element' . DS . 'sub_dir' . DS . 'sub_element.php';
  1007. $this->assertPathEquals($expected, $result);
  1008. }
  1009. public function testGetTemplateException()
  1010. {
  1011. $this->expectException(RuntimeException::class);
  1012. $this->expectExceptionMessage('Template name not provided');
  1013. $view = new View();
  1014. $view->render();
  1015. }
  1016. /**
  1017. * Test that view vars can replace the local helper variables
  1018. * and not overwrite the $this->Helper references
  1019. *
  1020. * @return void
  1021. */
  1022. public function testViewVarOverwritingLocalHelperVar()
  1023. {
  1024. $Controller = new ViewPostsController();
  1025. $Controller->set('html', 'I am some test html');
  1026. $View = $Controller->createView();
  1027. $View->setTemplatePath($Controller->getName());
  1028. $result = $View->render('helper_overwrite', false);
  1029. $this->assertRegExp('/I am some test html/', $result);
  1030. $this->assertRegExp('/Test link/', $result);
  1031. }
  1032. /**
  1033. * Test getTemplateFileName method
  1034. *
  1035. * @return void
  1036. */
  1037. public function testViewFileName()
  1038. {
  1039. /** @var \TestApp\View\TestView $View */
  1040. $View = $this->PostsController->createView(TestView::class);
  1041. $View->setTemplatePath('Posts');
  1042. $result = $View->getTemplateFileName('index');
  1043. $this->assertRegExp('/Posts(\/|\\\)index.php/', $result);
  1044. $result = $View->getTemplateFileName('TestPlugin.index');
  1045. $this->assertRegExp('/Posts(\/|\\\)index.php/', $result);
  1046. $result = $View->getTemplateFileName('/Pages/home');
  1047. $this->assertRegExp('/Pages(\/|\\\)home.php/', $result);
  1048. $result = $View->getTemplateFileName('../element/test_element');
  1049. $this->assertRegExp('/element(\/|\\\)test_element.php/', $result);
  1050. $expected = TEST_APP . 'templates' . DS . 'Posts' . DS . 'index.php';
  1051. $result = $View->getTemplateFileName('../Posts/index');
  1052. $this->assertPathEquals($expected, $result);
  1053. }
  1054. /**
  1055. * Test creating a block with capturing output.
  1056. *
  1057. * @return void
  1058. */
  1059. public function testBlockCaptureOverwrite()
  1060. {
  1061. $result = $this->View->start('test');
  1062. $this->assertSame($this->View, $result);
  1063. echo 'Block content';
  1064. $result = $this->View->end();
  1065. $this->assertSame($this->View, $result);
  1066. $this->View->start('test');
  1067. echo 'New content';
  1068. $this->View->end();
  1069. $result = $this->View->fetch('test');
  1070. $this->assertSame('New content', $result);
  1071. }
  1072. /**
  1073. * Test that blocks can be fetched inside a block with the same name
  1074. *
  1075. * @return void
  1076. */
  1077. public function testBlockExtend()
  1078. {
  1079. $this->View->start('test');
  1080. echo 'Block content';
  1081. $this->View->end();
  1082. $this->View->start('test');
  1083. echo $this->View->fetch('test');
  1084. echo 'New content';
  1085. $this->View->end();
  1086. $result = $this->View->fetch('test');
  1087. $this->assertSame('Block contentNew content', $result);
  1088. }
  1089. /**
  1090. * Test creating a block with capturing output.
  1091. *
  1092. * @return void
  1093. */
  1094. public function testBlockCapture()
  1095. {
  1096. $this->View->start('test');
  1097. echo 'Block content';
  1098. $this->View->end();
  1099. $result = $this->View->fetch('test');
  1100. $this->assertSame('Block content', $result);
  1101. }
  1102. /**
  1103. * Test appending to a block with capturing output.
  1104. *
  1105. * @return void
  1106. */
  1107. public function testBlockAppendCapture()
  1108. {
  1109. $this->View->start('test');
  1110. echo 'Content ';
  1111. $this->View->end();
  1112. $result = $this->View->append('test');
  1113. $this->assertSame($this->View, $result);
  1114. echo 'appended';
  1115. $this->View->end();
  1116. $result = $this->View->fetch('test');
  1117. $this->assertSame('Content appended', $result);
  1118. }
  1119. /**
  1120. * Test setting a block's content.
  1121. *
  1122. * @return void
  1123. */
  1124. public function testBlockSet()
  1125. {
  1126. $result = $this->View->assign('test', 'Block content');
  1127. $this->assertSame($this->View, $result);
  1128. $result = $this->View->fetch('test');
  1129. $this->assertSame('Block content', $result);
  1130. }
  1131. /**
  1132. * Test resetting a block's content.
  1133. *
  1134. * @return void
  1135. */
  1136. public function testBlockReset()
  1137. {
  1138. $this->View->assign('test', '');
  1139. $result = $this->View->fetch('test', 'This should not be returned');
  1140. $this->assertSame('', $result);
  1141. }
  1142. /**
  1143. * Test resetting a block's content with reset.
  1144. *
  1145. * @return void
  1146. */
  1147. public function testBlockResetFunc()
  1148. {
  1149. $this->View->assign('test', 'Block content');
  1150. $result = $this->View->fetch('test', 'This should not be returned');
  1151. $this->assertSame('Block content', $result);
  1152. $result = $this->View->reset('test');
  1153. $this->assertSame($this->View, $result);
  1154. $result = $this->View->fetch('test', 'This should not be returned');
  1155. $this->assertSame('', $result);
  1156. }
  1157. /**
  1158. * Test checking a block's existence.
  1159. *
  1160. * @return void
  1161. */
  1162. public function testBlockExist()
  1163. {
  1164. $this->assertFalse($this->View->exists('test'));
  1165. $this->View->assign('test', 'Block content');
  1166. $this->assertTrue($this->View->exists('test'));
  1167. }
  1168. /**
  1169. * Test setting a block's content to null
  1170. *
  1171. * @return void
  1172. */
  1173. public function testBlockSetNull()
  1174. {
  1175. $this->View->assign('testWithNull', null);
  1176. $result = $this->View->fetch('testWithNull');
  1177. $this->assertSame('', $result);
  1178. }
  1179. /**
  1180. * Test setting a block's content to an object with __toString magic method
  1181. *
  1182. * @return void
  1183. */
  1184. public function testBlockSetObjectWithToString()
  1185. {
  1186. $objectWithToString = new TestObjectWithToString();
  1187. $this->View->assign('testWithObjectWithToString', $objectWithToString);
  1188. $result = $this->View->fetch('testWithObjectWithToString');
  1189. $this->assertSame("I'm ObjectWithToString", $result);
  1190. }
  1191. /**
  1192. * Test setting a block's content to an object without __toString magic method
  1193. *
  1194. * @return void
  1195. */
  1196. public function testBlockSetObjectWithoutToString()
  1197. {
  1198. $this->checkException(
  1199. 'Object of class ' . TestObjectWithoutToString::class . ' could not be converted to string'
  1200. );
  1201. $objectWithToString = new TestObjectWithoutToString();
  1202. $this->View->assign('testWithObjectWithoutToString', $objectWithToString);
  1203. }
  1204. /**
  1205. * Test setting a block's content to a decimal
  1206. *
  1207. * @return void
  1208. */
  1209. public function testBlockSetDecimal()
  1210. {
  1211. $this->View->assign('testWithDecimal', 1.23456789);
  1212. $result = $this->View->fetch('testWithDecimal');
  1213. $this->assertSame('1.23456789', $result);
  1214. }
  1215. /**
  1216. * Data provider for block related tests.
  1217. *
  1218. * @return array
  1219. */
  1220. public static function blockValueProvider()
  1221. {
  1222. return [
  1223. 'string' => ['A string value'],
  1224. 'decimal' => [1.23456],
  1225. 'object with __toString' => [new TestObjectWithToString()],
  1226. ];
  1227. }
  1228. /**
  1229. * Test appending to a block with append.
  1230. *
  1231. * @param mixed $value Value
  1232. * @return void
  1233. * @dataProvider blockValueProvider
  1234. */
  1235. public function testBlockAppend($value)
  1236. {
  1237. $this->View->assign('testBlock', 'Block');
  1238. $this->View->append('testBlock', $value);
  1239. $result = $this->View->fetch('testBlock');
  1240. $this->assertSame('Block' . $value, $result);
  1241. }
  1242. /**
  1243. * Test appending an object without __toString magic method to a block with append.
  1244. *
  1245. * @return void
  1246. */
  1247. public function testBlockAppendObjectWithoutToString()
  1248. {
  1249. $this->checkException(
  1250. 'Object of class ' . TestObjectWithoutToString::class . ' could not be converted to string'
  1251. );
  1252. $object = new TestObjectWithoutToString();
  1253. $this->View->assign('testBlock', 'Block ');
  1254. $this->View->append('testBlock', $object);
  1255. }
  1256. /**
  1257. * Test prepending to a block with prepend.
  1258. *
  1259. * @param mixed $value Value
  1260. * @return void
  1261. * @dataProvider blockValueProvider
  1262. */
  1263. public function testBlockPrepend($value)
  1264. {
  1265. $this->View->assign('test', 'Block');
  1266. $result = $this->View->prepend('test', $value);
  1267. $this->assertSame($this->View, $result);
  1268. $result = $this->View->fetch('test');
  1269. $this->assertEquals($value . 'Block', $result);
  1270. }
  1271. /**
  1272. * Test prepending an object without __toString magic method to a block with prepend.
  1273. *
  1274. * @return void
  1275. */
  1276. public function testBlockPrependObjectWithoutToString()
  1277. {
  1278. $this->checkException(
  1279. 'Object of class ' . TestObjectWithoutToString::class . ' could not be converted to string'
  1280. );
  1281. $object = new TestObjectWithoutToString();
  1282. $this->View->assign('test', 'Block ');
  1283. $this->View->prepend('test', $object);
  1284. }
  1285. /**
  1286. * You should be able to append to undefined blocks.
  1287. *
  1288. * @return void
  1289. */
  1290. public function testBlockAppendUndefined()
  1291. {
  1292. $result = $this->View->append('test', 'Unknown');
  1293. $this->assertSame($this->View, $result);
  1294. $result = $this->View->fetch('test');
  1295. $this->assertSame('Unknown', $result);
  1296. }
  1297. /**
  1298. * You should be able to prepend to undefined blocks.
  1299. *
  1300. * @return void
  1301. */
  1302. public function testBlockPrependUndefined()
  1303. {
  1304. $this->View->prepend('test', 'Unknown');
  1305. $result = $this->View->fetch('test');
  1306. $this->assertSame('Unknown', $result);
  1307. }
  1308. /**
  1309. * Test getting block names
  1310. *
  1311. * @return void
  1312. */
  1313. public function testBlocks()
  1314. {
  1315. $this->View->append('test', 'one');
  1316. $this->View->assign('test1', 'one');
  1317. $this->assertEquals(['test', 'test1'], $this->View->blocks());
  1318. }
  1319. /**
  1320. * Test that blocks can be nested.
  1321. *
  1322. * @return void
  1323. */
  1324. public function testNestedBlocks()
  1325. {
  1326. $this->View->start('first');
  1327. echo 'In first ';
  1328. $this->View->start('second');
  1329. echo 'In second';
  1330. $this->View->end();
  1331. echo 'In first';
  1332. $this->View->end();
  1333. $this->assertSame('In first In first', $this->View->fetch('first'));
  1334. $this->assertSame('In second', $this->View->fetch('second'));
  1335. }
  1336. /**
  1337. * Test that starting the same block twice throws an exception
  1338. *
  1339. * @return void
  1340. */
  1341. public function testStartBlocksTwice()
  1342. {
  1343. try {
  1344. $this->View->start('first');
  1345. $this->View->start('first');
  1346. $this->fail('No exception');
  1347. } catch (\Cake\Core\Exception\Exception $e) {
  1348. ob_end_clean();
  1349. $this->assertTrue(true);
  1350. }
  1351. }
  1352. /**
  1353. * Test that an exception gets thrown when you leave a block open at the end
  1354. * of a view.
  1355. *
  1356. * @return void
  1357. */
  1358. public function testExceptionOnOpenBlock()
  1359. {
  1360. try {
  1361. $this->View->render('open_block');
  1362. $this->fail('No exception');
  1363. } catch (\LogicException $e) {
  1364. ob_end_clean();
  1365. $this->assertStringContainsString('The "no_close" block was left open', $e->getMessage());
  1366. }
  1367. }
  1368. /**
  1369. * Test nested extended views.
  1370. *
  1371. * @return void
  1372. */
  1373. public function testExtendNested()
  1374. {
  1375. $content = $this->View->render('nested_extends', false);
  1376. $expected = <<<TEXT
  1377. This is the second parent.
  1378. This is the first parent.
  1379. This is the first template.
  1380. Sidebar Content.
  1381. TEXT;
  1382. $this->assertEquals($expected, $content);
  1383. }
  1384. /**
  1385. * Make sure that extending the current view with itself causes an exception
  1386. *
  1387. * @return void
  1388. */
  1389. public function testExtendSelf()
  1390. {
  1391. try {
  1392. $this->View->render('extend_self', false);
  1393. $this->fail('No exception');
  1394. } catch (\LogicException $e) {
  1395. ob_end_clean();
  1396. $this->assertStringContainsString('cannot have templates extend themselves', $e->getMessage());
  1397. }
  1398. }
  1399. /**
  1400. * Make sure that extending in a loop causes an exception
  1401. *
  1402. * @return void
  1403. */
  1404. public function testExtendLoop()
  1405. {
  1406. try {
  1407. $this->View->render('extend_loop', false);
  1408. $this->fail('No exception');
  1409. } catch (\LogicException $e) {
  1410. ob_end_clean();
  1411. $this->assertStringContainsString('cannot have templates extend in a loop', $e->getMessage());
  1412. }
  1413. }
  1414. /**
  1415. * Test extend() in an element and a view.
  1416. *
  1417. * @return void
  1418. */
  1419. public function testExtendElement()
  1420. {
  1421. $content = $this->View->render('extend_element', false);
  1422. $expected = <<<TEXT
  1423. Parent View.
  1424. View content.
  1425. Parent Element.
  1426. Element content.
  1427. TEXT;
  1428. $this->assertEquals($expected, $content);
  1429. }
  1430. /**
  1431. * Test extend() in an element and a view.
  1432. *
  1433. * @return void
  1434. */
  1435. public function testExtendPrefixElement()
  1436. {
  1437. $this->View->setRequest($this->View->getRequest()->withParam('prefix', 'Admin'));
  1438. $content = $this->View->render('extend_element', false);
  1439. $expected = <<<TEXT
  1440. Parent View.
  1441. View content.
  1442. Parent Element.
  1443. Prefix Element content.
  1444. TEXT;
  1445. $this->assertEquals($expected, $content);
  1446. }
  1447. /**
  1448. * Extending an element which doesn't exist should throw a missing view exception
  1449. *
  1450. * @return void
  1451. */
  1452. public function testExtendMissingElement()
  1453. {
  1454. try {
  1455. $this->View->render('extend_missing_element', false);
  1456. $this->fail('No exception');
  1457. } catch (\LogicException $e) {
  1458. ob_end_clean();
  1459. ob_end_clean();
  1460. $this->assertStringContainsString('element', $e->getMessage());
  1461. }
  1462. }
  1463. /**
  1464. * Test extend() preceded by an element()
  1465. *
  1466. * @return void
  1467. */
  1468. public function testExtendWithElementBeforeExtend()
  1469. {
  1470. $result = $this->View->render('extend_with_element', false);
  1471. $expected = <<<TEXT
  1472. Parent View.
  1473. this is the test elementThe view
  1474. TEXT;
  1475. $this->assertEquals($expected, $result);
  1476. }
  1477. /**
  1478. * Test extend() preceded by an element()
  1479. *
  1480. * @return void
  1481. */
  1482. public function testExtendWithPrefixElementBeforeExtend()
  1483. {
  1484. $this->View->setRequest($this->View->getRequest()->withParam('prefix', 'Admin'));
  1485. $this->View->disableAutoLayout();
  1486. $result = $this->View->render('extend_with_element');
  1487. $expected = <<<TEXT
  1488. Parent View.
  1489. this is the test prefix elementThe view
  1490. TEXT;
  1491. $this->assertEquals($expected, $result);
  1492. }
  1493. /**
  1494. * Test memory leaks that existed in _paths at one point.
  1495. *
  1496. * @return void
  1497. */
  1498. public function testMemoryLeakInPaths()
  1499. {
  1500. $this->skipIf((bool)env('CODECOVERAGE'), 'Running coverage this causes this tests to fail sometimes.');
  1501. $this->ThemeController->setName('Posts');
  1502. $View = $this->ThemeController->createView();
  1503. $View->setTemplatePath('Posts');
  1504. $View->setLayout('whatever');
  1505. $View->setTheme('TestTheme');
  1506. $View->element('test_element');
  1507. $start = memory_get_usage();
  1508. for ($i = 0; $i < 10; $i++) {
  1509. $View->element('test_element');
  1510. }
  1511. $end = memory_get_usage();
  1512. $this->assertLessThanOrEqual($start + 15000, $end);
  1513. }
  1514. /**
  1515. * Tests that a view block uses default value when not assigned and uses assigned value when it is
  1516. *
  1517. * @return void
  1518. */
  1519. public function testBlockDefaultValue()
  1520. {
  1521. $default = 'Default';
  1522. $result = $this->View->fetch('title', $default);
  1523. $this->assertEquals($default, $result);
  1524. $expected = 'My Title';
  1525. $this->View->assign('title', $expected);
  1526. $result = $this->View->fetch('title', $default);
  1527. $this->assertEquals($expected, $result);
  1528. }
  1529. /**
  1530. * Tests that a view variable uses default value when not assigned and uses assigned value when it is
  1531. *
  1532. * @return void
  1533. */
  1534. public function testViewVarDefaultValue()
  1535. {
  1536. $default = 'Default';
  1537. $result = $this->View->get('title', $default);
  1538. $this->assertEquals($default, $result);
  1539. $expected = 'Back to the Future';
  1540. $this->View->set('title', $expected);
  1541. $result = $this->View->get('title', $default);
  1542. $this->assertEquals($expected, $result);
  1543. }
  1544. /**
  1545. * Test the helpers() method.
  1546. *
  1547. * @return void
  1548. */
  1549. public function testHelpers()
  1550. {
  1551. $this->assertInstanceOf('Cake\View\HelperRegistry', $this->View->helpers());
  1552. $result = $this->View->helpers();
  1553. $this->assertSame($result, $this->View->helpers());
  1554. }
  1555. /**
  1556. * Test getTemplatePath() and setTemplatePath().
  1557. *
  1558. * @return void
  1559. */
  1560. public function testGetSetTemplatePath()
  1561. {
  1562. $result = $this->View->setTemplatePath('foo');
  1563. $this->assertSame($this->View, $result);
  1564. $templatePath = $this->View->getTemplatePath();
  1565. $this->assertSame($templatePath, 'foo');
  1566. }
  1567. /**
  1568. * Test getLayoutPath() and setLayoutPath().
  1569. *
  1570. * @return void
  1571. */
  1572. public function testGetSetLayoutPath()
  1573. {
  1574. $result = $this->View->setLayoutPath('foo');
  1575. $this->assertSame($this->View, $result);
  1576. $layoutPath = $this->View->getLayoutPath();
  1577. $this->assertSame($layoutPath, 'foo');
  1578. }
  1579. /**
  1580. * Test isAutoLayoutEnabled() and enableAutoLayout().
  1581. *
  1582. * @return void
  1583. */
  1584. public function testAutoLayout()
  1585. {
  1586. $result = $this->View->enableAutoLayout(false);
  1587. $this->assertSame($this->View, $result);
  1588. $autoLayout = $this->View->isAutoLayoutEnabled();
  1589. $this->assertSame($autoLayout, false);
  1590. $this->View->enableAutoLayout();
  1591. $autoLayout = $this->View->isAutoLayoutEnabled();
  1592. $this->assertSame($autoLayout, true);
  1593. }
  1594. /**
  1595. * testDisableAutoLayout
  1596. *
  1597. * @return void
  1598. */
  1599. public function testDisableAutoLayout()
  1600. {
  1601. $this->assertTrue($this->View->isAutoLayoutEnabled());
  1602. $result = $this->View->disableAutoLayout();
  1603. $this->assertSame($this->View, $result);
  1604. $autoLayout = $this->View->isAutoLayoutEnabled();
  1605. $this->assertFalse($this->View->isAutoLayoutEnabled());
  1606. }
  1607. /**
  1608. * Test getTheme() and setTheme().
  1609. *
  1610. * @return void
  1611. */
  1612. public function testGetSetTheme()
  1613. {
  1614. $result = $this->View->setTheme('foo');
  1615. $this->assertSame($this->View, $result);
  1616. $theme = $this->View->getTheme();
  1617. $this->assertSame($theme, 'foo');
  1618. }
  1619. /**
  1620. * Test getTemplate() and setTemplate().
  1621. *
  1622. * @return void
  1623. */
  1624. public function testGetSetTemplate()
  1625. {
  1626. $result = $this->View->setTemplate('foo');
  1627. $this->assertSame($this->View, $result);
  1628. $template = $this->View->getTemplate();
  1629. $this->assertSame($template, 'foo');
  1630. }
  1631. /**
  1632. * Test setLayout() and getLayout().
  1633. *
  1634. * @return void
  1635. */
  1636. public function testGetSetLayout()
  1637. {
  1638. $result = $this->View->setLayout('foo');
  1639. $this->assertSame($this->View, $result);
  1640. $layout = $this->View->getLayout();
  1641. $this->assertSame($layout, 'foo');
  1642. }
  1643. /**
  1644. * Test getName() and getPlugin().
  1645. *
  1646. * @return void
  1647. */
  1648. public function testGetNamePlugin()
  1649. {
  1650. $this->assertSame('Posts', $this->View->getName());
  1651. $this->assertNull($this->View->getPlugin());
  1652. $this->assertSame($this->View, $this->View->setPlugin('TestPlugin'));
  1653. $this->assertSame('TestPlugin', $this->View->getPlugin());
  1654. }
  1655. protected function checkException($message)
  1656. {
  1657. if (version_compare(PHP_VERSION, '7.4', '>=')) {
  1658. $this->expectException(\Error::class);
  1659. } else {
  1660. $this->expectException(\PHPUnit\Framework\Error\Error::class);
  1661. }
  1662. $this->expectExceptionMessage($message);
  1663. }
  1664. }