ControllerTest.php 38 KB

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