ControllerTest.php 42 KB

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