ControllerTest.php 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  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(int $code, string $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. * testSetAction method
  414. *
  415. * @return void
  416. * @group deprecated
  417. */
  418. public function testSetAction(): void
  419. {
  420. $this->deprecated(function () {
  421. $request = new ServerRequest(['url' => 'controller/posts/index']);
  422. $TestController = new TestController($request);
  423. $TestController->setAction('view', 1, 2);
  424. $expected = ['testId' => 1, 'test2Id' => 2];
  425. $this->assertSame($expected, $TestController->getRequest()->getData());
  426. $this->assertSame('view', $TestController->getRequest()->getParam('action'));
  427. });
  428. }
  429. /**
  430. * Tests that the startup process calls the correct functions
  431. *
  432. * @return void
  433. */
  434. public function testStartupProcess(): void
  435. {
  436. $eventManager = $this->getMockBuilder('Cake\Event\EventManagerInterface')->getMock();
  437. $controller = new Controller(null, null, null, $eventManager);
  438. $eventManager
  439. ->expects($this->exactly(2))
  440. ->method('dispatch')
  441. ->withConsecutive(
  442. [$this->callback(function (EventInterface $event) {
  443. return $event->getName() === 'Controller.initialize';
  444. })],
  445. [$this->callback(function (EventInterface $event) {
  446. return $event->getName() === 'Controller.startup';
  447. })]
  448. )
  449. ->will($this->returnValue(new Event('stub')));
  450. $controller->startupProcess();
  451. }
  452. /**
  453. * Tests that the shutdown process calls the correct functions
  454. *
  455. * @return void
  456. */
  457. public function testShutdownProcess(): void
  458. {
  459. $eventManager = $this->getMockBuilder('Cake\Event\EventManagerInterface')->getMock();
  460. $controller = new Controller(null, null, null, $eventManager);
  461. $eventManager->expects($this->once())
  462. ->method('dispatch')
  463. ->with($this->callback(function (EventInterface $event) {
  464. return $event->getName() === 'Controller.shutdown';
  465. }))
  466. ->will($this->returnValue(new Event('stub')));
  467. $controller->shutdownProcess();
  468. }
  469. /**
  470. * test using Controller::paginate()
  471. *
  472. * @return void
  473. */
  474. public function testPaginate(): void
  475. {
  476. $request = new ServerRequest(['url' => 'controller_posts/index']);
  477. $response = new Response();
  478. $Controller = new Controller($request, $response);
  479. $Controller->setRequest($Controller->getRequest()->withQueryParams([
  480. 'posts' => [
  481. 'page' => 2,
  482. 'limit' => 2,
  483. ],
  484. ]));
  485. $this->assertEquals([], $Controller->paginate);
  486. $this->assertNotContains('Paginator', $Controller->viewBuilder()->getHelpers());
  487. $this->assertArrayNotHasKey('Paginator', $Controller->viewBuilder()->getHelpers());
  488. $results = $Controller->paginate('Posts');
  489. $this->assertInstanceOf('Cake\Datasource\ResultSetInterface', $results);
  490. $this->assertCount(3, $results);
  491. $results = $Controller->paginate($this->getTableLocator()->get('Posts'));
  492. $this->assertInstanceOf('Cake\Datasource\ResultSetInterface', $results);
  493. $this->assertCount(3, $results);
  494. $paging = $Controller->getRequest()->getAttribute('paging');
  495. $this->assertSame($paging['Posts']['page'], 1);
  496. $this->assertSame($paging['Posts']['pageCount'], 1);
  497. $this->assertFalse($paging['Posts']['prevPage']);
  498. $this->assertFalse($paging['Posts']['nextPage']);
  499. $this->assertNull($paging['Posts']['scope']);
  500. $results = $Controller->paginate($this->getTableLocator()->get('Posts'), ['scope' => 'posts']);
  501. $this->assertInstanceOf('Cake\Datasource\ResultSetInterface', $results);
  502. $this->assertCount(1, $results);
  503. $paging = $Controller->getRequest()->getAttribute('paging');
  504. $this->assertSame($paging['Posts']['page'], 2);
  505. $this->assertSame($paging['Posts']['pageCount'], 2);
  506. $this->assertTrue($paging['Posts']['prevPage']);
  507. $this->assertFalse($paging['Posts']['nextPage']);
  508. $this->assertSame($paging['Posts']['scope'], 'posts');
  509. }
  510. /**
  511. * test that paginate uses modelClass property.
  512. *
  513. * @return void
  514. */
  515. public function testPaginateUsesModelClass(): void
  516. {
  517. $request = new ServerRequest([
  518. 'url' => 'controller_posts/index',
  519. ]);
  520. $response = new Response();
  521. $Controller = new Controller($request, $response);
  522. $Controller->modelClass = 'Posts';
  523. $results = $Controller->paginate();
  524. $this->assertInstanceOf('Cake\Datasource\ResultSetInterface', $results);
  525. }
  526. /**
  527. * testMissingAction method
  528. *
  529. * @return void
  530. */
  531. public function testGetActionMissingAction(): void
  532. {
  533. $this->expectException(\Cake\Controller\Exception\MissingActionException::class);
  534. $this->expectExceptionMessage('Action TestController::missing() could not be found, or is not accessible.');
  535. $url = new ServerRequest([
  536. 'url' => 'test/missing',
  537. 'params' => ['controller' => 'Test', 'action' => 'missing'],
  538. ]);
  539. $response = new Response();
  540. $Controller = new TestController($url, $response);
  541. $Controller->getAction();
  542. }
  543. /**
  544. * test invoking private methods.
  545. *
  546. * @return void
  547. */
  548. public function testGetActionPrivate(): void
  549. {
  550. $this->expectException(\Cake\Controller\Exception\MissingActionException::class);
  551. $this->expectExceptionMessage('Action TestController::private_m() could not be found, or is not accessible.');
  552. $url = new ServerRequest([
  553. 'url' => 'test/private_m/',
  554. 'params' => ['controller' => 'Test', 'action' => 'private_m'],
  555. ]);
  556. $response = new Response();
  557. $Controller = new TestController($url, $response);
  558. $Controller->getAction();
  559. }
  560. /**
  561. * test invoking protected methods.
  562. *
  563. * @return void
  564. */
  565. public function testGetActionProtected(): void
  566. {
  567. $this->expectException(\Cake\Controller\Exception\MissingActionException::class);
  568. $this->expectExceptionMessage('Action TestController::protected_m() could not be found, or is not accessible.');
  569. $url = new ServerRequest([
  570. 'url' => 'test/protected_m/',
  571. 'params' => ['controller' => 'Test', 'action' => 'protected_m'],
  572. ]);
  573. $response = new Response();
  574. $Controller = new TestController($url, $response);
  575. $Controller->getAction();
  576. }
  577. /**
  578. * test invoking controller methods.
  579. *
  580. * @return void
  581. */
  582. public function testGetActionBaseMethods(): void
  583. {
  584. $this->expectException(\Cake\Controller\Exception\MissingActionException::class);
  585. $this->expectExceptionMessage('Action TestController::redirect() could not be found, or is not accessible.');
  586. $url = new ServerRequest([
  587. 'url' => 'test/redirect/',
  588. 'params' => ['controller' => 'Test', 'action' => 'redirect'],
  589. ]);
  590. $response = new Response();
  591. $Controller = new TestController($url, $response);
  592. $Controller->getAction();
  593. }
  594. /**
  595. * test invoking action method with mismatched casing.
  596. *
  597. * @return void
  598. */
  599. public function testGetActionMethodCasing(): void
  600. {
  601. $this->expectException(\Cake\Controller\Exception\MissingActionException::class);
  602. $this->expectExceptionMessage('Action TestController::RETURNER() could not be found, or is not accessible.');
  603. $url = new ServerRequest([
  604. 'url' => 'test/RETURNER/',
  605. 'params' => ['controller' => 'Test', 'action' => 'RETURNER'],
  606. ]);
  607. $response = new Response();
  608. $Controller = new TestController($url, $response);
  609. $Controller->getAction();
  610. }
  611. public function testGetActionArgsReflection(): void
  612. {
  613. $request = new ServerRequest([
  614. 'url' => 'test/reflection/1',
  615. 'params' => [
  616. 'controller' => 'Test',
  617. 'action' => 'reflection',
  618. 'pass' => ['1'],
  619. ],
  620. ]);
  621. $controller = new TestController($request, new Response());
  622. $closure = $controller->getAction();
  623. $args = (new ReflectionFunction($closure))->getParameters();
  624. $this->assertSame('Parameter #0 [ <required> $passed ]', (string)$args[0]);
  625. $this->assertSame('Parameter #1 [ <required> Cake\ORM\Table $table ]', (string)$args[1]);
  626. }
  627. /**
  628. * test invoking controller methods.
  629. *
  630. * @return void
  631. */
  632. public function testInvokeActionReturnValue(): void
  633. {
  634. $url = new ServerRequest([
  635. 'url' => 'test/returner/',
  636. 'params' => [
  637. 'controller' => 'Test',
  638. 'action' => 'returner',
  639. 'pass' => [],
  640. ],
  641. ]);
  642. $response = new Response();
  643. $Controller = new TestController($url, $response);
  644. $Controller->invokeAction($Controller->getAction(), $Controller->getRequest()->getParam('pass'));
  645. $this->assertSame('I am from the controller.', (string)$Controller->getResponse());
  646. }
  647. /**
  648. * test invoking controller methods with passed params
  649. *
  650. * @return void
  651. */
  652. public function testInvokeActionWithPassedParams(): void
  653. {
  654. $request = new ServerRequest([
  655. 'url' => 'test/index/1/2',
  656. 'params' => [
  657. 'controller' => 'Test',
  658. 'action' => 'index',
  659. 'pass' => ['param1' => '1', 'param2' => '2'],
  660. ],
  661. ]);
  662. $controller = new TestController($request, new Response());
  663. $controller->disableAutoRender();
  664. $controller->invokeAction($controller->getAction(), array_values($controller->getRequest()->getParam('pass')));
  665. $this->assertEquals(
  666. ['testId' => '1', 'test2Id' => '2'],
  667. $controller->getRequest()->getData()
  668. );
  669. }
  670. /**
  671. * test invalid return value from action method.
  672. *
  673. * @return void
  674. */
  675. public function testInvokeActionException()
  676. {
  677. $this->expectException(\UnexpectedValueException::class);
  678. $this->expectExceptionMessage(
  679. 'Controller actions can only return ResponseInterface instance or null. '
  680. . 'Got string instead.'
  681. );
  682. $url = new ServerRequest([
  683. 'url' => 'test/willCauseException',
  684. 'params' => [
  685. 'controller' => 'Test',
  686. 'action' => 'willCauseException',
  687. 'pass' => [],
  688. ],
  689. ]);
  690. $response = new Response();
  691. $Controller = new TestController($url, $response);
  692. $Controller->invokeAction($Controller->getAction(), $Controller->getRequest()->getParam('pass'));
  693. }
  694. /**
  695. * test that a classes namespace is used in the viewPath.
  696. *
  697. * @return void
  698. */
  699. public function testViewPathConventions(): void
  700. {
  701. $request = new ServerRequest([
  702. 'url' => 'admin/posts',
  703. 'params' => ['prefix' => 'Admin'],
  704. ]);
  705. $response = new Response();
  706. $Controller = new \TestApp\Controller\Admin\PostsController($request, $response);
  707. $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $e) {
  708. return $e->getSubject()->getResponse();
  709. });
  710. $Controller->render();
  711. $this->assertSame('Admin' . DS . 'Posts', $Controller->viewBuilder()->getTemplatePath());
  712. $request = $request->withParam('prefix', 'admin/super');
  713. $response = new Response();
  714. $Controller = new \TestApp\Controller\Admin\PostsController($request, $response);
  715. $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $e) {
  716. return $e->getSubject()->getResponse();
  717. });
  718. $Controller->render();
  719. $this->assertSame('Admin' . DS . 'Super' . DS . 'Posts', $Controller->viewBuilder()->getTemplatePath());
  720. $request = new ServerRequest([
  721. 'url' => 'pages/home',
  722. 'params' => [
  723. 'prefix' => false,
  724. ],
  725. ]);
  726. $Controller = new \TestApp\Controller\PagesController($request, $response);
  727. $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $e) {
  728. return $e->getSubject()->getResponse();
  729. });
  730. $Controller->render();
  731. $this->assertSame('Pages', $Controller->viewBuilder()->getTemplatePath());
  732. }
  733. /**
  734. * Test the components() method.
  735. *
  736. * @return void
  737. */
  738. public function testComponents(): void
  739. {
  740. $request = new ServerRequest(['url' => '/']);
  741. $response = new Response();
  742. $controller = new TestController($request, $response);
  743. $this->assertInstanceOf('Cake\Controller\ComponentRegistry', $controller->components());
  744. $result = $controller->components();
  745. $this->assertSame($result, $controller->components());
  746. }
  747. /**
  748. * Test the components property errors
  749. *
  750. * @return void
  751. */
  752. public function testComponentsPropertyError(): void
  753. {
  754. $this->expectWarning();
  755. $request = new ServerRequest(['url' => '/']);
  756. $response = new Response();
  757. $controller = new TestController($request, $response);
  758. $controller->components = ['Flash'];
  759. }
  760. /**
  761. * Test the helpers property errors
  762. *
  763. * @return void
  764. */
  765. public function testHelpersPropertyError(): void
  766. {
  767. $this->expectWarning();
  768. $request = new ServerRequest(['url' => '/']);
  769. $response = new Response();
  770. $controller = new TestController($request, $response);
  771. $controller->helpers = ['Flash'];
  772. }
  773. /**
  774. * Test the components() method with the custom ObjectRegistry.
  775. *
  776. * @return void
  777. */
  778. public function testComponentsWithCustomRegistry(): void
  779. {
  780. $request = new ServerRequest(['url' => '/']);
  781. $response = new Response();
  782. $componentRegistry = $this->getMockBuilder('Cake\Controller\ComponentRegistry')
  783. ->addMethods(['offsetGet'])
  784. ->getMock();
  785. $controller = new TestController($request, $response, null, null, $componentRegistry);
  786. $this->assertInstanceOf(get_class($componentRegistry), $controller->components());
  787. $result = $controller->components();
  788. $this->assertSame($result, $controller->components());
  789. }
  790. /**
  791. * Test adding a component
  792. *
  793. * @return void
  794. */
  795. public function testLoadComponent(): void
  796. {
  797. $request = new ServerRequest(['url' => '/']);
  798. $response = new Response();
  799. $controller = new TestController($request, $response);
  800. $result = $controller->loadComponent('Paginator');
  801. $this->assertInstanceOf('Cake\Controller\Component\PaginatorComponent', $result);
  802. $this->assertSame($result, $controller->Paginator);
  803. $registry = $controller->components();
  804. $this->assertTrue(isset($registry->Paginator));
  805. }
  806. /**
  807. * Test adding a component that is a duplicate.
  808. *
  809. * @return void
  810. */
  811. public function testLoadComponentDuplicate(): void
  812. {
  813. $request = new ServerRequest(['url' => '/']);
  814. $response = new Response();
  815. $controller = new TestController($request, $response);
  816. $this->assertNotEmpty($controller->loadComponent('Paginator'));
  817. $this->assertNotEmpty($controller->loadComponent('Paginator'));
  818. try {
  819. $controller->loadComponent('Paginator', ['bad' => 'settings']);
  820. $this->fail('No exception');
  821. } catch (\RuntimeException $e) {
  822. $this->assertStringContainsString('The "Paginator" alias has already been loaded', $e->getMessage());
  823. }
  824. }
  825. /**
  826. * Test the isAction method.
  827. *
  828. * @return void
  829. */
  830. public function testIsAction(): void
  831. {
  832. $request = new ServerRequest(['url' => '/']);
  833. $response = new Response();
  834. $controller = new TestController($request, $response);
  835. $this->assertFalse($controller->isAction('redirect'));
  836. $this->assertFalse($controller->isAction('beforeFilter'));
  837. $this->assertTrue($controller->isAction('index'));
  838. }
  839. /**
  840. * Test that view variables are being set after the beforeRender event gets dispatched
  841. *
  842. * @return void
  843. */
  844. public function testBeforeRenderViewVariables(): void
  845. {
  846. $controller = new PostsController();
  847. $controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $event): void {
  848. /** @var \Cake\Controller\Controller $controller */
  849. $controller = $event->getSubject();
  850. $controller->set('testVariable', 'test');
  851. });
  852. $controller->dispatchEvent('Controller.beforeRender');
  853. $view = $controller->createView();
  854. $this->assertNotEmpty('testVariable', $view->get('testVariable'));
  855. }
  856. /**
  857. * Test that render()'s arguments are available in beforeRender() through view builder.
  858. *
  859. * @return void
  860. */
  861. public function testBeforeRenderTemplateAndLayout()
  862. {
  863. $Controller = new Controller(new ServerRequest(), new Response());
  864. $Controller->getEventManager()->on('Controller.beforeRender', function ($event) {
  865. $this->assertSame(
  866. '/Element/test_element',
  867. $event->getSubject()->viewBuilder()->getTemplate()
  868. );
  869. $this->assertSame(
  870. 'default',
  871. $event->getSubject()->viewBuilder()->getLayout()
  872. );
  873. $event->getSubject()->viewBuilder()
  874. ->setTemplatePath('Posts')
  875. ->setTemplate('index');
  876. });
  877. $result = $Controller->render('/Element/test_element', 'default');
  878. $this->assertMatchesRegularExpression('/posts index/', (string)$result);
  879. }
  880. /**
  881. * Test name getter and setter.
  882. *
  883. * @return void
  884. */
  885. public function testName(): void
  886. {
  887. $controller = new PostsController();
  888. $this->assertSame('Posts', $controller->getName());
  889. $this->assertSame($controller, $controller->setName('Articles'));
  890. $this->assertSame('Articles', $controller->getName());
  891. }
  892. /**
  893. * Test plugin getter and setter.
  894. *
  895. * @return void
  896. */
  897. public function testPlugin(): void
  898. {
  899. $controller = new PostsController();
  900. $this->assertNull($controller->getPlugin());
  901. $this->assertSame($controller, $controller->setPlugin('Articles'));
  902. $this->assertSame('Articles', $controller->getPlugin());
  903. }
  904. /**
  905. * Test request getter and setter.
  906. *
  907. * @return void
  908. */
  909. public function testRequest(): void
  910. {
  911. $controller = new PostsController();
  912. $this->assertInstanceOf(ServerRequest::class, $controller->getRequest());
  913. $request = new ServerRequest([
  914. 'params' => [
  915. 'plugin' => 'Posts',
  916. 'pass' => [
  917. 'foo',
  918. 'bar',
  919. ],
  920. ],
  921. ]);
  922. $this->assertSame($controller, $controller->setRequest($request));
  923. $this->assertSame($request, $controller->getRequest());
  924. $this->assertSame('Posts', $controller->getRequest()->getParam('plugin'));
  925. $this->assertEquals(['foo', 'bar'], $controller->getRequest()->getParam('pass'));
  926. }
  927. /**
  928. * Test response getter and setter.
  929. *
  930. * @return void
  931. */
  932. public function testResponse(): void
  933. {
  934. $controller = new PostsController();
  935. $this->assertInstanceOf(Response::class, $controller->getResponse());
  936. $response = new Response();
  937. $this->assertSame($controller, $controller->setResponse($response));
  938. $this->assertSame($response, $controller->getResponse());
  939. }
  940. /**
  941. * Test autoRender getter and setter.
  942. *
  943. * @return void
  944. */
  945. public function testAutoRender(): void
  946. {
  947. $controller = new PostsController();
  948. $this->assertTrue($controller->isAutoRenderEnabled());
  949. $this->assertSame($controller, $controller->disableAutoRender());
  950. $this->assertFalse($controller->isAutoRenderEnabled());
  951. $this->assertSame($controller, $controller->enableAutoRender());
  952. $this->assertTrue($controller->isAutoRenderEnabled());
  953. }
  954. }