ViewTest.php 59 KB

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