ControllerTest.php 39 KB

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