ControllerTest.php 37 KB

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