ControllerTest.php 35 KB

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