CellTest.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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 3.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\View;
  17. use BadMethodCallException;
  18. use Cake\Cache\Cache;
  19. use Cake\Http\Response;
  20. use Cake\Http\ServerRequest;
  21. use Cake\TestSuite\TestCase;
  22. use Cake\View\Cell;
  23. use Cake\View\Exception\MissingCellException;
  24. use Cake\View\Exception\MissingCellTemplateException;
  25. use Cake\View\Exception\MissingTemplateException;
  26. use Cake\View\View;
  27. use TestApp\Controller\CellTraitTestController;
  28. use TestApp\View\Cell\CelloCell;
  29. use TestApp\View\CustomJsonView;
  30. /**
  31. * CellTest class.
  32. *
  33. * For testing both View\Cell & Utility\CellTrait
  34. */
  35. class CellTest extends TestCase
  36. {
  37. /**
  38. * @var \Cake\View\View
  39. */
  40. protected $View;
  41. /**
  42. * setUp method
  43. */
  44. public function setUp(): void
  45. {
  46. parent::setUp();
  47. static::setAppNamespace();
  48. $this->clearPlugins();
  49. $this->loadPlugins(['TestPlugin', 'TestTheme']);
  50. $request = new ServerRequest();
  51. $response = new Response();
  52. $this->View = new View($request, $response);
  53. }
  54. /**
  55. * tearDown method
  56. */
  57. public function tearDown(): void
  58. {
  59. parent::tearDown();
  60. unset($this->View);
  61. }
  62. /**
  63. * Tests basic cell rendering.
  64. */
  65. public function testCellRender(): void
  66. {
  67. $cell = $this->View->cell('Articles::teaserList');
  68. $render = "{$cell}";
  69. $this->assertSame('teaser_list', $cell->viewBuilder()->getTemplate());
  70. $this->assertStringContainsString('<h2>Lorem ipsum</h2>', $render);
  71. $this->assertStringContainsString('<h2>Usectetur adipiscing eli</h2>', $render);
  72. $this->assertStringContainsString('<h2>Topis semper blandit eu non</h2>', $render);
  73. $this->assertStringContainsString('<h2>Suspendisse gravida neque</h2>', $render);
  74. $cell = $this->View->cell('Cello');
  75. $this->assertInstanceOf(CelloCell::class, $cell);
  76. $this->assertSame("Cellos\n", $cell->render());
  77. }
  78. /**
  79. * Tests debug output.
  80. */
  81. public function testDebugInfo(): void
  82. {
  83. $cell = $this->View->cell('Articles::teaserList');
  84. $data = $cell->__debugInfo();
  85. $this->assertArrayHasKey('request', $data);
  86. $this->assertArrayHasKey('response', $data);
  87. $this->assertSame('teaserList', $data['action']);
  88. $this->assertEquals([], $data['args']);
  89. }
  90. /**
  91. * Test __toString() hitting an error when rendering views.
  92. */
  93. public function testCellImplictRenderWithError(): void
  94. {
  95. $capture = function ($errno, $msg): void {
  96. restore_error_handler();
  97. $this->assertSame(E_USER_WARNING, $errno);
  98. $this->assertStringContainsString('Could not render cell - Cell template file', $msg);
  99. };
  100. set_error_handler($capture);
  101. $cell = $this->View->cell('Articles::teaserList');
  102. $cell->viewBuilder()->setTemplate('nope');
  103. (string)$cell;
  104. }
  105. /**
  106. * Tests that we are able pass multiple arguments to cell methods.
  107. *
  108. * This test sets its own error handler, as PHPUnit won't convert
  109. * errors into exceptions when the caller is a __toString() method.
  110. */
  111. public function testCellWithArguments(): void
  112. {
  113. $cell = $this->View->cell('Articles::doEcho', ['dummy', ' message']);
  114. $render = "{$cell}";
  115. $this->assertStringContainsString('dummy message', $render);
  116. }
  117. public function testCellWithNamedArguments(): void
  118. {
  119. $cell = $this->View->cell('Articles::doEcho', ['msg1' => 'dummy', 'msg2' => ' message']);
  120. $render = "{$cell}";
  121. $this->assertStringContainsString('dummy message', $render);
  122. $cell = $this->View->cell('Articles::doEcho', ['msg2' => ' dummy', 'msg1' => 'message']);
  123. $render = "{$cell}";
  124. $this->assertStringContainsString('message dummy', $render);
  125. }
  126. /**
  127. * Tests that cell runs default action when none is provided.
  128. */
  129. public function testDefaultCellAction(): void
  130. {
  131. $appCell = $this->View->cell('Articles');
  132. $this->assertSame('display', $appCell->viewBuilder()->getTemplate());
  133. $this->assertStringContainsString('dummy', "{$appCell}");
  134. $pluginCell = $this->View->cell('TestPlugin.Dummy');
  135. $this->assertStringContainsString('dummy', "{$pluginCell}");
  136. $this->assertSame('display', $pluginCell->viewBuilder()->getTemplate());
  137. }
  138. /**
  139. * Tests that cell action setting the templatePath
  140. */
  141. public function testSettingCellTemplatePathFromAction(): void
  142. {
  143. $appCell = $this->View->cell('Articles::customTemplatePath');
  144. $this->assertStringContainsString('Articles subdir custom_template_path template', "{$appCell}");
  145. $this->assertSame('custom_template_path', $appCell->viewBuilder()->getTemplate());
  146. $this->assertSame(Cell::TEMPLATE_FOLDER . '/Articles/Subdir', $appCell->viewBuilder()->getTemplatePath());
  147. }
  148. /**
  149. * Tests that cell action setting the template using the ViewBuilder renders the correct template
  150. */
  151. public function testSettingCellTemplateFromActionViewBuilder(): void
  152. {
  153. $appCell = $this->View->cell('Articles::customTemplateViewBuilder');
  154. $this->assertStringContainsString('This is the alternate template', "{$appCell}");
  155. $this->assertSame('alternate_teaser_list', $appCell->viewBuilder()->getTemplate());
  156. }
  157. /**
  158. * Tests manual render() invocation.
  159. */
  160. public function testCellManualRender(): void
  161. {
  162. /** @var \TestApp\View\Cell\ArticlesCell $cell */
  163. $cell = $this->View->cell('Articles::doEcho', ['msg1' => 'dummy', 'msg2' => ' message']);
  164. $this->assertStringContainsString('dummy message', $cell->render());
  165. $cell->teaserList();
  166. $this->assertStringContainsString('<h2>Lorem ipsum</h2>', $cell->render('teaser_list'));
  167. }
  168. /**
  169. * Tests manual render() invocation with error
  170. */
  171. public function testCellManualRenderError(): void
  172. {
  173. $cell = $this->View->cell('Articles');
  174. $e = null;
  175. try {
  176. $cell->render('fooBar');
  177. } catch (MissingCellTemplateException $e) {
  178. }
  179. $this->assertNotNull($e);
  180. $message = $e->getMessage();
  181. $this->assertStringContainsString(
  182. str_replace('/', DS, 'Cell template file `cell/Articles/foo_bar.php` could not be found.'),
  183. $message
  184. );
  185. $this->assertStringContainsString('The following paths', $message);
  186. $this->assertStringContainsString(ROOT . DS . 'templates', $message);
  187. $this->assertInstanceOf(MissingTemplateException::class, $e->getPrevious());
  188. }
  189. /**
  190. * Test rendering a cell with a theme.
  191. */
  192. public function testCellRenderThemed(): void
  193. {
  194. $this->View->setTheme('TestTheme');
  195. $cell = $this->View->cell('Articles');
  196. $this->assertEquals($this->View->getTheme(), $cell->viewBuilder()->getTheme());
  197. $this->assertStringContainsString('Themed cell content.', $cell->render());
  198. }
  199. /**
  200. * Test that a cell can render a plugin view.
  201. */
  202. public function testCellRenderPluginTemplate(): void
  203. {
  204. $cell = $this->View->cell('Articles');
  205. $this->assertStringContainsString(
  206. 'TestPlugin Articles/display',
  207. $cell->render('TestPlugin.display')
  208. );
  209. $cell = $this->View->cell('Articles');
  210. $cell->viewBuilder()->setPlugin('TestPlugin');
  211. $this->assertStringContainsString(
  212. 'TestPlugin Articles/display',
  213. $cell->render('display')
  214. );
  215. }
  216. /**
  217. * Tests that using plugin's cells works.
  218. */
  219. public function testPluginCell(): void
  220. {
  221. $cell = $this->View->cell('TestPlugin.Dummy::echoThis', ['msg' => 'hello world!']);
  222. $this->assertStringContainsString('hello world!', "{$cell}");
  223. }
  224. /**
  225. * Tests that using namespaced cells works.
  226. */
  227. public function testNamespacedCell(): void
  228. {
  229. $cell = $this->View->cell('Admin/Menu');
  230. $this->assertStringContainsString('Admin Menu Cell', $cell->render());
  231. }
  232. /**
  233. * Tests that using namespaced cells in plugins works
  234. */
  235. public function testPluginNamespacedCell(): void
  236. {
  237. $cell = $this->View->cell('TestPlugin.Admin/Menu');
  238. $this->assertStringContainsString('Test Plugin Admin Menu Cell', $cell->render());
  239. }
  240. /**
  241. * Test that plugin cells can render other view templates.
  242. */
  243. public function testPluginCellAlternateTemplate(): void
  244. {
  245. $cell = $this->View->cell('TestPlugin.Dummy::echoThis', ['msg' => 'hello world!']);
  246. $cell->viewBuilder()->setTemplate('../../element/translate');
  247. $this->assertStringContainsString('This is a translatable string', "{$cell}");
  248. }
  249. /**
  250. * Test that plugin cells can render other view templates.
  251. */
  252. public function testPluginCellAlternateTemplateRenderParam(): void
  253. {
  254. $cell = $this->View->cell('TestPlugin.Dummy::echoThis', ['msg' => 'hello world!']);
  255. $result = $cell->render('../../element/translate');
  256. $this->assertStringContainsString('This is a translatable string', $result);
  257. }
  258. /**
  259. * Tests that using an nonexistent cell throws an exception.
  260. */
  261. public function testNonExistentCell(): void
  262. {
  263. $this->expectException(MissingCellException::class);
  264. $this->View->cell('Void::echoThis', ['arg1' => 'v1', 'arg2' => 'v2']);
  265. }
  266. /**
  267. * Tests missing method errors
  268. */
  269. public function testCellMissingMethod(): void
  270. {
  271. $this->expectException(BadMethodCallException::class);
  272. $this->expectExceptionMessage('Class `TestApp\View\Cell\ArticlesCell` does not have a `nope` method.');
  273. $cell = $this->View->cell('Articles::nope');
  274. $cell->render();
  275. }
  276. /**
  277. * Test that cell options are passed on.
  278. */
  279. public function testCellOptions(): void
  280. {
  281. /** @var \TestApp\View\Cell\ArticlesCell $cell */
  282. $cell = $this->View->cell('Articles', [], ['limit' => 10, 'nope' => 'nope']);
  283. $this->assertSame(10, $cell->limit);
  284. $this->assertTrue(!isset($cell->nope), 'Not a valid option');
  285. }
  286. /**
  287. * Test that cells get the helper configuration from the view that created them.
  288. */
  289. public function testCellInheritsHelperConfig(): void
  290. {
  291. $request = new ServerRequest();
  292. $response = new Response();
  293. $helpers = ['Url', 'Form', 'Banana'];
  294. $view = new View($request, $response, null, ['helpers' => $helpers]);
  295. $cell = $view->cell('Articles');
  296. $expected = array_combine($helpers, [[], [], []]);
  297. $this->assertSame($expected, $cell->viewBuilder()->getHelpers());
  298. }
  299. /**
  300. * Test that cells the view class name of a custom view passed on.
  301. */
  302. public function testCellInheritsCustomViewClass(): void
  303. {
  304. $request = new ServerRequest();
  305. $response = new Response();
  306. $view = new CustomJsonView($request, $response);
  307. $view->setTheme('Pretty');
  308. $cell = $view->cell('Articles');
  309. $this->assertSame(CustomJsonView::class, $cell->viewBuilder()->getClassName());
  310. $this->assertSame('Pretty', $cell->viewBuilder()->getTheme());
  311. }
  312. /**
  313. * Test that cells the view class name of a controller passed on.
  314. */
  315. public function testCellInheritsController(): void
  316. {
  317. $request = new ServerRequest();
  318. $controller = new CellTraitTestController($request);
  319. $controller->viewBuilder()->setTheme('Pretty');
  320. $controller->viewBuilder()->setClassName('Json');
  321. $cell = $controller->cell('Articles');
  322. $this->assertSame('Json', $cell->viewBuilder()->getClassName());
  323. $this->assertSame('Pretty', $cell->viewBuilder()->getTheme());
  324. }
  325. /**
  326. * Test cached render.
  327. */
  328. public function testCachedRenderSimple(): void
  329. {
  330. Cache::setConfig('default', ['className' => 'Array']);
  331. $cell = $this->View->cell('Articles', [], ['cache' => true]);
  332. $result = $cell->render();
  333. $expected = "dummy\n";
  334. $this->assertSame($expected, $result);
  335. $result = Cache::read('cell_test_app_view_cell_articles_cell_display_default', 'default');
  336. $this->assertSame($expected, $result);
  337. Cache::drop('default');
  338. }
  339. /**
  340. * Test read cached cell.
  341. */
  342. public function testReadCachedCell(): void
  343. {
  344. Cache::setConfig('default', ['className' => 'Array']);
  345. Cache::write('cell_test_app_view_cell_articles_cell_display_default', 'from cache');
  346. $cell = $this->View->cell('Articles', [], ['cache' => true]);
  347. $result = $cell->render();
  348. $this->assertSame('from cache', $result);
  349. Cache::drop('default');
  350. }
  351. /**
  352. * Test cached render array config
  353. */
  354. public function testCachedRenderArrayConfig(): void
  355. {
  356. Cache::setConfig('cell', ['className' => 'Array']);
  357. Cache::write('my_key', 'from cache', 'cell');
  358. $cell = $this->View->cell('Articles', [], [
  359. 'cache' => ['key' => 'my_key', 'config' => 'cell'],
  360. ]);
  361. $result = $cell->render();
  362. $this->assertSame('from cache', $result);
  363. Cache::drop('cell');
  364. }
  365. /**
  366. * Test cached render when using an action changing the template used
  367. */
  368. public function testCachedRenderSimpleCustomTemplate(): void
  369. {
  370. Cache::setConfig('default', ['className' => 'Array']);
  371. $cell = $this->View->cell('Articles::customTemplateViewBuilder', [], ['cache' => true]);
  372. $result = $cell->render();
  373. $expected = 'This is the alternate template';
  374. $this->assertStringContainsString($expected, $result);
  375. $result = Cache::read('cell_test_app_view_cell_articles_cell_customTemplateViewBuilder_default');
  376. $this->assertStringContainsString($expected, $result);
  377. Cache::drop('default');
  378. }
  379. /**
  380. * Test that when the cell cache is enabled, the cell action is only invoke the first
  381. * time the cell is rendered
  382. */
  383. public function testCachedRenderSimpleCustomTemplateViewBuilder(): void
  384. {
  385. Cache::setConfig('default', ['className' => 'Array']);
  386. /** @var \TestApp\View\Cell\ArticlesCell $cell */
  387. $cell = $this->View->cell('Articles::customTemplateViewBuilder', [], ['cache' => ['key' => 'celltest']]);
  388. $result = $cell->render();
  389. $this->assertSame(1, $cell->counter);
  390. $cell->render();
  391. $this->assertSame(1, $cell->counter);
  392. $this->assertStringContainsString('This is the alternate template', $result);
  393. Cache::drop('default');
  394. }
  395. /**
  396. * Test that when the cell cache is enabled, the cell action is only invoke the first
  397. * time the cell is rendered
  398. */
  399. public function testACachedViewCellReRendersWhenGivenADifferentTemplate(): void
  400. {
  401. Cache::setConfig('default', ['className' => 'Array']);
  402. $cell = $this->View->cell('Articles::customTemplateViewBuilder', [], ['cache' => true]);
  403. $result = $cell->render('alternate_teaser_list');
  404. $result2 = $cell->render('not_the_alternate_teaser_list');
  405. $this->assertStringContainsString('This is the alternate template', $result);
  406. $this->assertStringContainsString('This is NOT the alternate template', $result2);
  407. Cache::delete('celltest');
  408. Cache::drop('default');
  409. }
  410. /**
  411. * Tests events are dispatched correctly
  412. */
  413. public function testCellRenderDispatchesEvents(): void
  414. {
  415. $args = ['msg1' => 'dummy', 'msg2' => ' message'];
  416. /** @var \TestApp\View\Cell\ArticlesCell $cell */
  417. $cell = $this->View->cell('Articles::doEcho', $args);
  418. $beforeEventIsCalled = false;
  419. $afterEventIsCalled = false;
  420. $manager = $this->View->getEventManager();
  421. $manager->on('Cell.beforeAction', function ($event, $eventCell, $action, $eventArgs) use ($cell, $args, &$beforeEventIsCalled): void {
  422. $this->assertSame($eventCell, $cell);
  423. $this->assertEquals('doEcho', $action);
  424. $this->assertEquals($args, $eventArgs);
  425. $beforeEventIsCalled = true;
  426. });
  427. $manager->on('Cell.afterAction', function ($event, $eventCell, $action, $eventArgs) use ($cell, $args, &$afterEventIsCalled): void {
  428. $this->assertSame($eventCell, $cell);
  429. $this->assertEquals('doEcho', $action);
  430. $this->assertEquals($args, $eventArgs);
  431. $afterEventIsCalled = true;
  432. });
  433. $cell->render();
  434. $this->assertTrue($beforeEventIsCalled);
  435. $this->assertTrue($afterEventIsCalled);
  436. }
  437. }