ViewTest.php 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943
  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' could not be found");
  506. $this->expectExceptionMessage('The following paths were searched');
  507. $this->expectExceptionMessage('- ' . ROOT . DS . 'templates');
  508. $viewOptions = ['plugin' => null,
  509. 'name' => 'Pages',
  510. 'viewPath' => 'Pages',
  511. ];
  512. $request = new ServerRequest();
  513. $response = new Response();
  514. $View = new TestView($request, $response, null, $viewOptions);
  515. $View->getTemplateFileName('does_not_exist');
  516. }
  517. /**
  518. * Test for missing layouts
  519. *
  520. * @return void
  521. */
  522. public function testMissingLayout()
  523. {
  524. $this->expectException(\Cake\View\Exception\MissingLayoutException::class);
  525. $this->expectExceptionMessage("Layout file 'whatever' could not be found");
  526. $this->expectExceptionMessage('The following paths were searched');
  527. $this->expectExceptionMessage('- ' . ROOT . DS . 'templates' . DS . 'layout');
  528. $viewOptions = ['plugin' => null,
  529. 'name' => 'Pages',
  530. 'viewPath' => 'Pages',
  531. 'layout' => 'whatever',
  532. ];
  533. $View = new TestView(null, null, null, $viewOptions);
  534. $View->getLayoutFileName();
  535. }
  536. /**
  537. * Test viewVars method
  538. *
  539. * @return void
  540. */
  541. public function testViewVars()
  542. {
  543. $this->assertEquals(['testData', 'test2', 'test3'], $this->View->getVars());
  544. }
  545. /**
  546. * Test elementExists method
  547. *
  548. * @return void
  549. */
  550. public function testElementExists()
  551. {
  552. $result = $this->View->elementExists('test_element');
  553. $this->assertTrue($result);
  554. $result = $this->View->elementExists('TestPlugin.plugin_element');
  555. $this->assertTrue($result);
  556. $result = $this->View->elementExists('non_existent_element');
  557. $this->assertFalse($result);
  558. $result = $this->View->elementExists('TestPlugin.element');
  559. $this->assertFalse($result);
  560. $this->View->setRequest($this->View->getRequest()->withParam('plugin', 'TestPlugin'));
  561. $result = $this->View->elementExists('plugin_element');
  562. $this->assertTrue($result);
  563. }
  564. /**
  565. * Test element method
  566. *
  567. * @return void
  568. */
  569. public function testElement()
  570. {
  571. $result = $this->View->element('test_element');
  572. $this->assertSame('this is the test element', $result);
  573. $result = $this->View->element('TestPlugin.plugin_element');
  574. $this->assertEquals("Element in the TestPlugin\n", $result);
  575. $this->View->setRequest($this->View->getRequest()->withParam('plugin', 'TestPlugin'));
  576. $result = $this->View->element('plugin_element');
  577. $this->assertEquals("Element in the TestPlugin\n", $result);
  578. $result = $this->View->element('plugin_element', [], ['plugin' => false]);
  579. $this->assertEquals("Plugin element overridden in app\n", $result);
  580. }
  581. /**
  582. * Test element method with a prefix
  583. *
  584. * @return void
  585. */
  586. public function testPrefixElement()
  587. {
  588. $this->View->setRequest($this->View->getRequest()->withParam('prefix', 'Admin'));
  589. $result = $this->View->element('prefix_element');
  590. $this->assertSame('this is a prefixed test element', $result);
  591. $result = $this->View->element('TestPlugin.plugin_element');
  592. $this->assertSame('this is the plugin prefixed element using params[plugin]', $result);
  593. $this->View->setRequest($this->View->getRequest()->withParam('plugin', 'TestPlugin'));
  594. $result = $this->View->element('test_plugin_element');
  595. $this->assertSame('this is the test set using View::$plugin plugin prefixed element', $result);
  596. $this->View->setRequest($this->View->getRequest()->withParam('prefix', 'FooPrefix/BarPrefix'));
  597. $result = $this->View->element('prefix_element');
  598. $this->assertSame('this is a nested prefixed test element', $result);
  599. $result = $this->View->element('prefix_element_in_parent');
  600. $this->assertSame('this is a nested prefixed test element in first level element', $result);
  601. }
  602. /**
  603. * Test loading missing view element
  604. *
  605. * @return void
  606. */
  607. public function testElementMissing()
  608. {
  609. $this->expectException(\Cake\View\Exception\MissingElementException::class);
  610. $this->expectExceptionMessage("Element file 'non_existent_element' could not be found");
  611. $this->View->element('non_existent_element');
  612. }
  613. /**
  614. * Test loading non-existent plugin view element
  615. *
  616. * @return void
  617. */
  618. public function testElementMissingPluginElement()
  619. {
  620. $this->expectException(\Cake\View\Exception\MissingElementException::class);
  621. $this->expectExceptionMessage("Element file 'TestPlugin.nope' could not be found");
  622. $this->View->element('TestPlugin.nope');
  623. }
  624. /**
  625. * Test that elements can have callbacks
  626. *
  627. * @return void
  628. */
  629. public function testElementCallbacks()
  630. {
  631. $count = 0;
  632. $callback = function (EventInterface $event, $file) use (&$count) {
  633. $count++;
  634. };
  635. $events = $this->View->getEventManager();
  636. $events->on('View.beforeRender', $callback);
  637. $events->on('View.afterRender', $callback);
  638. $this->View->element('test_element', [], ['callbacks' => true]);
  639. $this->assertEquals(2, $count);
  640. }
  641. /**
  642. * Test that additional element viewVars don't get overwritten with helpers.
  643. *
  644. * @return void
  645. */
  646. public function testElementParamsDontOverwriteHelpers()
  647. {
  648. $Controller = new ViewPostsController();
  649. $View = $Controller->createView();
  650. $result = $View->element('type_check', ['form' => 'string'], ['callbacks' => true]);
  651. $this->assertSame('string', $result);
  652. $View->set('form', 'string');
  653. $result = $View->element('type_check', [], ['callbacks' => true]);
  654. $this->assertSame('string', $result);
  655. }
  656. /**
  657. * Test elementCacheHelperNoCache method
  658. *
  659. * @return void
  660. */
  661. public function testElementCacheHelperNoCache()
  662. {
  663. $Controller = new ViewPostsController();
  664. $View = $Controller->createView();
  665. $result = $View->element('test_element', ['ram' => 'val', 'test' => ['foo', 'bar']]);
  666. $this->assertSame('this is the test element', $result);
  667. }
  668. /**
  669. * Test elementCache method
  670. *
  671. * @return void
  672. */
  673. public function testElementCache()
  674. {
  675. Cache::drop('test_view');
  676. Cache::setConfig('test_view', [
  677. 'engine' => 'File',
  678. 'duration' => '+1 day',
  679. 'path' => CACHE . 'views/',
  680. 'prefix' => '',
  681. ]);
  682. Cache::clear('test_view');
  683. $View = $this->PostsController->createView();
  684. $View->setElementCache('test_view');
  685. $result = $View->element('test_element', [], ['cache' => true]);
  686. $expected = 'this is the test element';
  687. $this->assertEquals($expected, $result);
  688. $result = Cache::read('element__test_element', 'test_view');
  689. $this->assertEquals($expected, $result);
  690. $result = $View->element('test_element', ['param' => 'one', 'foo' => 'two'], ['cache' => true]);
  691. $this->assertEquals($expected, $result);
  692. $result = Cache::read('element__test_element_param_foo', 'test_view');
  693. $this->assertEquals($expected, $result);
  694. $View->element('test_element', [
  695. 'param' => 'one',
  696. 'foo' => 'two',
  697. ], [
  698. 'cache' => ['key' => 'custom_key'],
  699. ]);
  700. $result = Cache::read('element_custom_key', 'test_view');
  701. $this->assertEquals($expected, $result);
  702. $View->setElementCache('default');
  703. $View->element('test_element', [
  704. 'param' => 'one',
  705. 'foo' => 'two',
  706. ], [
  707. 'cache' => ['config' => 'test_view'],
  708. ]);
  709. $result = Cache::read('element__test_element_param_foo', 'test_view');
  710. $this->assertEquals($expected, $result);
  711. Cache::clear('test_view');
  712. Cache::drop('test_view');
  713. }
  714. /**
  715. * Test elementCache method with namespaces and subfolder
  716. *
  717. * @return void
  718. */
  719. public function testElementCacheSubfolder()
  720. {
  721. Cache::drop('test_view');
  722. Cache::setConfig('test_view', [
  723. 'engine' => 'File',
  724. 'duration' => '+1 day',
  725. 'path' => CACHE . 'views/',
  726. 'prefix' => '',
  727. ]);
  728. Cache::clear('test_view');
  729. $View = $this->PostsController->createView();
  730. $View->setElementCache('test_view');
  731. $result = $View->element('subfolder/test_element', [], ['cache' => true]);
  732. $expected = 'this is the test element in subfolder';
  733. $this->assertEquals($expected, trim($result));
  734. $result = Cache::read('element__subfolder_test_element', 'test_view');
  735. $this->assertEquals($expected, trim($result));
  736. }
  737. /**
  738. * Test element events
  739. *
  740. * @return void
  741. */
  742. public function testViewEvent()
  743. {
  744. $View = $this->PostsController->createView();
  745. $View->setTemplatePath($this->PostsController->getName());
  746. $View->enableAutoLayout(false);
  747. $listener = new TestViewEventListenerInterface();
  748. $View->getEventManager()->on($listener);
  749. $View->render('index');
  750. $this->assertEquals(View::TYPE_TEMPLATE, $listener->beforeRenderViewType);
  751. $this->assertEquals(View::TYPE_TEMPLATE, $listener->afterRenderViewType);
  752. $this->assertEquals($View->getCurrentType(), View::TYPE_TEMPLATE);
  753. $View->element('test_element', [], ['callbacks' => true]);
  754. $this->assertEquals($View->getCurrentType(), View::TYPE_TEMPLATE);
  755. $this->assertEquals(View::TYPE_ELEMENT, $listener->beforeRenderViewType);
  756. $this->assertEquals(View::TYPE_ELEMENT, $listener->afterRenderViewType);
  757. }
  758. /**
  759. * Test loading helper using loadHelper().
  760. *
  761. * @return void
  762. */
  763. public function testLoadHelper()
  764. {
  765. $View = new View();
  766. $View->loadHelper('Html', ['foo' => 'bar']);
  767. $this->assertInstanceOf('Cake\View\Helper\HtmlHelper', $View->Html);
  768. $config = $View->Html->getConfig();
  769. $this->assertSame('bar', $config['foo']);
  770. }
  771. /**
  772. * Test loading helper when duplicate.
  773. *
  774. * @return void
  775. */
  776. public function testLoadHelperDuplicate()
  777. {
  778. $View = new View();
  779. $this->assertNotEmpty($View->loadHelper('Html', ['foo' => 'bar']));
  780. try {
  781. $View->loadHelper('Html', ['test' => 'value']);
  782. $this->fail('No exception');
  783. } catch (\RuntimeException $e) {
  784. $this->assertStringContainsString('The "Html" alias has already been loaded', $e->getMessage());
  785. }
  786. }
  787. /**
  788. * Test loadHelpers method
  789. *
  790. * @return void
  791. */
  792. public function testLoadHelpers()
  793. {
  794. $View = new View(null, null, null, [
  795. 'helpers' => ['Html' => ['foo' => 'bar'], 'Form' => ['foo' => 'baz']],
  796. ]);
  797. $result = $View->loadHelpers();
  798. $this->assertSame($View, $result);
  799. $this->assertInstanceOf('Cake\View\Helper\HtmlHelper', $View->Html, 'Object type is wrong.');
  800. $this->assertInstanceOf('Cake\View\Helper\FormHelper', $View->Form, 'Object type is wrong.');
  801. $config = $View->Html->getConfig();
  802. $this->assertSame('bar', $config['foo']);
  803. $config = $View->Form->getConfig();
  804. $this->assertSame('baz', $config['foo']);
  805. }
  806. /**
  807. * Test lazy loading helpers
  808. *
  809. * @return void
  810. */
  811. public function testLazyLoadHelpers()
  812. {
  813. $View = new View();
  814. $this->assertInstanceOf('Cake\View\Helper\HtmlHelper', $View->Html, 'Object type is wrong.');
  815. $this->assertInstanceOf('Cake\View\Helper\FormHelper', $View->Form, 'Object type is wrong.');
  816. }
  817. /**
  818. * Test manipulating class properties in initialize()
  819. *
  820. * @return void
  821. */
  822. public function testInitialize()
  823. {
  824. $View = new TestView();
  825. $config = $View->Html->getConfig();
  826. $this->assertSame('myval', $config['mykey']);
  827. }
  828. /**
  829. * Test the correct triggering of helper callbacks
  830. *
  831. * @return void
  832. */
  833. public function testHelperCallbackTriggering()
  834. {
  835. $View = $this->PostsController->createView();
  836. $View->setTemplatePath($this->PostsController->getName());
  837. $manager = $this->getMockBuilder('Cake\Event\EventManager')->getMock();
  838. $View->setEventManager($manager);
  839. $manager->expects($this->at(0))
  840. ->method('dispatch')
  841. ->with($this->callback(function (EventInterface $event) {
  842. return $event->getName() === 'View.beforeRender';
  843. }));
  844. $manager->expects($this->at(1))
  845. ->method('dispatch')
  846. ->with($this->callback(function (EventInterface $event) {
  847. return $event->getName() === 'View.beforeRenderFile';
  848. }));
  849. $manager->expects($this->at(2))
  850. ->method('dispatch')
  851. ->with($this->callback(function (EventInterface $event) {
  852. return $event->getName() === 'View.afterRenderFile';
  853. }));
  854. $manager->expects($this->at(3))
  855. ->method('dispatch')
  856. ->with($this->callback(function (EventInterface $event) {
  857. return $event->getName() === 'View.afterRender';
  858. }));
  859. $manager->expects($this->at(4))
  860. ->method('dispatch')
  861. ->with($this->callback(function (EventInterface $event) {
  862. return $event->getName() === 'View.beforeLayout';
  863. }));
  864. $manager->expects($this->at(5))
  865. ->method('dispatch')
  866. ->with($this->callback(function (EventInterface $event) {
  867. return $event->getName() === 'View.beforeRenderFile';
  868. }));
  869. $manager->expects($this->at(6))
  870. ->method('dispatch')
  871. ->with($this->callback(function (EventInterface $event) {
  872. return $event->getName() === 'View.afterRenderFile';
  873. }));
  874. $manager->expects($this->at(7))
  875. ->method('dispatch')
  876. ->with($this->callback(function (EventInterface $event) {
  877. return $event->getName() === 'View.afterLayout';
  878. }));
  879. $View->render('index');
  880. }
  881. /**
  882. * Test beforeLayout method
  883. *
  884. * @return void
  885. */
  886. public function testBeforeLayout()
  887. {
  888. $this->PostsController->viewBuilder()->setHelpers([
  889. 'TestBeforeAfter' => ['className' => TestBeforeAfterHelper::class],
  890. 'Html',
  891. ]);
  892. $View = $this->PostsController->createView();
  893. $View->setTemplatePath($this->PostsController->getName());
  894. $View->render('index');
  895. $this->assertSame('Valuation', $View->helpers()->TestBeforeAfter->property);
  896. }
  897. /**
  898. * Test afterLayout method
  899. *
  900. * @return void
  901. */
  902. public function testAfterLayout()
  903. {
  904. $this->PostsController->viewBuilder()->setHelpers([
  905. 'TestBeforeAfter' => ['className' => TestBeforeAfterHelper::class],
  906. 'Html',
  907. ]);
  908. $this->PostsController->set('variable', 'values');
  909. $View = $this->PostsController->createView();
  910. $View->setTemplatePath($this->PostsController->getName());
  911. $content = 'This is my view output';
  912. $result = $View->renderLayout($content, 'default');
  913. $this->assertRegExp('/modified in the afterlife/', $result);
  914. $this->assertRegExp('/This is my view output/', $result);
  915. }
  916. /**
  917. * Test renderLoadHelper method
  918. *
  919. * @return void
  920. */
  921. public function testRenderLoadHelper()
  922. {
  923. $this->PostsController->viewBuilder()->setHelpers(['Form', 'Number']);
  924. $View = $this->PostsController->createView(TestView::class);
  925. $View->setTemplatePath($this->PostsController->getName());
  926. $result = $View->render('index', false);
  927. $this->assertSame('posts index', $result);
  928. $attached = $View->helpers()->loaded();
  929. // HtmlHelper is loaded in TestView::initialize()
  930. $this->assertEquals(['Html', 'Form', 'Number'], $attached);
  931. $this->PostsController->viewBuilder()->setHelpers(
  932. ['Html', 'Form', 'Number', 'TestPlugin.PluggedHelper']
  933. );
  934. $View = $this->PostsController->createView(TestView::class);
  935. $View->setTemplatePath($this->PostsController->getName());
  936. $result = $View->render('index', false);
  937. $this->assertSame('posts index', $result);
  938. $attached = $View->helpers()->loaded();
  939. $expected = ['Html', 'Form', 'Number', 'PluggedHelper'];
  940. $this->assertEquals($expected, $attached, 'Attached helpers are wrong.');
  941. }
  942. /**
  943. * Test render method
  944. *
  945. * @return void
  946. */
  947. public function testRender()
  948. {
  949. $View = $this->PostsController->createView(TestView::class);
  950. $View->setTemplatePath($this->PostsController->getName());
  951. $result = $View->render('index');
  952. $this->assertRegExp("/<meta charset=\"utf-8\"\/>\s*<title>/", $result);
  953. $this->assertRegExp("/<div id=\"content\">\s*posts index\s*<\/div>/", $result);
  954. $this->assertRegExp("/<div id=\"content\">\s*posts index\s*<\/div>/", $result);
  955. $this->PostsController->viewBuilder()->setHelpers(['Html']);
  956. $this->PostsController->setRequest(
  957. $this->PostsController->getRequest()->withParam('action', 'index')
  958. );
  959. Configure::write('Cache.check', true);
  960. $View = $this->PostsController->createView(TestView::class);
  961. $View->setTemplatePath($this->PostsController->getName());
  962. $result = $View->render('index');
  963. $this->assertRegExp("/<meta charset=\"utf-8\"\/>\s*<title>/", $result);
  964. $this->assertRegExp("/<div id=\"content\">\s*posts index\s*<\/div>/", $result);
  965. }
  966. /**
  967. * Test that View::$view works
  968. *
  969. * @return void
  970. */
  971. public function testRenderUsingViewProperty()
  972. {
  973. $View = $this->PostsController->createView(TestView::class);
  974. $View->setTemplatePath($this->PostsController->getName());
  975. $View->setTemplate('cache_form');
  976. $this->assertSame('cache_form', $View->getTemplate());
  977. $result = $View->render();
  978. $this->assertRegExp('/Add User/', $result);
  979. }
  980. /**
  981. * Test that layout set from view file takes precedence over layout set
  982. * as argument to render().
  983. *
  984. * @return void
  985. */
  986. public function testRenderUsingLayoutArgument()
  987. {
  988. $error = new \PDOException();
  989. $error->queryString = 'this is sql string';
  990. $message = 'it works';
  991. $trace = $error->getTrace();
  992. $View = $this->PostsController->createView(TestView::class);
  993. $View->set(compact('error', 'message', 'trace'));
  994. $View->setTemplatePath('Error');
  995. $result = $View->render('pdo_error', 'error');
  996. $this->assertRegExp('/this is sql string/', $result);
  997. $this->assertRegExp('/it works/', $result);
  998. }
  999. /**
  1000. * Test renderLayout()
  1001. *
  1002. * @return void
  1003. */
  1004. public function testRenderLayout()
  1005. {
  1006. $View = $this->PostsController->createView(TestView::class);
  1007. $result = $View->renderLayout('', 'ajax2');
  1008. $this->assertRegExp('/Ajax\!/', $result);
  1009. }
  1010. /**
  1011. * Test render()ing a file in a subdir from a custom viewPath
  1012. * in a plugin.
  1013. *
  1014. * @return void
  1015. */
  1016. public function testGetTemplateFileNameSubdirWithPluginAndViewPath()
  1017. {
  1018. $this->PostsController->setPlugin('TestPlugin');
  1019. $this->PostsController->setName('Posts');
  1020. /** @var \TestApp\View\TestView $View */
  1021. $View = $this->PostsController->createView(TestView::class);
  1022. $View->setTemplatePath('element');
  1023. $pluginPath = TEST_APP . 'Plugin' . DS . 'TestPlugin' . DS;
  1024. $result = $View->getTemplateFileName('sub_dir/sub_element');
  1025. $expected = $pluginPath . 'templates' . DS . 'element' . DS . 'sub_dir' . DS . 'sub_element.php';
  1026. $this->assertPathEquals($expected, $result);
  1027. }
  1028. public function testGetTemplateException()
  1029. {
  1030. $this->expectException(RuntimeException::class);
  1031. $this->expectExceptionMessage('Template name not provided');
  1032. $view = new View();
  1033. $view->render();
  1034. }
  1035. /**
  1036. * Test that view vars can replace the local helper variables
  1037. * and not overwrite the $this->Helper references
  1038. *
  1039. * @return void
  1040. */
  1041. public function testViewVarOverwritingLocalHelperVar()
  1042. {
  1043. $Controller = new ViewPostsController();
  1044. $Controller->set('html', 'I am some test html');
  1045. $View = $Controller->createView();
  1046. $View->setTemplatePath($Controller->getName());
  1047. $result = $View->render('helper_overwrite', false);
  1048. $this->assertRegExp('/I am some test html/', $result);
  1049. $this->assertRegExp('/Test link/', $result);
  1050. }
  1051. /**
  1052. * Test getTemplateFileName method
  1053. *
  1054. * @return void
  1055. */
  1056. public function testViewFileName()
  1057. {
  1058. /** @var \TestApp\View\TestView $View */
  1059. $View = $this->PostsController->createView(TestView::class);
  1060. $View->setTemplatePath('Posts');
  1061. $result = $View->getTemplateFileName('index');
  1062. $this->assertRegExp('/Posts(\/|\\\)index.php/', $result);
  1063. $result = $View->getTemplateFileName('TestPlugin.index');
  1064. $this->assertRegExp('/Posts(\/|\\\)index.php/', $result);
  1065. $result = $View->getTemplateFileName('/Pages/home');
  1066. $this->assertRegExp('/Pages(\/|\\\)home.php/', $result);
  1067. $result = $View->getTemplateFileName('../element/test_element');
  1068. $this->assertRegExp('/element(\/|\\\)test_element.php/', $result);
  1069. $expected = TEST_APP . 'templates' . DS . 'Posts' . DS . 'index.php';
  1070. $result = $View->getTemplateFileName('../Posts/index');
  1071. $this->assertPathEquals($expected, $result);
  1072. }
  1073. /**
  1074. * Test creating a block with capturing output.
  1075. *
  1076. * @return void
  1077. */
  1078. public function testBlockCaptureOverwrite()
  1079. {
  1080. $result = $this->View->start('test');
  1081. $this->assertSame($this->View, $result);
  1082. echo 'Block content';
  1083. $result = $this->View->end();
  1084. $this->assertSame($this->View, $result);
  1085. $this->View->start('test');
  1086. echo 'New content';
  1087. $this->View->end();
  1088. $result = $this->View->fetch('test');
  1089. $this->assertSame('New content', $result);
  1090. }
  1091. /**
  1092. * Test that blocks can be fetched inside a block with the same name
  1093. *
  1094. * @return void
  1095. */
  1096. public function testBlockExtend()
  1097. {
  1098. $this->View->start('test');
  1099. echo 'Block content';
  1100. $this->View->end();
  1101. $this->View->start('test');
  1102. echo $this->View->fetch('test');
  1103. echo 'New content';
  1104. $this->View->end();
  1105. $result = $this->View->fetch('test');
  1106. $this->assertSame('Block contentNew content', $result);
  1107. }
  1108. /**
  1109. * Test creating a block with capturing output.
  1110. *
  1111. * @return void
  1112. */
  1113. public function testBlockCapture()
  1114. {
  1115. $this->View->start('test');
  1116. echo 'Block content';
  1117. $this->View->end();
  1118. $result = $this->View->fetch('test');
  1119. $this->assertSame('Block content', $result);
  1120. }
  1121. /**
  1122. * Test appending to a block with capturing output.
  1123. *
  1124. * @return void
  1125. */
  1126. public function testBlockAppendCapture()
  1127. {
  1128. $this->View->start('test');
  1129. echo 'Content ';
  1130. $this->View->end();
  1131. $result = $this->View->append('test');
  1132. $this->assertSame($this->View, $result);
  1133. echo 'appended';
  1134. $this->View->end();
  1135. $result = $this->View->fetch('test');
  1136. $this->assertSame('Content appended', $result);
  1137. }
  1138. /**
  1139. * Test setting a block's content.
  1140. *
  1141. * @return void
  1142. */
  1143. public function testBlockSet()
  1144. {
  1145. $result = $this->View->assign('test', 'Block content');
  1146. $this->assertSame($this->View, $result);
  1147. $result = $this->View->fetch('test');
  1148. $this->assertSame('Block content', $result);
  1149. }
  1150. /**
  1151. * Test resetting a block's content.
  1152. *
  1153. * @return void
  1154. */
  1155. public function testBlockReset()
  1156. {
  1157. $this->View->assign('test', '');
  1158. $result = $this->View->fetch('test', 'This should not be returned');
  1159. $this->assertSame('', $result);
  1160. }
  1161. /**
  1162. * Test resetting a block's content with reset.
  1163. *
  1164. * @return void
  1165. */
  1166. public function testBlockResetFunc()
  1167. {
  1168. $this->View->assign('test', 'Block content');
  1169. $result = $this->View->fetch('test', 'This should not be returned');
  1170. $this->assertSame('Block content', $result);
  1171. $result = $this->View->reset('test');
  1172. $this->assertSame($this->View, $result);
  1173. $result = $this->View->fetch('test', 'This should not be returned');
  1174. $this->assertSame('', $result);
  1175. }
  1176. /**
  1177. * Test checking a block's existence.
  1178. *
  1179. * @return void
  1180. */
  1181. public function testBlockExist()
  1182. {
  1183. $this->assertFalse($this->View->exists('test'));
  1184. $this->View->assign('test', 'Block content');
  1185. $this->assertTrue($this->View->exists('test'));
  1186. }
  1187. /**
  1188. * Test setting a block's content to null
  1189. *
  1190. * @return void
  1191. */
  1192. public function testBlockSetNull()
  1193. {
  1194. $this->View->assign('testWithNull', null);
  1195. $result = $this->View->fetch('testWithNull');
  1196. $this->assertSame('', $result);
  1197. }
  1198. /**
  1199. * Test setting a block's content to an object with __toString magic method
  1200. *
  1201. * @return void
  1202. */
  1203. public function testBlockSetObjectWithToString()
  1204. {
  1205. $objectWithToString = new TestObjectWithToString();
  1206. $this->View->assign('testWithObjectWithToString', $objectWithToString);
  1207. $result = $this->View->fetch('testWithObjectWithToString');
  1208. $this->assertSame("I'm ObjectWithToString", $result);
  1209. }
  1210. /**
  1211. * Test setting a block's content to an object without __toString magic method
  1212. *
  1213. * @return void
  1214. */
  1215. public function testBlockSetObjectWithoutToString()
  1216. {
  1217. $this->checkException(
  1218. 'Object of class ' . TestObjectWithoutToString::class . ' could not be converted to string'
  1219. );
  1220. $objectWithToString = new TestObjectWithoutToString();
  1221. $this->View->assign('testWithObjectWithoutToString', $objectWithToString);
  1222. }
  1223. /**
  1224. * Test setting a block's content to a decimal
  1225. *
  1226. * @return void
  1227. */
  1228. public function testBlockSetDecimal()
  1229. {
  1230. $this->View->assign('testWithDecimal', 1.23456789);
  1231. $result = $this->View->fetch('testWithDecimal');
  1232. $this->assertSame('1.23456789', $result);
  1233. }
  1234. /**
  1235. * Data provider for block related tests.
  1236. *
  1237. * @return array
  1238. */
  1239. public static function blockValueProvider()
  1240. {
  1241. return [
  1242. 'string' => ['A string value'],
  1243. 'decimal' => [1.23456],
  1244. 'object with __toString' => [new TestObjectWithToString()],
  1245. ];
  1246. }
  1247. /**
  1248. * Test appending to a block with append.
  1249. *
  1250. * @param mixed $value Value
  1251. * @return void
  1252. * @dataProvider blockValueProvider
  1253. */
  1254. public function testBlockAppend($value)
  1255. {
  1256. $this->View->assign('testBlock', 'Block');
  1257. $this->View->append('testBlock', $value);
  1258. $result = $this->View->fetch('testBlock');
  1259. $this->assertSame('Block' . $value, $result);
  1260. }
  1261. /**
  1262. * Test appending an object without __toString magic method to a block with append.
  1263. *
  1264. * @return void
  1265. */
  1266. public function testBlockAppendObjectWithoutToString()
  1267. {
  1268. $this->checkException(
  1269. 'Object of class ' . TestObjectWithoutToString::class . ' could not be converted to string'
  1270. );
  1271. $object = new TestObjectWithoutToString();
  1272. $this->View->assign('testBlock', 'Block ');
  1273. $this->View->append('testBlock', $object);
  1274. }
  1275. /**
  1276. * Test prepending to a block with prepend.
  1277. *
  1278. * @param mixed $value Value
  1279. * @return void
  1280. * @dataProvider blockValueProvider
  1281. */
  1282. public function testBlockPrepend($value)
  1283. {
  1284. $this->View->assign('test', 'Block');
  1285. $result = $this->View->prepend('test', $value);
  1286. $this->assertSame($this->View, $result);
  1287. $result = $this->View->fetch('test');
  1288. $this->assertEquals($value . 'Block', $result);
  1289. }
  1290. /**
  1291. * Test prepending an object without __toString magic method to a block with prepend.
  1292. *
  1293. * @return void
  1294. */
  1295. public function testBlockPrependObjectWithoutToString()
  1296. {
  1297. $this->checkException(
  1298. 'Object of class ' . TestObjectWithoutToString::class . ' could not be converted to string'
  1299. );
  1300. $object = new TestObjectWithoutToString();
  1301. $this->View->assign('test', 'Block ');
  1302. $this->View->prepend('test', $object);
  1303. }
  1304. /**
  1305. * You should be able to append to undefined blocks.
  1306. *
  1307. * @return void
  1308. */
  1309. public function testBlockAppendUndefined()
  1310. {
  1311. $result = $this->View->append('test', 'Unknown');
  1312. $this->assertSame($this->View, $result);
  1313. $result = $this->View->fetch('test');
  1314. $this->assertSame('Unknown', $result);
  1315. }
  1316. /**
  1317. * You should be able to prepend to undefined blocks.
  1318. *
  1319. * @return void
  1320. */
  1321. public function testBlockPrependUndefined()
  1322. {
  1323. $this->View->prepend('test', 'Unknown');
  1324. $result = $this->View->fetch('test');
  1325. $this->assertSame('Unknown', $result);
  1326. }
  1327. /**
  1328. * Test getting block names
  1329. *
  1330. * @return void
  1331. */
  1332. public function testBlocks()
  1333. {
  1334. $this->View->append('test', 'one');
  1335. $this->View->assign('test1', 'one');
  1336. $this->assertEquals(['test', 'test1'], $this->View->blocks());
  1337. }
  1338. /**
  1339. * Test that blocks can be nested.
  1340. *
  1341. * @return void
  1342. */
  1343. public function testNestedBlocks()
  1344. {
  1345. $this->View->start('first');
  1346. echo 'In first ';
  1347. $this->View->start('second');
  1348. echo 'In second';
  1349. $this->View->end();
  1350. echo 'In first';
  1351. $this->View->end();
  1352. $this->assertSame('In first In first', $this->View->fetch('first'));
  1353. $this->assertSame('In second', $this->View->fetch('second'));
  1354. }
  1355. /**
  1356. * Test that starting the same block twice throws an exception
  1357. *
  1358. * @return void
  1359. */
  1360. public function testStartBlocksTwice()
  1361. {
  1362. try {
  1363. $this->View->start('first');
  1364. $this->View->start('first');
  1365. $this->fail('No exception');
  1366. } catch (\Cake\Core\Exception\Exception $e) {
  1367. ob_end_clean();
  1368. $this->assertTrue(true);
  1369. }
  1370. }
  1371. /**
  1372. * Test that an exception gets thrown when you leave a block open at the end
  1373. * of a view.
  1374. *
  1375. * @return void
  1376. */
  1377. public function testExceptionOnOpenBlock()
  1378. {
  1379. try {
  1380. $this->View->render('open_block');
  1381. $this->fail('No exception');
  1382. } catch (\LogicException $e) {
  1383. ob_end_clean();
  1384. $this->assertStringContainsString('The "no_close" block was left open', $e->getMessage());
  1385. }
  1386. }
  1387. /**
  1388. * Test nested extended views.
  1389. *
  1390. * @return void
  1391. */
  1392. public function testExtendNested()
  1393. {
  1394. $content = $this->View->render('nested_extends', false);
  1395. $expected = <<<TEXT
  1396. This is the second parent.
  1397. This is the first parent.
  1398. This is the first template.
  1399. Sidebar Content.
  1400. TEXT;
  1401. $this->assertEquals($expected, $content);
  1402. }
  1403. /**
  1404. * Make sure that extending the current view with itself causes an exception
  1405. *
  1406. * @return void
  1407. */
  1408. public function testExtendSelf()
  1409. {
  1410. try {
  1411. $this->View->render('extend_self', false);
  1412. $this->fail('No exception');
  1413. } catch (\LogicException $e) {
  1414. ob_end_clean();
  1415. $this->assertStringContainsString('cannot have templates extend themselves', $e->getMessage());
  1416. }
  1417. }
  1418. /**
  1419. * Make sure that extending in a loop causes an exception
  1420. *
  1421. * @return void
  1422. */
  1423. public function testExtendLoop()
  1424. {
  1425. try {
  1426. $this->View->render('extend_loop', false);
  1427. $this->fail('No exception');
  1428. } catch (\LogicException $e) {
  1429. ob_end_clean();
  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. ob_end_clean();
  1478. ob_end_clean();
  1479. $this->assertStringContainsString('element', $e->getMessage());
  1480. }
  1481. }
  1482. /**
  1483. * Test extend() preceded by an element()
  1484. *
  1485. * @return void
  1486. */
  1487. public function testExtendWithElementBeforeExtend()
  1488. {
  1489. $result = $this->View->render('extend_with_element', false);
  1490. $expected = <<<TEXT
  1491. Parent View.
  1492. this is the test elementThe view
  1493. TEXT;
  1494. $this->assertEquals($expected, $result);
  1495. }
  1496. /**
  1497. * Test extend() preceded by an element()
  1498. *
  1499. * @return void
  1500. */
  1501. public function testExtendWithPrefixElementBeforeExtend()
  1502. {
  1503. $this->View->setRequest($this->View->getRequest()->withParam('prefix', 'Admin'));
  1504. $this->View->disableAutoLayout();
  1505. $result = $this->View->render('extend_with_element');
  1506. $expected = <<<TEXT
  1507. Parent View.
  1508. this is the test prefix elementThe view
  1509. TEXT;
  1510. $this->assertEquals($expected, $result);
  1511. }
  1512. /**
  1513. * Test memory leaks that existed in _paths at one point.
  1514. *
  1515. * @return void
  1516. */
  1517. public function testMemoryLeakInPaths()
  1518. {
  1519. $this->skipIf((bool)env('CODECOVERAGE'), 'Running coverage this causes this tests to fail sometimes.');
  1520. $this->ThemeController->setName('Posts');
  1521. $View = $this->ThemeController->createView();
  1522. $View->setTemplatePath('Posts');
  1523. $View->setLayout('whatever');
  1524. $View->setTheme('TestTheme');
  1525. $View->element('test_element');
  1526. $start = memory_get_usage();
  1527. for ($i = 0; $i < 10; $i++) {
  1528. $View->element('test_element');
  1529. }
  1530. $end = memory_get_usage();
  1531. $this->assertLessThanOrEqual($start + 15000, $end);
  1532. }
  1533. /**
  1534. * Tests that a view block uses default value when not assigned and uses assigned value when it is
  1535. *
  1536. * @return void
  1537. */
  1538. public function testBlockDefaultValue()
  1539. {
  1540. $default = 'Default';
  1541. $result = $this->View->fetch('title', $default);
  1542. $this->assertEquals($default, $result);
  1543. $expected = 'My Title';
  1544. $this->View->assign('title', $expected);
  1545. $result = $this->View->fetch('title', $default);
  1546. $this->assertEquals($expected, $result);
  1547. }
  1548. /**
  1549. * Tests that a view variable uses default value when not assigned and uses assigned value when it is
  1550. *
  1551. * @return void
  1552. */
  1553. public function testViewVarDefaultValue()
  1554. {
  1555. $default = 'Default';
  1556. $result = $this->View->get('title', $default);
  1557. $this->assertEquals($default, $result);
  1558. $expected = 'Back to the Future';
  1559. $this->View->set('title', $expected);
  1560. $result = $this->View->get('title', $default);
  1561. $this->assertEquals($expected, $result);
  1562. }
  1563. /**
  1564. * Test the helpers() method.
  1565. *
  1566. * @return void
  1567. */
  1568. public function testHelpers()
  1569. {
  1570. $this->assertInstanceOf('Cake\View\HelperRegistry', $this->View->helpers());
  1571. $result = $this->View->helpers();
  1572. $this->assertSame($result, $this->View->helpers());
  1573. }
  1574. /**
  1575. * Test getTemplatePath() and setTemplatePath().
  1576. *
  1577. * @return void
  1578. */
  1579. public function testGetSetTemplatePath()
  1580. {
  1581. $result = $this->View->setTemplatePath('foo');
  1582. $this->assertSame($this->View, $result);
  1583. $templatePath = $this->View->getTemplatePath();
  1584. $this->assertSame($templatePath, 'foo');
  1585. }
  1586. /**
  1587. * Test getLayoutPath() and setLayoutPath().
  1588. *
  1589. * @return void
  1590. */
  1591. public function testGetSetLayoutPath()
  1592. {
  1593. $result = $this->View->setLayoutPath('foo');
  1594. $this->assertSame($this->View, $result);
  1595. $layoutPath = $this->View->getLayoutPath();
  1596. $this->assertSame($layoutPath, 'foo');
  1597. }
  1598. /**
  1599. * Test isAutoLayoutEnabled() and enableAutoLayout().
  1600. *
  1601. * @return void
  1602. */
  1603. public function testAutoLayout()
  1604. {
  1605. $result = $this->View->enableAutoLayout(false);
  1606. $this->assertSame($this->View, $result);
  1607. $autoLayout = $this->View->isAutoLayoutEnabled();
  1608. $this->assertSame($autoLayout, false);
  1609. $this->View->enableAutoLayout();
  1610. $autoLayout = $this->View->isAutoLayoutEnabled();
  1611. $this->assertSame($autoLayout, true);
  1612. }
  1613. /**
  1614. * testDisableAutoLayout
  1615. *
  1616. * @return void
  1617. */
  1618. public function testDisableAutoLayout()
  1619. {
  1620. $this->assertTrue($this->View->isAutoLayoutEnabled());
  1621. $result = $this->View->disableAutoLayout();
  1622. $this->assertSame($this->View, $result);
  1623. $autoLayout = $this->View->isAutoLayoutEnabled();
  1624. $this->assertFalse($this->View->isAutoLayoutEnabled());
  1625. }
  1626. /**
  1627. * Test getTheme() and setTheme().
  1628. *
  1629. * @return void
  1630. */
  1631. public function testGetSetTheme()
  1632. {
  1633. $result = $this->View->setTheme('foo');
  1634. $this->assertSame($this->View, $result);
  1635. $theme = $this->View->getTheme();
  1636. $this->assertSame($theme, 'foo');
  1637. }
  1638. /**
  1639. * Test getTemplate() and setTemplate().
  1640. *
  1641. * @return void
  1642. */
  1643. public function testGetSetTemplate()
  1644. {
  1645. $result = $this->View->setTemplate('foo');
  1646. $this->assertSame($this->View, $result);
  1647. $template = $this->View->getTemplate();
  1648. $this->assertSame($template, 'foo');
  1649. }
  1650. /**
  1651. * Test setLayout() and getLayout().
  1652. *
  1653. * @return void
  1654. */
  1655. public function testGetSetLayout()
  1656. {
  1657. $result = $this->View->setLayout('foo');
  1658. $this->assertSame($this->View, $result);
  1659. $layout = $this->View->getLayout();
  1660. $this->assertSame($layout, 'foo');
  1661. }
  1662. /**
  1663. * Test getName() and getPlugin().
  1664. *
  1665. * @return void
  1666. */
  1667. public function testGetNamePlugin()
  1668. {
  1669. $this->assertSame('Posts', $this->View->getName());
  1670. $this->assertNull($this->View->getPlugin());
  1671. $this->assertSame($this->View, $this->View->setPlugin('TestPlugin'));
  1672. $this->assertSame('TestPlugin', $this->View->getPlugin());
  1673. }
  1674. protected function checkException($message)
  1675. {
  1676. if (version_compare(PHP_VERSION, '7.4', '>=')) {
  1677. $this->expectException(\Error::class);
  1678. } else {
  1679. $this->expectException(\PHPUnit\Framework\Error\Error::class);
  1680. }
  1681. $this->expectExceptionMessage($message);
  1682. }
  1683. }