ViewTest.php 61 KB

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