ViewTest.php 60 KB

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