ViewTest.php 59 KB

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