ControllerTest.php 35 KB

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