ViewTest.php 59 KB

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