ControllerTest.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146
  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. $results = $Controller->paginate($this->getTableLocator()->get('Posts'), ['scope' => 'posts']);
  580. $this->assertInstanceOf('Cake\Datasource\ResultSetInterface', $results);
  581. $this->assertCount(1, $results);
  582. $paging = $Controller->getRequest()->getAttribute('paging');
  583. $this->assertSame($paging['Posts']['page'], 2);
  584. $this->assertSame($paging['Posts']['pageCount'], 2);
  585. $this->assertTrue($paging['Posts']['prevPage']);
  586. $this->assertFalse($paging['Posts']['nextPage']);
  587. $this->assertSame($paging['Posts']['scope'], 'posts');
  588. }
  589. /**
  590. * test that paginate uses modelClass property.
  591. */
  592. public function testPaginateUsesModelClass(): void
  593. {
  594. $request = new ServerRequest([
  595. 'url' => 'controller_posts/index',
  596. ]);
  597. $response = new Response();
  598. $Controller = new Controller($request, $response);
  599. $Controller->modelClass = 'Posts';
  600. $results = $Controller->paginate();
  601. $this->assertInstanceOf('Cake\Datasource\ResultSetInterface', $results);
  602. }
  603. /**
  604. * testMissingAction method
  605. */
  606. public function testGetActionMissingAction(): void
  607. {
  608. $this->expectException(MissingActionException::class);
  609. $this->expectExceptionMessage('Action TestController::missing() could not be found, or is not accessible.');
  610. $url = new ServerRequest([
  611. 'url' => 'test/missing',
  612. 'params' => ['controller' => 'Test', 'action' => 'missing'],
  613. ]);
  614. $response = new Response();
  615. $Controller = new TestController($url, $response);
  616. $Controller->getAction();
  617. }
  618. /**
  619. * test invoking private methods.
  620. */
  621. public function testGetActionPrivate(): void
  622. {
  623. $this->expectException(MissingActionException::class);
  624. $this->expectExceptionMessage('Action TestController::private_m() could not be found, or is not accessible.');
  625. $url = new ServerRequest([
  626. 'url' => 'test/private_m/',
  627. 'params' => ['controller' => 'Test', 'action' => 'private_m'],
  628. ]);
  629. $response = new Response();
  630. $Controller = new TestController($url, $response);
  631. $Controller->getAction();
  632. }
  633. /**
  634. * test invoking protected methods.
  635. */
  636. public function testGetActionProtected(): void
  637. {
  638. $this->expectException(MissingActionException::class);
  639. $this->expectExceptionMessage('Action TestController::protected_m() could not be found, or is not accessible.');
  640. $url = new ServerRequest([
  641. 'url' => 'test/protected_m/',
  642. 'params' => ['controller' => 'Test', 'action' => 'protected_m'],
  643. ]);
  644. $response = new Response();
  645. $Controller = new TestController($url, $response);
  646. $Controller->getAction();
  647. }
  648. /**
  649. * test invoking controller methods.
  650. */
  651. public function testGetActionBaseMethods(): void
  652. {
  653. $this->expectException(MissingActionException::class);
  654. $this->expectExceptionMessage('Action TestController::redirect() could not be found, or is not accessible.');
  655. $url = new ServerRequest([
  656. 'url' => 'test/redirect/',
  657. 'params' => ['controller' => 'Test', 'action' => 'redirect'],
  658. ]);
  659. $response = new Response();
  660. $Controller = new TestController($url, $response);
  661. $Controller->getAction();
  662. }
  663. /**
  664. * test invoking action method with mismatched casing.
  665. */
  666. public function testGetActionMethodCasing(): void
  667. {
  668. $this->expectException(MissingActionException::class);
  669. $this->expectExceptionMessage('Action TestController::RETURNER() could not be found, or is not accessible.');
  670. $url = new ServerRequest([
  671. 'url' => 'test/RETURNER/',
  672. 'params' => ['controller' => 'Test', 'action' => 'RETURNER'],
  673. ]);
  674. $response = new Response();
  675. $Controller = new TestController($url, $response);
  676. $Controller->getAction();
  677. }
  678. public function testGetActionArgsReflection(): void
  679. {
  680. $request = new ServerRequest([
  681. 'url' => 'test/reflection/1',
  682. 'params' => [
  683. 'controller' => 'Test',
  684. 'action' => 'reflection',
  685. 'pass' => ['1'],
  686. ],
  687. ]);
  688. $controller = new TestController($request, new Response());
  689. $closure = $controller->getAction();
  690. $args = (new ReflectionFunction($closure))->getParameters();
  691. $this->assertSame('Parameter #0 [ <required> $passed ]', (string)$args[0]);
  692. $this->assertSame('Parameter #1 [ <required> Cake\ORM\Table $table ]', (string)$args[1]);
  693. }
  694. /**
  695. * test invoking controller methods.
  696. */
  697. public function testInvokeActionReturnValue(): void
  698. {
  699. $url = new ServerRequest([
  700. 'url' => 'test/returner/',
  701. 'params' => [
  702. 'controller' => 'Test',
  703. 'action' => 'returner',
  704. 'pass' => [],
  705. ],
  706. ]);
  707. $response = new Response();
  708. $Controller = new TestController($url, $response);
  709. $Controller->invokeAction($Controller->getAction(), $Controller->getRequest()->getParam('pass'));
  710. $this->assertSame('I am from the controller.', (string)$Controller->getResponse());
  711. }
  712. /**
  713. * test invoking controller methods with passed params
  714. */
  715. public function testInvokeActionWithPassedParams(): void
  716. {
  717. $request = new ServerRequest([
  718. 'url' => 'test/index/1/2',
  719. 'params' => [
  720. 'controller' => 'Test',
  721. 'action' => 'index',
  722. 'pass' => ['param1' => '1', 'param2' => '2'],
  723. ],
  724. ]);
  725. $controller = new TestController($request, new Response());
  726. $controller->disableAutoRender();
  727. $controller->invokeAction($controller->getAction(), array_values($controller->getRequest()->getParam('pass')));
  728. $this->assertEquals(
  729. ['testId' => '1', 'test2Id' => '2'],
  730. $controller->getRequest()->getData()
  731. );
  732. }
  733. /**
  734. * test invalid return value from action method.
  735. */
  736. public function testInvokeActionException(): void
  737. {
  738. $this->expectException(UnexpectedValueException::class);
  739. $this->expectExceptionMessage(
  740. 'Controller actions can only return ResponseInterface instance or null. '
  741. . 'Got string instead.'
  742. );
  743. $url = new ServerRequest([
  744. 'url' => 'test/willCauseException',
  745. 'params' => [
  746. 'controller' => 'Test',
  747. 'action' => 'willCauseException',
  748. 'pass' => [],
  749. ],
  750. ]);
  751. $response = new Response();
  752. $Controller = new TestController($url, $response);
  753. $Controller->invokeAction($Controller->getAction(), $Controller->getRequest()->getParam('pass'));
  754. }
  755. /**
  756. * test that a classes namespace is used in the viewPath.
  757. */
  758. public function testViewPathConventions(): void
  759. {
  760. $request = new ServerRequest([
  761. 'url' => 'admin/posts',
  762. 'params' => ['prefix' => 'Admin'],
  763. ]);
  764. $response = new Response();
  765. $Controller = new AdminPostsController($request, $response);
  766. $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $e) {
  767. return $e->getSubject()->getResponse();
  768. });
  769. $Controller->render();
  770. $this->assertSame('Admin' . DS . 'Posts', $Controller->viewBuilder()->getTemplatePath());
  771. $request = $request->withParam('prefix', 'admin/super');
  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 . 'Super' . DS . 'Posts', $Controller->viewBuilder()->getTemplatePath());
  779. $request = new ServerRequest([
  780. 'url' => 'pages/home',
  781. 'params' => [
  782. 'prefix' => false,
  783. ],
  784. ]);
  785. $Controller = new PagesController($request, $response);
  786. $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $e) {
  787. return $e->getSubject()->getResponse();
  788. });
  789. $Controller->render();
  790. $this->assertSame('Pages', $Controller->viewBuilder()->getTemplatePath());
  791. }
  792. /**
  793. * Test the components() method.
  794. */
  795. public function testComponents(): void
  796. {
  797. $request = new ServerRequest(['url' => '/']);
  798. $response = new Response();
  799. $controller = new TestController($request, $response);
  800. $this->assertInstanceOf('Cake\Controller\ComponentRegistry', $controller->components());
  801. $result = $controller->components();
  802. $this->assertSame($result, $controller->components());
  803. }
  804. /**
  805. * Test the components property errors
  806. */
  807. public function testComponentsPropertyError(): void
  808. {
  809. $this->expectWarning();
  810. $request = new ServerRequest(['url' => '/']);
  811. $response = new Response();
  812. $controller = new TestController($request, $response);
  813. $controller->components = ['Flash'];
  814. }
  815. /**
  816. * Test the helpers property errors
  817. */
  818. public function testHelpersPropertyError(): void
  819. {
  820. $this->expectWarning();
  821. $request = new ServerRequest(['url' => '/']);
  822. $response = new Response();
  823. $controller = new TestController($request, $response);
  824. $controller->helpers = ['Flash'];
  825. }
  826. /**
  827. * Test the components() method with the custom ObjectRegistry.
  828. */
  829. public function testComponentsWithCustomRegistry(): void
  830. {
  831. $request = new ServerRequest(['url' => '/']);
  832. $response = new Response();
  833. $componentRegistry = $this->getMockBuilder('Cake\Controller\ComponentRegistry')
  834. ->addMethods(['offsetGet'])
  835. ->getMock();
  836. $controller = new TestController($request, $response, null, null, $componentRegistry);
  837. $this->assertInstanceOf(get_class($componentRegistry), $controller->components());
  838. $result = $controller->components();
  839. $this->assertSame($result, $controller->components());
  840. }
  841. /**
  842. * Test adding a component
  843. */
  844. public function testLoadComponent(): void
  845. {
  846. $request = new ServerRequest(['url' => '/']);
  847. $response = new Response();
  848. $controller = new TestController($request, $response);
  849. $result = $controller->loadComponent('Paginator');
  850. $this->assertInstanceOf('Cake\Controller\Component\PaginatorComponent', $result);
  851. $this->assertSame($result, $controller->Paginator);
  852. $registry = $controller->components();
  853. $this->assertTrue(isset($registry->Paginator));
  854. }
  855. /**
  856. * Test adding a component that is a duplicate.
  857. */
  858. public function testLoadComponentDuplicate(): void
  859. {
  860. $request = new ServerRequest(['url' => '/']);
  861. $response = new Response();
  862. $controller = new TestController($request, $response);
  863. $this->assertNotEmpty($controller->loadComponent('Paginator'));
  864. $this->assertNotEmpty($controller->loadComponent('Paginator'));
  865. try {
  866. $controller->loadComponent('Paginator', ['bad' => 'settings']);
  867. $this->fail('No exception');
  868. } catch (RuntimeException $e) {
  869. $this->assertStringContainsString('The "Paginator" alias has already been loaded', $e->getMessage());
  870. }
  871. }
  872. /**
  873. * Test the isAction method.
  874. */
  875. public function testIsAction(): void
  876. {
  877. $request = new ServerRequest(['url' => '/']);
  878. $response = new Response();
  879. $controller = new TestController($request, $response);
  880. $this->assertFalse($controller->isAction('redirect'));
  881. $this->assertFalse($controller->isAction('beforeFilter'));
  882. $this->assertTrue($controller->isAction('index'));
  883. }
  884. /**
  885. * Test that view variables are being set after the beforeRender event gets dispatched
  886. */
  887. public function testBeforeRenderViewVariables(): void
  888. {
  889. $controller = new AdminPostsController();
  890. $controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $event): void {
  891. /** @var \Cake\Controller\Controller $controller */
  892. $controller = $event->getSubject();
  893. $controller->set('testVariable', 'test');
  894. });
  895. $controller->dispatchEvent('Controller.beforeRender');
  896. $view = $controller->createView();
  897. $this->assertNotEmpty('testVariable', $view->get('testVariable'));
  898. }
  899. /**
  900. * Test that render()'s arguments are available in beforeRender() through view builder.
  901. */
  902. public function testBeforeRenderTemplateAndLayout(): void
  903. {
  904. $Controller = new Controller(new ServerRequest(), new Response());
  905. $Controller->getEventManager()->on('Controller.beforeRender', function ($event): void {
  906. $this->assertSame(
  907. '/Element/test_element',
  908. $event->getSubject()->viewBuilder()->getTemplate()
  909. );
  910. $this->assertSame(
  911. 'default',
  912. $event->getSubject()->viewBuilder()->getLayout()
  913. );
  914. $event->getSubject()->viewBuilder()
  915. ->setTemplatePath('Posts')
  916. ->setTemplate('index');
  917. });
  918. $result = $Controller->render('/Element/test_element', 'default');
  919. $this->assertMatchesRegularExpression('/posts index/', (string)$result);
  920. }
  921. /**
  922. * Test name getter and setter.
  923. */
  924. public function testName(): void
  925. {
  926. $controller = new AdminPostsController();
  927. $this->assertSame('Posts', $controller->getName());
  928. $this->assertSame($controller, $controller->setName('Articles'));
  929. $this->assertSame('Articles', $controller->getName());
  930. }
  931. /**
  932. * Test plugin getter and setter.
  933. */
  934. public function testPlugin(): void
  935. {
  936. $controller = new AdminPostsController();
  937. $this->assertNull($controller->getPlugin());
  938. $this->assertSame($controller, $controller->setPlugin('Articles'));
  939. $this->assertSame('Articles', $controller->getPlugin());
  940. }
  941. /**
  942. * Test request getter and setter.
  943. */
  944. public function testRequest(): void
  945. {
  946. $controller = new AdminPostsController();
  947. $this->assertInstanceOf(ServerRequest::class, $controller->getRequest());
  948. $request = new ServerRequest([
  949. 'params' => [
  950. 'plugin' => 'Posts',
  951. 'pass' => [
  952. 'foo',
  953. 'bar',
  954. ],
  955. ],
  956. ]);
  957. $this->assertSame($controller, $controller->setRequest($request));
  958. $this->assertSame($request, $controller->getRequest());
  959. $this->assertSame('Posts', $controller->getRequest()->getParam('plugin'));
  960. $this->assertEquals(['foo', 'bar'], $controller->getRequest()->getParam('pass'));
  961. }
  962. /**
  963. * Test response getter and setter.
  964. */
  965. public function testResponse(): void
  966. {
  967. $controller = new AdminPostsController();
  968. $this->assertInstanceOf(Response::class, $controller->getResponse());
  969. $response = new Response();
  970. $this->assertSame($controller, $controller->setResponse($response));
  971. $this->assertSame($response, $controller->getResponse());
  972. }
  973. /**
  974. * Test autoRender getter and setter.
  975. */
  976. public function testAutoRender(): void
  977. {
  978. $controller = new AdminPostsController();
  979. $this->assertTrue($controller->isAutoRenderEnabled());
  980. $this->assertSame($controller, $controller->disableAutoRender());
  981. $this->assertFalse($controller->isAutoRenderEnabled());
  982. $this->assertSame($controller, $controller->enableAutoRender());
  983. $this->assertTrue($controller->isAutoRenderEnabled());
  984. }
  985. }