ViewTest.php 59 KB

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