ControllerTest.php 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  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. [403, 'Forbidden'],
  438. ];
  439. }
  440. /**
  441. * testRedirect method
  442. *
  443. * @dataProvider statusCodeProvider
  444. */
  445. public function testRedirectByCode(int $code, string $msg): void
  446. {
  447. $Controller = new Controller(null, new Response());
  448. $response = $Controller->redirect('http://cakephp.org', (int)$code);
  449. $this->assertSame($response, $Controller->getResponse());
  450. $this->assertEquals($code, $response->getStatusCode());
  451. $this->assertSame('http://cakephp.org', $response->getHeaderLine('Location'));
  452. $this->assertFalse($Controller->isAutoRenderEnabled());
  453. }
  454. /**
  455. * test that beforeRedirect callbacks can set the URL that is being redirected to.
  456. */
  457. public function testRedirectBeforeRedirectModifyingUrl(): void
  458. {
  459. $Controller = new Controller(null, new Response());
  460. $Controller->getEventManager()->on('Controller.beforeRedirect', function (EventInterface $event, $url, Response $response): void {
  461. $controller = $event->getSubject();
  462. $controller->setResponse($response->withLocation('https://book.cakephp.org'));
  463. });
  464. $response = $Controller->redirect('http://cakephp.org', 301);
  465. $this->assertSame('https://book.cakephp.org', $response->getHeaderLine('Location'));
  466. $this->assertSame(301, $response->getStatusCode());
  467. }
  468. /**
  469. * test that beforeRedirect callback returning null doesn't affect things.
  470. */
  471. public function testRedirectBeforeRedirectModifyingStatusCode(): void
  472. {
  473. $response = new Response();
  474. $Controller = new Controller(null, $response);
  475. $Controller->getEventManager()->on('Controller.beforeRedirect', function (EventInterface $event, $url, Response $response): void {
  476. $controller = $event->getSubject();
  477. $controller->setResponse($response->withStatus(302));
  478. });
  479. $response = $Controller->redirect('http://cakephp.org', 301);
  480. $this->assertSame('http://cakephp.org', $response->getHeaderLine('Location'));
  481. $this->assertSame(302, $response->getStatusCode());
  482. }
  483. public function testRedirectBeforeRedirectListenerReturnResponse(): void
  484. {
  485. $Controller = new Controller(null, new Response());
  486. $newResponse = new Response();
  487. $Controller->getEventManager()->on('Controller.beforeRedirect', function (EventInterface $event, $url, Response $response) use ($newResponse) {
  488. return $newResponse;
  489. });
  490. $result = $Controller->redirect('http://cakephp.org');
  491. $this->assertSame($newResponse, $result);
  492. $this->assertSame($newResponse, $Controller->getResponse());
  493. }
  494. /**
  495. * testReferer method
  496. */
  497. public function testReferer(): void
  498. {
  499. $request = new ServerRequest([
  500. 'environment' => ['HTTP_REFERER' => 'http://localhost/posts/index'],
  501. ]);
  502. $Controller = new Controller($request);
  503. $result = $Controller->referer();
  504. $this->assertSame('/posts/index', $result);
  505. $request = new ServerRequest([
  506. 'environment' => ['HTTP_REFERER' => 'http://localhost/posts/index'],
  507. ]);
  508. $Controller = new Controller($request);
  509. $result = $Controller->referer(['controller' => 'Posts', 'action' => 'index'], true);
  510. $this->assertSame('/posts/index', $result);
  511. $request = $this->getMockBuilder('Cake\Http\ServerRequest')
  512. ->onlyMethods(['referer'])
  513. ->getMock();
  514. $request = new ServerRequest([
  515. 'environment' => ['HTTP_REFERER' => 'http://localhost/posts/index'],
  516. ]);
  517. $Controller = new Controller($request);
  518. $result = $Controller->referer(null, false);
  519. $this->assertSame('http://localhost/posts/index', $result);
  520. $Controller = new Controller(null);
  521. $result = $Controller->referer('/', false);
  522. $this->assertSame('http://localhost/', $result);
  523. }
  524. /**
  525. * Test that the referer is not absolute if it is '/'.
  526. *
  527. * This avoids the base path being applied twice on string urls.
  528. */
  529. public function testRefererSlash(): void
  530. {
  531. $request = new ServerRequest();
  532. $request = $request->withAttribute('base', '/base');
  533. Router::setRequest($request);
  534. $controller = new Controller($request);
  535. $result = $controller->referer('/', true);
  536. $this->assertSame('/', $result);
  537. $controller = new Controller($request);
  538. $result = $controller->referer('/some/path', true);
  539. $this->assertSame('/some/path', $result);
  540. }
  541. /**
  542. * testSetAction method
  543. *
  544. * @group deprecated
  545. */
  546. public function testSetAction(): void
  547. {
  548. $this->deprecated(function (): void {
  549. $request = new ServerRequest(['url' => 'controller/posts/index']);
  550. $TestController = new TestController($request);
  551. $TestController->setAction('view', 1, 2);
  552. $expected = ['testId' => 1, 'test2Id' => 2];
  553. $this->assertSame($expected, $TestController->getRequest()->getData());
  554. $this->assertSame('view', $TestController->getRequest()->getParam('action'));
  555. });
  556. }
  557. /**
  558. * Tests that the startup process calls the correct functions
  559. */
  560. public function testStartupProcess(): void
  561. {
  562. $eventManager = $this->getMockBuilder('Cake\Event\EventManagerInterface')->getMock();
  563. $controller = new Controller(null, null, null, $eventManager);
  564. $eventManager
  565. ->expects($this->exactly(2))
  566. ->method('dispatch')
  567. ->withConsecutive(
  568. [$this->callback(function (EventInterface $event) {
  569. return $event->getName() === 'Controller.initialize';
  570. })],
  571. [$this->callback(function (EventInterface $event) {
  572. return $event->getName() === 'Controller.startup';
  573. })]
  574. )
  575. ->will($this->returnValue(new Event('stub')));
  576. $controller->startupProcess();
  577. }
  578. /**
  579. * Tests that the shutdown process calls the correct functions
  580. */
  581. public function testShutdownProcess(): void
  582. {
  583. $eventManager = $this->getMockBuilder('Cake\Event\EventManagerInterface')->getMock();
  584. $controller = new Controller(null, null, null, $eventManager);
  585. $eventManager->expects($this->once())
  586. ->method('dispatch')
  587. ->with($this->callback(function (EventInterface $event) {
  588. return $event->getName() === 'Controller.shutdown';
  589. }))
  590. ->will($this->returnValue(new Event('stub')));
  591. $controller->shutdownProcess();
  592. }
  593. /**
  594. * test using Controller::paginate()
  595. */
  596. public function testPaginate(): void
  597. {
  598. $request = new ServerRequest(['url' => 'controller_posts/index']);
  599. $response = new Response();
  600. $Controller = new Controller($request, $response);
  601. $Controller->setRequest($Controller->getRequest()->withQueryParams([
  602. 'posts' => [
  603. 'page' => 2,
  604. 'limit' => 2,
  605. ],
  606. ]));
  607. $this->assertEquals([], $Controller->paginate);
  608. $this->assertNotContains('Paginator', $Controller->viewBuilder()->getHelpers());
  609. $this->assertArrayNotHasKey('Paginator', $Controller->viewBuilder()->getHelpers());
  610. $results = $Controller->paginate('Posts');
  611. $this->assertInstanceOf('Cake\Datasource\ResultSetInterface', $results);
  612. $this->assertCount(3, $results);
  613. $results = $Controller->paginate($this->getTableLocator()->get('Posts'));
  614. $this->assertInstanceOf('Cake\Datasource\ResultSetInterface', $results);
  615. $this->assertCount(3, $results);
  616. $paging = $Controller->getRequest()->getAttribute('paging');
  617. $this->assertSame($paging['Posts']['page'], 1);
  618. $this->assertSame($paging['Posts']['pageCount'], 1);
  619. $this->assertFalse($paging['Posts']['prevPage']);
  620. $this->assertFalse($paging['Posts']['nextPage']);
  621. $this->assertNull($paging['Posts']['scope']);
  622. $Controller->paginate = ['className' => 'Numeric'];
  623. $results = $Controller->paginate($this->getTableLocator()->get('Posts'), ['scope' => 'posts']);
  624. $this->assertInstanceOf('Cake\Datasource\ResultSetInterface', $results);
  625. $this->assertCount(1, $results);
  626. $paging = $Controller->getRequest()->getAttribute('paging');
  627. $this->assertSame($paging['Posts']['page'], 2);
  628. $this->assertSame($paging['Posts']['pageCount'], 2);
  629. $this->assertTrue($paging['Posts']['prevPage']);
  630. $this->assertFalse($paging['Posts']['nextPage']);
  631. $this->assertSame($paging['Posts']['scope'], 'posts');
  632. $results = $Controller->paginate(
  633. $this->getTableLocator()->get('Posts'),
  634. ['className' => 'Simple']
  635. );
  636. $this->assertInstanceOf('Cake\Datasource\ResultSetInterface', $results);
  637. $paging = $Controller->getRequest()->getAttribute('paging');
  638. $this->assertSame($paging['Posts']['pageCount'], 0, 'SimplePaginator doesn\'t have a page count');
  639. }
  640. /**
  641. * test that paginate uses modelClass property.
  642. */
  643. public function testPaginateUsesModelClass(): void
  644. {
  645. $request = new ServerRequest([
  646. 'url' => 'controller_posts/index',
  647. ]);
  648. $response = new Response();
  649. $Controller = new Controller($request, $response);
  650. $Controller->modelClass = 'Posts';
  651. $results = $Controller->paginate();
  652. $this->assertInstanceOf('Cake\Datasource\ResultSetInterface', $results);
  653. }
  654. /**
  655. * testMissingAction method
  656. */
  657. public function testGetActionMissingAction(): void
  658. {
  659. $this->expectException(MissingActionException::class);
  660. $this->expectExceptionMessage('Action TestController::missing() could not be found, or is not accessible.');
  661. $url = new ServerRequest([
  662. 'url' => 'test/missing',
  663. 'params' => ['controller' => 'Test', 'action' => 'missing'],
  664. ]);
  665. $response = new Response();
  666. $Controller = new TestController($url, $response);
  667. $Controller->getAction();
  668. }
  669. /**
  670. * test invoking private methods.
  671. */
  672. public function testGetActionPrivate(): void
  673. {
  674. $this->expectException(MissingActionException::class);
  675. $this->expectExceptionMessage('Action TestController::private_m() could not be found, or is not accessible.');
  676. $url = new ServerRequest([
  677. 'url' => 'test/private_m/',
  678. 'params' => ['controller' => 'Test', 'action' => 'private_m'],
  679. ]);
  680. $response = new Response();
  681. $Controller = new TestController($url, $response);
  682. $Controller->getAction();
  683. }
  684. /**
  685. * test invoking protected methods.
  686. */
  687. public function testGetActionProtected(): void
  688. {
  689. $this->expectException(MissingActionException::class);
  690. $this->expectExceptionMessage('Action TestController::protected_m() could not be found, or is not accessible.');
  691. $url = new ServerRequest([
  692. 'url' => 'test/protected_m/',
  693. 'params' => ['controller' => 'Test', 'action' => 'protected_m'],
  694. ]);
  695. $response = new Response();
  696. $Controller = new TestController($url, $response);
  697. $Controller->getAction();
  698. }
  699. /**
  700. * test invoking controller methods.
  701. */
  702. public function testGetActionBaseMethods(): void
  703. {
  704. $this->expectException(MissingActionException::class);
  705. $this->expectExceptionMessage('Action TestController::redirect() could not be found, or is not accessible.');
  706. $url = new ServerRequest([
  707. 'url' => 'test/redirect/',
  708. 'params' => ['controller' => 'Test', 'action' => 'redirect'],
  709. ]);
  710. $response = new Response();
  711. $Controller = new TestController($url, $response);
  712. $Controller->getAction();
  713. }
  714. /**
  715. * test invoking action method with mismatched casing.
  716. */
  717. public function testGetActionMethodCasing(): void
  718. {
  719. $this->expectException(MissingActionException::class);
  720. $this->expectExceptionMessage('Action TestController::RETURNER() could not be found, or is not accessible.');
  721. $url = new ServerRequest([
  722. 'url' => 'test/RETURNER/',
  723. 'params' => ['controller' => 'Test', 'action' => 'RETURNER'],
  724. ]);
  725. $response = new Response();
  726. $Controller = new TestController($url, $response);
  727. $Controller->getAction();
  728. }
  729. public function testGetActionArgsReflection(): void
  730. {
  731. $request = new ServerRequest([
  732. 'url' => 'test/reflection/1',
  733. 'params' => [
  734. 'controller' => 'Test',
  735. 'action' => 'reflection',
  736. 'pass' => ['1'],
  737. ],
  738. ]);
  739. $controller = new TestController($request, new Response());
  740. $closure = $controller->getAction();
  741. $args = (new ReflectionFunction($closure))->getParameters();
  742. $this->assertSame('Parameter #0 [ <required> $passed ]', (string)$args[0]);
  743. $this->assertSame('Parameter #1 [ <required> Cake\ORM\Table $table ]', (string)$args[1]);
  744. }
  745. /**
  746. * test invoking controller methods.
  747. */
  748. public function testInvokeActionReturnValue(): void
  749. {
  750. $url = new ServerRequest([
  751. 'url' => 'test/returner/',
  752. 'params' => [
  753. 'controller' => 'Test',
  754. 'action' => 'returner',
  755. 'pass' => [],
  756. ],
  757. ]);
  758. $response = new Response();
  759. $Controller = new TestController($url, $response);
  760. $Controller->invokeAction($Controller->getAction(), $Controller->getRequest()->getParam('pass'));
  761. $this->assertSame('I am from the controller.', (string)$Controller->getResponse());
  762. }
  763. /**
  764. * test invoking controller methods with passed params
  765. */
  766. public function testInvokeActionWithPassedParams(): void
  767. {
  768. $request = new ServerRequest([
  769. 'url' => 'test/index/1/2',
  770. 'params' => [
  771. 'controller' => 'Test',
  772. 'action' => 'index',
  773. 'pass' => ['param1' => '1', 'param2' => '2'],
  774. ],
  775. ]);
  776. $controller = new TestController($request, new Response());
  777. $controller->disableAutoRender();
  778. $controller->invokeAction($controller->getAction(), array_values($controller->getRequest()->getParam('pass')));
  779. $this->assertEquals(
  780. ['testId' => '1', 'test2Id' => '2'],
  781. $controller->getRequest()->getData()
  782. );
  783. }
  784. /**
  785. * test invalid return value from action method.
  786. */
  787. public function testInvokeActionException(): void
  788. {
  789. $this->expectException(UnexpectedValueException::class);
  790. $this->expectExceptionMessage(
  791. 'Controller actions can only return ResponseInterface instance or null. '
  792. . 'Got string instead.'
  793. );
  794. $url = new ServerRequest([
  795. 'url' => 'test/willCauseException',
  796. 'params' => [
  797. 'controller' => 'Test',
  798. 'action' => 'willCauseException',
  799. 'pass' => [],
  800. ],
  801. ]);
  802. $response = new Response();
  803. $Controller = new TestController($url, $response);
  804. $Controller->invokeAction($Controller->getAction(), $Controller->getRequest()->getParam('pass'));
  805. }
  806. /**
  807. * test that a classes namespace is used in the viewPath.
  808. */
  809. public function testViewPathConventions(): void
  810. {
  811. $request = new ServerRequest([
  812. 'url' => 'admin/posts',
  813. 'params' => ['prefix' => 'Admin'],
  814. ]);
  815. $response = new Response();
  816. $Controller = new AdminPostsController($request, $response);
  817. $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $e) {
  818. return $e->getSubject()->getResponse();
  819. });
  820. $Controller->render();
  821. $this->assertSame('Admin' . DS . 'Posts', $Controller->viewBuilder()->getTemplatePath());
  822. $request = $request->withParam('prefix', 'admin/super');
  823. $response = new Response();
  824. $Controller = new AdminPostsController($request, $response);
  825. $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $e) {
  826. return $e->getSubject()->getResponse();
  827. });
  828. $Controller->render();
  829. $this->assertSame('Admin' . DS . 'Super' . DS . 'Posts', $Controller->viewBuilder()->getTemplatePath());
  830. $request = new ServerRequest([
  831. 'url' => 'pages/home',
  832. 'params' => [
  833. 'prefix' => false,
  834. ],
  835. ]);
  836. $Controller = new PagesController($request, $response);
  837. $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $e) {
  838. return $e->getSubject()->getResponse();
  839. });
  840. $Controller->render();
  841. $this->assertSame('Pages', $Controller->viewBuilder()->getTemplatePath());
  842. }
  843. /**
  844. * Test the components() method.
  845. */
  846. public function testComponents(): void
  847. {
  848. $request = new ServerRequest(['url' => '/']);
  849. $response = new Response();
  850. $controller = new TestController($request, $response);
  851. $this->assertInstanceOf('Cake\Controller\ComponentRegistry', $controller->components());
  852. $result = $controller->components();
  853. $this->assertSame($result, $controller->components());
  854. }
  855. /**
  856. * Test the components property errors
  857. */
  858. public function testComponentsPropertyError(): void
  859. {
  860. $this->expectWarning();
  861. $request = new ServerRequest(['url' => '/']);
  862. $response = new Response();
  863. $controller = new TestController($request, $response);
  864. $controller->components = ['Flash'];
  865. }
  866. /**
  867. * Test the helpers property errors
  868. */
  869. public function testHelpersPropertyError(): void
  870. {
  871. $this->expectWarning();
  872. $request = new ServerRequest(['url' => '/']);
  873. $response = new Response();
  874. $controller = new TestController($request, $response);
  875. $controller->helpers = ['Flash'];
  876. }
  877. /**
  878. * Test the components() method with the custom ObjectRegistry.
  879. */
  880. public function testComponentsWithCustomRegistry(): void
  881. {
  882. $request = new ServerRequest(['url' => '/']);
  883. $response = new Response();
  884. $componentRegistry = $this->getMockBuilder('Cake\Controller\ComponentRegistry')
  885. ->addMethods(['offsetGet'])
  886. ->getMock();
  887. $controller = new TestController($request, $response, null, null, $componentRegistry);
  888. $this->assertInstanceOf(get_class($componentRegistry), $controller->components());
  889. $result = $controller->components();
  890. $this->assertSame($result, $controller->components());
  891. }
  892. /**
  893. * Test adding a component
  894. */
  895. public function testLoadComponent(): void
  896. {
  897. $request = new ServerRequest(['url' => '/']);
  898. $response = new Response();
  899. $controller = new TestController($request, $response);
  900. $result = $controller->loadComponent('FormProtection');
  901. $this->assertInstanceOf('Cake\Controller\Component\FormProtectionComponent', $result);
  902. $this->assertSame($result, $controller->FormProtection);
  903. $registry = $controller->components();
  904. $this->assertTrue(isset($registry->FormProtection));
  905. }
  906. /**
  907. * Test adding a component that is a duplicate.
  908. */
  909. public function testLoadComponentDuplicate(): void
  910. {
  911. $request = new ServerRequest(['url' => '/']);
  912. $response = new Response();
  913. $controller = new TestController($request, $response);
  914. $this->assertNotEmpty($controller->loadComponent('FormProtection'));
  915. $this->assertNotEmpty($controller->loadComponent('FormProtection'));
  916. try {
  917. $controller->loadComponent('FormProtection', ['bad' => 'settings']);
  918. $this->fail('No exception');
  919. } catch (RuntimeException $e) {
  920. $this->assertStringContainsString('The "FormProtection" alias has already been loaded', $e->getMessage());
  921. }
  922. }
  923. /**
  924. * Test the isAction method.
  925. */
  926. public function testIsAction(): void
  927. {
  928. $request = new ServerRequest(['url' => '/']);
  929. $response = new Response();
  930. $controller = new TestController($request, $response);
  931. $this->assertFalse($controller->isAction('redirect'));
  932. $this->assertFalse($controller->isAction('beforeFilter'));
  933. $this->assertTrue($controller->isAction('index'));
  934. }
  935. /**
  936. * Test that view variables are being set after the beforeRender event gets dispatched
  937. */
  938. public function testBeforeRenderViewVariables(): void
  939. {
  940. $controller = new AdminPostsController();
  941. $controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $event): void {
  942. /** @var \Cake\Controller\Controller $controller */
  943. $controller = $event->getSubject();
  944. $controller->set('testVariable', 'test');
  945. });
  946. $controller->dispatchEvent('Controller.beforeRender');
  947. $view = $controller->createView();
  948. $this->assertNotEmpty('testVariable', $view->get('testVariable'));
  949. }
  950. /**
  951. * Test that render()'s arguments are available in beforeRender() through view builder.
  952. */
  953. public function testBeforeRenderTemplateAndLayout(): void
  954. {
  955. $Controller = new Controller(new ServerRequest(), new Response());
  956. $Controller->getEventManager()->on('Controller.beforeRender', function ($event): void {
  957. $this->assertSame(
  958. '/Element/test_element',
  959. $event->getSubject()->viewBuilder()->getTemplate()
  960. );
  961. $this->assertSame(
  962. 'default',
  963. $event->getSubject()->viewBuilder()->getLayout()
  964. );
  965. $event->getSubject()->viewBuilder()
  966. ->setTemplatePath('Posts')
  967. ->setTemplate('index');
  968. });
  969. $result = $Controller->render('/Element/test_element', 'default');
  970. $this->assertMatchesRegularExpression('/posts index/', (string)$result);
  971. }
  972. /**
  973. * Test name getter and setter.
  974. */
  975. public function testName(): void
  976. {
  977. $controller = new AdminPostsController();
  978. $this->assertSame('Posts', $controller->getName());
  979. $this->assertSame($controller, $controller->setName('Articles'));
  980. $this->assertSame('Articles', $controller->getName());
  981. }
  982. /**
  983. * Test plugin getter and setter.
  984. */
  985. public function testPlugin(): void
  986. {
  987. $controller = new AdminPostsController();
  988. $this->assertNull($controller->getPlugin());
  989. $this->assertSame($controller, $controller->setPlugin('Articles'));
  990. $this->assertSame('Articles', $controller->getPlugin());
  991. }
  992. /**
  993. * Test request getter and setter.
  994. */
  995. public function testRequest(): void
  996. {
  997. $controller = new AdminPostsController();
  998. $this->assertInstanceOf(ServerRequest::class, $controller->getRequest());
  999. $request = new ServerRequest([
  1000. 'params' => [
  1001. 'plugin' => 'Posts',
  1002. 'pass' => [
  1003. 'foo',
  1004. 'bar',
  1005. ],
  1006. ],
  1007. ]);
  1008. $this->assertSame($controller, $controller->setRequest($request));
  1009. $this->assertSame($request, $controller->getRequest());
  1010. $this->assertSame('Posts', $controller->getRequest()->getParam('plugin'));
  1011. $this->assertEquals(['foo', 'bar'], $controller->getRequest()->getParam('pass'));
  1012. }
  1013. /**
  1014. * Test response getter and setter.
  1015. */
  1016. public function testResponse(): void
  1017. {
  1018. $controller = new AdminPostsController();
  1019. $this->assertInstanceOf(Response::class, $controller->getResponse());
  1020. $response = new Response();
  1021. $this->assertSame($controller, $controller->setResponse($response));
  1022. $this->assertSame($response, $controller->getResponse());
  1023. }
  1024. /**
  1025. * Test autoRender getter and setter.
  1026. */
  1027. public function testAutoRender(): void
  1028. {
  1029. $controller = new AdminPostsController();
  1030. $this->assertTrue($controller->isAutoRenderEnabled());
  1031. $this->assertSame($controller, $controller->disableAutoRender());
  1032. $this->assertFalse($controller->isAutoRenderEnabled());
  1033. $this->assertSame($controller, $controller->enableAutoRender());
  1034. $this->assertTrue($controller->isAutoRenderEnabled());
  1035. }
  1036. }