ControllerTest.php 35 KB

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