ControllerTest.php 42 KB

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