ControllerTest.php 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  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 Project
  13. * @since 1.2.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Controller;
  17. use AssertionError;
  18. use Cake\Controller\Component\FlashComponent;
  19. use Cake\Controller\Component\FormProtectionComponent;
  20. use Cake\Controller\ComponentRegistry;
  21. use Cake\Controller\Controller;
  22. use Cake\Controller\Exception\MissingActionException;
  23. use Cake\Core\Configure;
  24. use Cake\Core\Container;
  25. use Cake\Datasource\Paging\PaginatedInterface;
  26. use Cake\Event\Event;
  27. use Cake\Event\EventInterface;
  28. use Cake\Event\EventManager;
  29. use Cake\Http\Exception\NotFoundException;
  30. use Cake\Http\Response;
  31. use Cake\Http\ServerRequest;
  32. use Cake\Routing\Router;
  33. use Cake\TestSuite\TestCase;
  34. use Cake\View\View;
  35. use Cake\View\XmlView;
  36. use InvalidArgumentException;
  37. use Laminas\Diactoros\Uri;
  38. use Mockery;
  39. use PHPUnit\Framework\Attributes\DataProvider;
  40. use ReflectionFunction;
  41. use RuntimeException;
  42. use TestApp\Controller\Admin\PostsController as AdminPostsController;
  43. use TestApp\Controller\ArticlesController;
  44. use TestApp\Controller\ContentTypesController;
  45. use TestApp\Controller\PagesController;
  46. use TestApp\Controller\PostsController;
  47. use TestApp\Controller\TestController;
  48. use TestApp\Controller\WithDefaultTableController;
  49. use TestApp\Model\Table\ArticlesTable;
  50. use TestApp\Model\Table\PostsTable;
  51. use TestApp\View\PlainTextView;
  52. use TestPlugin\Controller\Admin\CommentsController;
  53. use TestPlugin\Controller\Component\OtherComponent;
  54. use TestPlugin\Controller\TestPluginController;
  55. use TestPlugin\Model\Table\CommentsTable;
  56. use TestPlugin\Model\Table\TestPluginCommentsTable;
  57. /**
  58. * ControllerTest class
  59. */
  60. class ControllerTest extends TestCase
  61. {
  62. /**
  63. * fixtures property
  64. *
  65. * @var list<string>
  66. */
  67. protected array $fixtures = [
  68. 'core.Comments',
  69. 'core.Posts',
  70. ];
  71. /**
  72. * reset environment.
  73. */
  74. public function setUp(): void
  75. {
  76. parent::setUp();
  77. static::setAppNamespace();
  78. Router::reload();
  79. }
  80. /**
  81. * tearDown
  82. */
  83. public function tearDown(): void
  84. {
  85. parent::tearDown();
  86. $this->clearPlugins();
  87. }
  88. /**
  89. * test autoload default table
  90. */
  91. public function testTableAutoload(): void
  92. {
  93. $request = new ServerRequest(['url' => 'controller/posts/index']);
  94. $Controller = new Controller($request, 'Articles');
  95. $this->assertInstanceOf(
  96. ArticlesTable::class,
  97. $Controller->Articles
  98. );
  99. }
  100. /**
  101. * testUndefinedPropertyError
  102. */
  103. public function testUndefinedPropertyError(): void
  104. {
  105. $this->expectNoticeMessageMatches('/Undefined property `Controller::\$Foo` in `.*` on line \d+/', function (): void {
  106. $controller = new Controller(new ServerRequest());
  107. $controller->Foo->baz();
  108. });
  109. }
  110. /**
  111. * testGetTable method
  112. */
  113. public function testGetTable(): void
  114. {
  115. $request = new ServerRequest(['url' => 'controller/posts/index']);
  116. $Controller = new Controller($request);
  117. $this->assertFalse(isset($Controller->Articles));
  118. $result = $Controller->fetchTable('Articles');
  119. $this->assertInstanceOf(
  120. ArticlesTable::class,
  121. $result
  122. );
  123. }
  124. public function testAutoLoadModelUsingDefaultTable(): void
  125. {
  126. Configure::write('App.namespace', 'TestApp');
  127. $Controller = new WithDefaultTableController(new ServerRequest());
  128. $this->assertInstanceOf(PostsTable::class, $Controller->Posts);
  129. Configure::write('App.namespace', 'App');
  130. }
  131. /**
  132. * @link https://github.com/cakephp/cakephp/issues/14804
  133. */
  134. public function testAutoLoadTableUsingFqcn(): void
  135. {
  136. Configure::write('App.namespace', 'TestApp');
  137. $Controller = new ArticlesController(new ServerRequest());
  138. $this->assertInstanceOf(ArticlesTable::class, $Controller->fetchTable());
  139. Configure::write('App.namespace', 'App');
  140. }
  141. public function testGetTableInPlugins(): void
  142. {
  143. $this->loadPlugins(['TestPlugin']);
  144. $Controller = new TestPluginController(new ServerRequest());
  145. $Controller->setPlugin('TestPlugin');
  146. $this->assertFalse(isset($Controller->TestPluginComments));
  147. $result = $Controller->fetchTable('TestPlugin.TestPluginComments');
  148. $this->assertInstanceOf(
  149. TestPluginCommentsTable::class,
  150. $result
  151. );
  152. }
  153. /**
  154. * Test that the constructor sets defaultTable properly.
  155. */
  156. public function testConstructSetDefaultTable(): void
  157. {
  158. $this->loadPlugins(['TestPlugin']);
  159. $request = new ServerRequest();
  160. $controller = new PostsController($request);
  161. $this->assertInstanceOf(PostsTable::class, $controller->fetchTable());
  162. $controller = new AdminPostsController($request);
  163. $this->assertInstanceOf(PostsTable::class, $controller->fetchTable());
  164. $request = $request->withParam('plugin', 'TestPlugin');
  165. $controller = new CommentsController($request);
  166. $this->assertInstanceOf(CommentsTable::class, $controller->fetchTable());
  167. }
  168. /**
  169. * testConstructClassesWithComponents method
  170. */
  171. public function testConstructClassesWithComponents(): void
  172. {
  173. $this->loadPlugins(['TestPlugin']);
  174. $Controller = new TestPluginController(new ServerRequest());
  175. $Controller->loadComponent('TestPlugin.Other');
  176. $this->assertInstanceOf(OtherComponent::class, $Controller->Other);
  177. }
  178. /**
  179. * testRender method
  180. */
  181. public function testRender(): void
  182. {
  183. $this->loadPlugins(['TestPlugin']);
  184. $request = new ServerRequest([
  185. 'url' => 'controller_posts/index',
  186. 'params' => [
  187. 'action' => 'header',
  188. ],
  189. ]);
  190. $Controller = new Controller($request);
  191. $Controller->viewBuilder()->setTemplatePath('Posts');
  192. $result = $Controller->render('index');
  193. $this->assertMatchesRegularExpression('/posts index/', (string)$result);
  194. $Controller->viewBuilder()->setTemplate('index');
  195. $result = $Controller->render();
  196. $this->assertMatchesRegularExpression('/posts index/', (string)$result);
  197. $result = $Controller->render('/element/test_element');
  198. $this->assertMatchesRegularExpression('/this is the test element/', (string)$result);
  199. }
  200. public function testAddViewClasses(): void
  201. {
  202. $request = new ServerRequest([
  203. 'url' => 'controller_posts/index',
  204. ]);
  205. $controller = new ContentTypesController($request);
  206. $this->assertSame([], $controller->viewClasses());
  207. $controller->addViewClasses([PlainTextView::class]);
  208. $this->assertSame([PlainTextView::class], $controller->viewClasses());
  209. $controller->addViewClasses([XmlView::class]);
  210. $this->assertSame([PlainTextView::class, XmlView::class], $controller->viewClasses());
  211. }
  212. /**
  213. * Test that render() will do content negotiation when supported
  214. * by the controller.
  215. */
  216. public function testRenderViewClassesContentNegotiationMatch(): void
  217. {
  218. $request = new ServerRequest([
  219. 'url' => '/',
  220. 'environment' => ['HTTP_ACCEPT' => 'application/json'],
  221. ]);
  222. $controller = new ContentTypesController($request);
  223. $controller->all();
  224. $response = $controller->render();
  225. $this->assertSame('application/json', $response->getHeaderLine('Content-Type'), 'Has correct header');
  226. $this->assertNotEmpty(json_decode($response->getBody() . ''), 'Body should be json');
  227. }
  228. /**
  229. * Test that render() will do content negotiation when supported
  230. * by the controller.
  231. */
  232. public function testRenderViewClassContentNegotiationMatchLast(): void
  233. {
  234. $request = new ServerRequest([
  235. 'url' => '/',
  236. 'environment' => ['HTTP_ACCEPT' => 'application/xml'],
  237. ]);
  238. $controller = new ContentTypesController($request);
  239. $controller->all();
  240. $response = $controller->render();
  241. $this->assertSame(
  242. 'application/xml; charset=UTF-8',
  243. $response->getHeaderLine('Content-Type'),
  244. 'Has correct header'
  245. );
  246. $this->assertStringContainsString('<?xml', $response->getBody() . '');
  247. }
  248. public function testRenderViewClassesContentNegotiationNoMatch(): void
  249. {
  250. $request = new ServerRequest([
  251. 'url' => '/',
  252. 'environment' => ['HTTP_ACCEPT' => 'text/plain'],
  253. 'params' => ['plugin' => null, 'controller' => 'ContentTypes', 'action' => 'all'],
  254. ]);
  255. $controller = new ContentTypesController($request);
  256. $controller->all();
  257. $response = $controller->render();
  258. $this->assertSame('text/html; charset=UTF-8', $response->getHeaderLine('Content-Type'));
  259. $this->assertStringContainsString('hello world', $response->getBody() . '');
  260. }
  261. /**
  262. * Test that render() will skip content-negotiation when a view class is set.
  263. */
  264. public function testRenderViewClassContentNegotiationSkipWithViewClass(): void
  265. {
  266. $request = new ServerRequest([
  267. 'url' => '/',
  268. 'environment' => ['HTTP_ACCEPT' => 'application/xml'],
  269. 'params' => ['plugin' => null, 'controller' => 'ContentTypes', 'action' => 'all'],
  270. ]);
  271. $controller = new ContentTypesController($request);
  272. $controller->all();
  273. $controller->viewBuilder()->setClassName(View::class);
  274. $response = $controller->render();
  275. $this->assertSame(
  276. 'text/html; charset=UTF-8',
  277. $response->getHeaderLine('Content-Type'),
  278. 'Should not be XML response.'
  279. );
  280. $this->assertStringContainsString('hello world', $response->getBody() . '');
  281. }
  282. /**
  283. * Test that render() will do content negotiation when supported
  284. * by the controller.
  285. */
  286. public function testRenderViewClassesContentNegotiationMatchAllType(): void
  287. {
  288. $request = new ServerRequest([
  289. 'url' => '/',
  290. 'environment' => ['HTTP_ACCEPT' => 'text/html'],
  291. ]);
  292. $controller = new ContentTypesController($request);
  293. $controller->matchAll();
  294. $response = $controller->render();
  295. $this->assertSame('text/html; charset=UTF-8', $response->getHeaderLine('Content-Type'), 'Default response type');
  296. $this->assertEmpty($response->getBody() . '', 'Body should be empty');
  297. $this->assertSame(406, $response->getStatusCode(), 'status code is wrong');
  298. }
  299. public function testRenderViewClassesSetContentTypeHeader(): void
  300. {
  301. $request = new ServerRequest([
  302. 'url' => '/',
  303. 'environment' => ['HTTP_ACCEPT' => 'text/plain'],
  304. 'params' => ['plugin' => null, 'controller' => 'ContentTypes', 'action' => 'plain'],
  305. ]);
  306. $controller = new ContentTypesController($request);
  307. $controller->plain();
  308. $response = $controller->render();
  309. $this->assertSame('text/plain; charset=UTF-8', $response->getHeaderLine('Content-Type'));
  310. $this->assertStringContainsString('hello world', $response->getBody() . '');
  311. }
  312. public function testRenderViewClassesUsesSingleMimeExt(): void
  313. {
  314. $request = new ServerRequest([
  315. 'url' => '/',
  316. 'environment' => [],
  317. 'params' => ['plugin' => null, 'controller' => 'ContentTypes', 'action' => 'all', '_ext' => 'json'],
  318. ]);
  319. $controller = new ContentTypesController($request);
  320. $controller->all();
  321. $response = $controller->render();
  322. $this->assertSame('application/json', $response->getHeaderLine('Content-Type'));
  323. $this->assertNotEmpty(json_decode($response->getBody() . ''), 'Body should be json');
  324. }
  325. public function testRenderViewClassesUsesMultiMimeExt(): void
  326. {
  327. $request = new ServerRequest([
  328. 'url' => '/',
  329. 'environment' => [],
  330. 'params' => ['plugin' => null, 'controller' => 'ContentTypes', 'action' => 'all', '_ext' => 'xml'],
  331. ]);
  332. $controller = new ContentTypesController($request);
  333. $controller->all();
  334. $response = $controller->render();
  335. $this->assertSame('application/xml; charset=UTF-8', $response->getHeaderLine('Content-Type'));
  336. $this->assertTextStartsWith('<?xml', $response->getBody() . '', 'Body should be xml');
  337. }
  338. public function testRenderViewClassesMineExtMissingView(): void
  339. {
  340. $request = new ServerRequest([
  341. 'url' => '/',
  342. 'environment' => [],
  343. 'params' => ['plugin' => null, 'controller' => 'ContentTypes', 'action' => 'all', '_ext' => 'json'],
  344. ]);
  345. $controller = new ContentTypesController($request);
  346. $controller->plain();
  347. $this->expectException(NotFoundException::class);
  348. $controller->render();
  349. }
  350. /**
  351. * test view rendering changing response
  352. */
  353. public function testRenderViewChangesResponse(): void
  354. {
  355. $request = new ServerRequest([
  356. 'url' => 'controller_posts/index',
  357. 'params' => [
  358. 'action' => 'header',
  359. ],
  360. ]);
  361. $controller = new Controller($request);
  362. $controller->viewBuilder()->setTemplatePath('Posts');
  363. $result = $controller->render('header');
  364. $this->assertStringContainsString('header template', (string)$result);
  365. $this->assertTrue($controller->getResponse()->hasHeader('X-view-template'));
  366. $this->assertSame('yes', $controller->getResponse()->getHeaderLine('X-view-template'));
  367. }
  368. /**
  369. * test that a component beforeRender can change the controller view class.
  370. */
  371. public function testBeforeRenderCallbackChangingViewClass(): void
  372. {
  373. $Controller = new Controller(new ServerRequest());
  374. $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $event): void {
  375. $controller = $event->getSubject();
  376. $controller->viewBuilder()->setClassName('Json');
  377. });
  378. $Controller->set([
  379. 'test' => 'value',
  380. ]);
  381. $Controller->viewBuilder()->setOption('serialize', ['test']);
  382. $debug = Configure::read('debug');
  383. Configure::write('debug', false);
  384. $result = $Controller->render('index');
  385. $this->assertSame('{"test":"value"}', (string)$result->getBody());
  386. Configure::write('debug', $debug);
  387. }
  388. /**
  389. * test that a component beforeRender can change the controller view class.
  390. */
  391. public function testBeforeRenderEventCancelsRender(): void
  392. {
  393. $Controller = new Controller(new ServerRequest());
  394. $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $event) {
  395. return false;
  396. });
  397. $result = $Controller->render('index');
  398. $this->assertInstanceOf(Response::class, $result);
  399. }
  400. public function testControllerRedirect(): void
  401. {
  402. $Controller = new Controller(new ServerRequest());
  403. $uri = new Uri('/foo/bar');
  404. $response = $Controller->redirect($uri);
  405. $this->assertSame('http://localhost/foo/bar', $response->getHeaderLine('Location'));
  406. $Controller = new Controller(new ServerRequest());
  407. $uri = new Uri('http://cakephp.org/foo/bar');
  408. $response = $Controller->redirect($uri);
  409. $this->assertSame('http://cakephp.org/foo/bar', $response->getHeaderLine('Location'));
  410. }
  411. /**
  412. * Generates status codes for redirect test.
  413. *
  414. * @return array
  415. */
  416. public static function statusCodeProvider(): array
  417. {
  418. return [
  419. [300, 'Multiple Choices'],
  420. [301, 'Moved Permanently'],
  421. [302, 'Found'],
  422. [303, 'See Other'],
  423. [304, 'Not Modified'],
  424. [305, 'Use Proxy'],
  425. [307, 'Temporary Redirect'],
  426. ];
  427. }
  428. /**
  429. * testRedirect method
  430. */
  431. #[DataProvider('statusCodeProvider')]
  432. public function testRedirectByCode(int $code, string $msg): void
  433. {
  434. $Controller = new Controller(new ServerRequest());
  435. $response = $Controller->redirect('http://cakephp.org', (int)$code);
  436. $this->assertSame($response, $Controller->getResponse());
  437. $this->assertEquals($code, $response->getStatusCode());
  438. $this->assertSame('http://cakephp.org', $response->getHeaderLine('Location'));
  439. $this->assertFalse($Controller->isAutoRenderEnabled());
  440. }
  441. /**
  442. * test that beforeRedirect callbacks can set the URL that is being redirected to.
  443. */
  444. public function testRedirectBeforeRedirectModifyingUrl(): void
  445. {
  446. $Controller = new Controller(new ServerRequest());
  447. $Controller->getEventManager()->on('Controller.beforeRedirect', function (EventInterface $event, $url, Response $response): void {
  448. $controller = $event->getSubject();
  449. $controller->setResponse($response->withLocation('https://book.cakephp.org'));
  450. });
  451. $response = $Controller->redirect('http://cakephp.org', 301);
  452. $this->assertSame('https://book.cakephp.org', $response->getHeaderLine('Location'));
  453. $this->assertSame(301, $response->getStatusCode());
  454. }
  455. /**
  456. * test that beforeRedirect callback returning null doesn't affect things.
  457. */
  458. public function testRedirectBeforeRedirectModifyingStatusCode(): void
  459. {
  460. $Controller = new Controller(new ServerRequest());
  461. $Controller->getEventManager()->on('Controller.beforeRedirect', function (EventInterface $event, $url, Response $response): void {
  462. $controller = $event->getSubject();
  463. $controller->setResponse($response->withStatus(302));
  464. });
  465. $response = $Controller->redirect('http://cakephp.org', 301);
  466. $this->assertSame('http://cakephp.org', $response->getHeaderLine('Location'));
  467. $this->assertSame(302, $response->getStatusCode());
  468. }
  469. public function testRedirectBeforeRedirectListenerReturnResponse(): void
  470. {
  471. $Controller = new Controller(new ServerRequest());
  472. $newResponse = new Response();
  473. $Controller->getEventManager()->on('Controller.beforeRedirect', function (EventInterface $event, $url, Response $response) use ($newResponse) {
  474. return $newResponse;
  475. });
  476. $result = $Controller->redirect('http://cakephp.org');
  477. $this->assertSame($newResponse, $result);
  478. $this->assertSame($newResponse, $Controller->getResponse());
  479. }
  480. public function testRedirectWithInvalidStatusCode(): void
  481. {
  482. $Controller = new Controller(new ServerRequest());
  483. $uri = new Uri('/foo/bar');
  484. $this->expectException(InvalidArgumentException::class);
  485. $Controller->redirect($uri, 200);
  486. }
  487. /**
  488. * testReferer method
  489. */
  490. public function testReferer(): void
  491. {
  492. $request = new ServerRequest([
  493. 'environment' => ['HTTP_REFERER' => 'http://localhost/posts/index'],
  494. ]);
  495. $Controller = new Controller($request);
  496. $result = $Controller->referer();
  497. $this->assertSame('/posts/index', $result);
  498. $request = new ServerRequest([
  499. 'environment' => ['HTTP_REFERER' => 'http://localhost/posts/index'],
  500. ]);
  501. $Controller = new Controller($request);
  502. $result = $Controller->referer(['controller' => 'Posts', 'action' => 'index'], true);
  503. $this->assertSame('/posts/index', $result);
  504. $request = new ServerRequest([
  505. 'environment' => ['HTTP_REFERER' => 'http://localhost/posts/index'],
  506. ]);
  507. $Controller = new Controller($request);
  508. $result = $Controller->referer(null, false);
  509. $this->assertSame('http://localhost/posts/index', $result);
  510. $Controller = new Controller(new ServerRequest());
  511. $result = $Controller->referer('/', false);
  512. $this->assertSame('http://localhost/', $result);
  513. }
  514. /**
  515. * Test that the referer is not absolute if it is '/'.
  516. *
  517. * This avoids the base path being applied twice on string urls.
  518. */
  519. public function testRefererSlash(): void
  520. {
  521. $request = new ServerRequest();
  522. $request = $request->withAttribute('base', '/base');
  523. Router::setRequest($request);
  524. $controller = new Controller($request);
  525. $result = $controller->referer('/', true);
  526. $this->assertSame('/', $result);
  527. $controller = new Controller($request);
  528. $result = $controller->referer('/some/path', true);
  529. $this->assertSame('/some/path', $result);
  530. }
  531. /**
  532. * Tests that the startup process calls the correct functions
  533. */
  534. public function testStartupProcess(): void
  535. {
  536. $eventManager = Mockery::mock(EventManager::class)->makePartial();
  537. $eventManager->shouldReceive('dispatch')
  538. ->withArgs(function ($event) {
  539. return $event->getName() === 'Controller.initialize';
  540. })
  541. ->once()
  542. ->andReturn(new Event('stub'));
  543. $eventManager->shouldReceive('dispatch')
  544. ->withArgs(function ($event) {
  545. return $event->getName() === 'Controller.startup';
  546. })
  547. ->once()
  548. ->andReturn(new Event('stub'));
  549. $controller = new Controller(new ServerRequest(), null, $eventManager);
  550. $this->assertNull($controller->startupProcess());
  551. }
  552. /**
  553. * Tests that the shutdown process calls the correct functions
  554. */
  555. public function testShutdownProcess(): void
  556. {
  557. $eventManager = Mockery::mock(EventManager::class)->makePartial();
  558. $eventManager->shouldReceive('dispatch')
  559. ->withArgs(function ($event) {
  560. return $event->getName() === 'Controller.shutdown';
  561. })
  562. ->once()
  563. ->andReturn(new Event('stub'));
  564. $controller = new Controller(new ServerRequest(), null, $eventManager);
  565. $this->assertNull($controller->shutdownProcess());
  566. }
  567. /**
  568. * test using Controller::paginate()
  569. */
  570. public function testPaginate(): void
  571. {
  572. $request = new ServerRequest(['url' => 'controller_posts/index']);
  573. $Controller = new Controller($request);
  574. $Controller->setRequest($Controller->getRequest()->withQueryParams([
  575. 'posts' => [
  576. 'page' => 2,
  577. 'limit' => 2,
  578. ],
  579. ]));
  580. $this->assertNotContains('Paginator', $Controller->viewBuilder()->getHelpers());
  581. $this->assertArrayNotHasKey('Paginator', $Controller->viewBuilder()->getHelpers());
  582. $results = $Controller->paginate('Posts');
  583. $this->assertInstanceOf(PaginatedInterface::class, $results);
  584. $this->assertCount(3, $results);
  585. $results = $Controller->paginate($this->getTableLocator()->get('Posts'));
  586. $this->assertInstanceOf(PaginatedInterface::class, $results);
  587. $this->assertCount(3, $results);
  588. $this->assertSame($results->currentPage(), 1);
  589. $this->assertSame($results->pageCount(), 1);
  590. $this->assertFalse($results->hasPrevPage());
  591. $this->assertFalse($results->hasPrevPage());
  592. $this->assertNull($results->pagingParam('scope'));
  593. $results = $Controller->paginate(
  594. $this->getTableLocator()->get('Posts'),
  595. ['scope' => 'posts', 'className' => 'Numeric']
  596. );
  597. $this->assertInstanceOf(PaginatedInterface::class, $results);
  598. $this->assertCount(1, $results);
  599. $this->assertSame($results->currentPage(), 2);
  600. $this->assertSame($results->pageCount(), 2);
  601. $this->assertTrue($results->hasPrevPage());
  602. $this->assertFalse($results->hasNextPage());
  603. $this->assertSame($results->pagingParam('scope'), 'posts');
  604. $results = $Controller->paginate(
  605. $this->getTableLocator()->get('Posts'),
  606. ['className' => 'Simple']
  607. );
  608. $this->assertInstanceOf(PaginatedInterface::class, $results);
  609. $this->assertNull($results->pageCount(), "SimplePaginator doesn't have a page count");
  610. }
  611. /**
  612. * test that paginate uses modelClass property.
  613. */
  614. public function testPaginateUsesModelClass(): void
  615. {
  616. $request = new ServerRequest([
  617. 'url' => 'controller_posts/index',
  618. ]);
  619. $Controller = new Controller($request, 'Posts');
  620. $results = $Controller->paginate();
  621. $this->assertInstanceOf(PaginatedInterface::class, $results);
  622. }
  623. public function testPaginateException(): void
  624. {
  625. $this->expectException(NotFoundException::class);
  626. $request = new ServerRequest(['url' => 'controller_posts/index?page=2&limit=100']);
  627. $Controller = new Controller($request, 'Posts');
  628. $Controller->paginate();
  629. }
  630. /**
  631. * testMissingAction method
  632. */
  633. public function testGetActionMissingAction(): void
  634. {
  635. $this->expectException(MissingActionException::class);
  636. $this->expectExceptionMessage('Action `TestController::missing()` could not be found, or is not accessible.');
  637. $url = new ServerRequest([
  638. 'url' => 'test/missing',
  639. 'params' => ['controller' => 'Test', 'action' => 'missing'],
  640. ]);
  641. $Controller = new TestController($url);
  642. $Controller->getAction();
  643. }
  644. /**
  645. * test invoking private methods.
  646. */
  647. public function testGetActionPrivate(): void
  648. {
  649. $this->expectException(MissingActionException::class);
  650. $this->expectExceptionMessage('Action `TestController::private_m()` could not be found, or is not accessible.');
  651. $url = new ServerRequest([
  652. 'url' => 'test/private_m/',
  653. 'params' => ['controller' => 'Test', 'action' => 'private_m'],
  654. ]);
  655. $Controller = new TestController($url);
  656. $Controller->getAction();
  657. }
  658. /**
  659. * test invoking protected methods.
  660. */
  661. public function testGetActionProtected(): void
  662. {
  663. $this->expectException(MissingActionException::class);
  664. $this->expectExceptionMessage('Action `TestController::protected_m()` could not be found, or is not accessible.');
  665. $url = new ServerRequest([
  666. 'url' => 'test/protected_m/',
  667. 'params' => ['controller' => 'Test', 'action' => 'protected_m'],
  668. ]);
  669. $Controller = new TestController($url);
  670. $Controller->getAction();
  671. }
  672. /**
  673. * test invoking controller methods.
  674. */
  675. public function testGetActionBaseMethods(): void
  676. {
  677. $this->expectException(MissingActionException::class);
  678. $this->expectExceptionMessage('Action `TestController::redirect()` could not be found, or is not accessible.');
  679. $url = new ServerRequest([
  680. 'url' => 'test/redirect/',
  681. 'params' => ['controller' => 'Test', 'action' => 'redirect'],
  682. ]);
  683. $Controller = new TestController($url);
  684. $Controller->getAction();
  685. }
  686. /**
  687. * test invoking action method with mismatched casing.
  688. */
  689. public function testGetActionMethodCasing(): void
  690. {
  691. $this->expectException(MissingActionException::class);
  692. $this->expectExceptionMessage('Action `TestController::RETURNER()` could not be found, or is not accessible.');
  693. $url = new ServerRequest([
  694. 'url' => 'test/RETURNER/',
  695. 'params' => ['controller' => 'Test', 'action' => 'RETURNER'],
  696. ]);
  697. $Controller = new TestController($url);
  698. $Controller->getAction();
  699. }
  700. public function testGetActionArgsReflection(): void
  701. {
  702. $request = new ServerRequest([
  703. 'url' => 'test/reflection/1',
  704. 'params' => [
  705. 'controller' => 'Test',
  706. 'action' => 'reflection',
  707. 'pass' => ['1'],
  708. ],
  709. ]);
  710. $controller = new TestController($request);
  711. $closure = $controller->getAction();
  712. $args = (new ReflectionFunction($closure))->getParameters();
  713. $this->assertSame('Parameter #0 [ <required> $passed ]', (string)$args[0]);
  714. $this->assertSame('Parameter #1 [ <required> Cake\ORM\Table $table ]', (string)$args[1]);
  715. }
  716. /**
  717. * test invoking controller methods.
  718. */
  719. public function testInvokeActionReturnValue(): void
  720. {
  721. $url = new ServerRequest([
  722. 'url' => 'test/returner/',
  723. 'params' => [
  724. 'controller' => 'Test',
  725. 'action' => 'returner',
  726. 'pass' => [],
  727. ],
  728. ]);
  729. $Controller = new TestController($url);
  730. $Controller->invokeAction($Controller->getAction(), $Controller->getRequest()->getParam('pass'));
  731. $this->assertSame('I am from the controller.', (string)$Controller->getResponse());
  732. }
  733. /**
  734. * test invoking controller methods with passed params
  735. */
  736. public function testInvokeActionWithPassedParams(): void
  737. {
  738. $request = new ServerRequest([
  739. 'url' => 'test/index/1/2',
  740. 'params' => [
  741. 'controller' => 'Test',
  742. 'action' => 'index',
  743. 'pass' => ['param1' => '1', 'param2' => '2'],
  744. ],
  745. ]);
  746. $controller = new TestController($request);
  747. $controller->disableAutoRender();
  748. $controller->invokeAction($controller->getAction(), array_values($controller->getRequest()->getParam('pass')));
  749. $this->assertEquals(
  750. ['testId' => '1', 'test2Id' => '2'],
  751. $controller->getRequest()->getData()
  752. );
  753. }
  754. /**
  755. * test invalid return value from action method.
  756. */
  757. public function testInvokeActionException(): void
  758. {
  759. $this->expectException(AssertionError::class);
  760. $this->expectExceptionMessage(
  761. 'Controller actions can only return Response instance or null. '
  762. . 'Got string instead.'
  763. );
  764. $url = new ServerRequest([
  765. 'url' => 'test/willCauseException',
  766. 'params' => [
  767. 'controller' => 'Test',
  768. 'action' => 'willCauseException',
  769. 'pass' => [],
  770. ],
  771. ]);
  772. $Controller = new TestController($url);
  773. $Controller->invokeAction($Controller->getAction(), $Controller->getRequest()->getParam('pass'));
  774. }
  775. /**
  776. * test that a classes namespace is used in the viewPath.
  777. */
  778. public function testViewPathConventions(): void
  779. {
  780. $request = new ServerRequest([
  781. 'url' => 'admin/posts',
  782. 'params' => ['prefix' => 'Admin'],
  783. ]);
  784. $Controller = new AdminPostsController($request);
  785. $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $e) {
  786. return $e->getSubject()->getResponse();
  787. });
  788. $Controller->render();
  789. $this->assertSame('Admin' . DS . 'Posts', $Controller->viewBuilder()->getTemplatePath());
  790. $request = $request->withParam('prefix', 'admin/super');
  791. $Controller = new AdminPostsController($request);
  792. $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $e) {
  793. return $e->getSubject()->getResponse();
  794. });
  795. $Controller->render();
  796. $this->assertSame('Admin' . DS . 'Super' . DS . 'Posts', $Controller->viewBuilder()->getTemplatePath());
  797. $request = new ServerRequest([
  798. 'url' => 'pages/home',
  799. 'params' => [
  800. 'prefix' => false,
  801. ],
  802. ]);
  803. $Controller = new PagesController($request);
  804. $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $e) {
  805. return $e->getSubject()->getResponse();
  806. });
  807. $Controller->render();
  808. $this->assertSame('Pages', $Controller->viewBuilder()->getTemplatePath());
  809. }
  810. /**
  811. * Test the components() method.
  812. */
  813. public function testComponents(): void
  814. {
  815. $request = new ServerRequest(['url' => '/']);
  816. $controller = new TestController($request);
  817. $this->assertInstanceOf(ComponentRegistry::class, $controller->components());
  818. $result = $controller->components();
  819. $this->assertSame($result, $controller->components());
  820. }
  821. /**
  822. * Test adding a component
  823. */
  824. public function testLoadComponent(): void
  825. {
  826. $request = new ServerRequest(['url' => '/']);
  827. $controller = new TestController($request);
  828. $result = $controller->loadComponent('FormProtection');
  829. $this->assertInstanceOf(FormProtectionComponent::class, $result);
  830. $this->assertSame($result, $controller->FormProtection);
  831. $registry = $controller->components();
  832. $this->assertTrue(isset($registry->FormProtection));
  833. }
  834. /**
  835. * Test adding a component that is a duplicate.
  836. */
  837. public function testLoadComponentDuplicate(): void
  838. {
  839. $request = new ServerRequest(['url' => '/']);
  840. $controller = new TestController($request);
  841. $this->assertNotEmpty($controller->loadComponent('FormProtection'));
  842. $this->assertNotEmpty($controller->loadComponent('FormProtection'));
  843. try {
  844. $controller->loadComponent('FormProtection', ['bad' => 'settings']);
  845. $this->fail('No exception');
  846. } catch (RuntimeException $e) {
  847. $this->assertStringContainsString('The `FormProtection` alias has already been loaded', $e->getMessage());
  848. }
  849. }
  850. /**
  851. * Test adding a component with container passed to controller
  852. */
  853. public function testLoadComponentWithContainer(): void
  854. {
  855. $container = new Container();
  856. $container->add(FlashComponent::class, function (ComponentRegistry $registry, array $config) {
  857. return new FlashComponent($registry, $config);
  858. })
  859. ->addArgument(ComponentRegistry::class)
  860. ->addArgument(['key' => 'customFlash']);
  861. $request = new ServerRequest(['url' => '/']);
  862. $controller = new TestController($request);
  863. $result = $controller->loadComponent('Flash');
  864. $this->assertInstanceOf(FlashComponent::class, $result);
  865. $this->assertSame($result, $controller->Flash);
  866. $registry = $controller->components();
  867. $this->assertTrue(isset($registry->Flash));
  868. }
  869. /**
  870. * Test the isAction method.
  871. */
  872. public function testIsAction(): void
  873. {
  874. $request = new ServerRequest(['url' => '/']);
  875. $controller = new TestController($request);
  876. $this->assertFalse($controller->isAction('redirect'));
  877. $this->assertFalse($controller->isAction('beforeFilter'));
  878. $this->assertTrue($controller->isAction('index'));
  879. }
  880. /**
  881. * Test that view variables are being set after the beforeRender event gets dispatched
  882. */
  883. public function testBeforeRenderViewVariables(): void
  884. {
  885. $controller = new AdminPostsController(new ServerRequest());
  886. $controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $event): void {
  887. /** @var \Cake\Controller\Controller $controller */
  888. $controller = $event->getSubject();
  889. $controller->set('testVariable', 'test');
  890. });
  891. $controller->dispatchEvent('Controller.beforeRender');
  892. $view = $controller->createView();
  893. $this->assertNotEmpty('testVariable', $view->get('testVariable'));
  894. }
  895. /**
  896. * Test that render()'s arguments are available in beforeRender() through view builder.
  897. */
  898. public function testBeforeRenderTemplateAndLayout(): void
  899. {
  900. $Controller = new Controller(new ServerRequest());
  901. $Controller->getEventManager()->on('Controller.beforeRender', function ($event): void {
  902. $this->assertSame(
  903. '/Element/test_element',
  904. $event->getSubject()->viewBuilder()->getTemplate()
  905. );
  906. $this->assertSame(
  907. 'default',
  908. $event->getSubject()->viewBuilder()->getLayout()
  909. );
  910. $event->getSubject()->viewBuilder()
  911. ->setTemplatePath('Posts')
  912. ->setTemplate('index');
  913. });
  914. $result = $Controller->render('/Element/test_element', 'default');
  915. $this->assertMatchesRegularExpression('/posts index/', (string)$result);
  916. }
  917. /**
  918. * Test name getter and setter.
  919. */
  920. public function testName(): void
  921. {
  922. $controller = new AdminPostsController(new ServerRequest());
  923. $this->assertSame('Posts', $controller->getName());
  924. $this->assertSame($controller, $controller->setName('Articles'));
  925. $this->assertSame('Articles', $controller->getName());
  926. }
  927. /**
  928. * Test plugin getter and setter.
  929. */
  930. public function testPlugin(): void
  931. {
  932. $controller = new AdminPostsController(new ServerRequest());
  933. $this->assertNull($controller->getPlugin());
  934. $this->assertSame($controller, $controller->setPlugin('Articles'));
  935. $this->assertSame('Articles', $controller->getPlugin());
  936. }
  937. /**
  938. * Test request getter and setter.
  939. */
  940. public function testRequest(): void
  941. {
  942. $controller = new AdminPostsController(new ServerRequest());
  943. $this->assertInstanceOf(ServerRequest::class, $controller->getRequest());
  944. $request = new ServerRequest([
  945. 'params' => [
  946. 'plugin' => 'Posts',
  947. 'pass' => [
  948. 'foo',
  949. 'bar',
  950. ],
  951. ],
  952. ]);
  953. $this->assertSame($controller, $controller->setRequest($request));
  954. $this->assertSame($request, $controller->getRequest());
  955. $this->assertSame('Posts', $controller->getRequest()->getParam('plugin'));
  956. $this->assertEquals(['foo', 'bar'], $controller->getRequest()->getParam('pass'));
  957. }
  958. /**
  959. * Test response getter and setter.
  960. */
  961. public function testResponse(): void
  962. {
  963. $controller = new AdminPostsController(new ServerRequest());
  964. $this->assertInstanceOf(Response::class, $controller->getResponse());
  965. $response = new Response();
  966. $this->assertSame($controller, $controller->setResponse($response));
  967. $this->assertSame($response, $controller->getResponse());
  968. }
  969. /**
  970. * Test autoRender getter and setter.
  971. */
  972. public function testAutoRender(): void
  973. {
  974. $controller = new AdminPostsController(new ServerRequest());
  975. $this->assertTrue($controller->isAutoRenderEnabled());
  976. $this->assertSame($controller, $controller->disableAutoRender());
  977. $this->assertFalse($controller->isAutoRenderEnabled());
  978. $this->assertSame($controller, $controller->enableAutoRender());
  979. $this->assertTrue($controller->isAutoRenderEnabled());
  980. }
  981. }