ViewTest.php 60 KB

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