ViewTest.php 60 KB

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