ViewTest.php 60 KB

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