Controller.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 0.2.9
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Controller;
  16. use Cake\Controller\Exception\MissingActionException;
  17. use Cake\Datasource\ModelAwareTrait;
  18. use Cake\Event\Event;
  19. use Cake\Event\EventDispatcherInterface;
  20. use Cake\Event\EventDispatcherTrait;
  21. use Cake\Event\EventListenerInterface;
  22. use Cake\Http\Response;
  23. use Cake\Http\ServerRequest;
  24. use Cake\Log\LogTrait;
  25. use Cake\ORM\Locator\LocatorAwareTrait;
  26. use Cake\Routing\RequestActionTrait;
  27. use Cake\Routing\Router;
  28. use Cake\Utility\MergeVariablesTrait;
  29. use Cake\View\ViewVarsTrait;
  30. use LogicException;
  31. use ReflectionClass;
  32. use ReflectionException;
  33. use ReflectionMethod;
  34. use RuntimeException;
  35. /**
  36. * Application controller class for organization of business logic.
  37. * Provides basic functionality, such as rendering views inside layouts,
  38. * automatic model availability, redirection, callbacks, and more.
  39. *
  40. * Controllers should provide a number of 'action' methods. These are public
  41. * methods on a controller that are not inherited from `Controller`.
  42. * Each action serves as an endpoint for performing a specific action on a
  43. * resource or collection of resources. For example adding or editing a new
  44. * object, or listing a set of objects.
  45. *
  46. * You can access request parameters, using `$this->request`. The request object
  47. * contains all the POST, GET and FILES that were part of the request.
  48. *
  49. * After performing the required action, controllers are responsible for
  50. * creating a response. This usually takes the form of a generated `View`, or
  51. * possibly a redirection to another URL. In either case `$this->response`
  52. * allows you to manipulate all aspects of the response.
  53. *
  54. * Controllers are created by `Dispatcher` based on request parameters and
  55. * routing. By default controllers and actions use conventional names.
  56. * For example `/posts/index` maps to `PostsController::index()`. You can re-map
  57. * URLs using Router::connect() or RouterBuilder::connect().
  58. *
  59. * ### Life cycle callbacks
  60. *
  61. * CakePHP fires a number of life cycle callbacks during each request.
  62. * By implementing a method you can receive the related events. The available
  63. * callbacks are:
  64. *
  65. * - `beforeFilter(Event $event)`
  66. * Called before each action. This is a good place to do general logic that
  67. * applies to all actions.
  68. * - `beforeRender(Event $event)`
  69. * Called before the view is rendered.
  70. * - `beforeRedirect(Event $event, $url, Response $response)`
  71. * Called before a redirect is done.
  72. * - `afterFilter(Event $event)`
  73. * Called after each action is complete and after the view is rendered.
  74. *
  75. * @property \Cake\Controller\Component\AuthComponent $Auth
  76. * @property \Cake\Controller\Component\CookieComponent $Cookie
  77. * @property \Cake\Controller\Component\CsrfComponent $Csrf
  78. * @property \Cake\Controller\Component\FlashComponent $Flash
  79. * @property \Cake\Controller\Component\PaginatorComponent $Paginator
  80. * @property \Cake\Controller\Component\RequestHandlerComponent $RequestHandler
  81. * @property \Cake\Controller\Component\SecurityComponent $Security
  82. * @method bool isAuthorized($user)
  83. * @link https://book.cakephp.org/3.0/en/controllers.html
  84. */
  85. class Controller implements EventListenerInterface, EventDispatcherInterface
  86. {
  87. use EventDispatcherTrait;
  88. use LocatorAwareTrait;
  89. use LogTrait;
  90. use MergeVariablesTrait;
  91. use ModelAwareTrait;
  92. use RequestActionTrait;
  93. use ViewVarsTrait;
  94. /**
  95. * The name of this controller. Controller names are plural, named after the model they manipulate.
  96. *
  97. * Set automatically using conventions in Controller::__construct().
  98. *
  99. * @var string
  100. */
  101. protected $name;
  102. /**
  103. * An array containing the names of helpers this controller uses. The array elements should
  104. * not contain the "Helper" part of the class name.
  105. *
  106. * Example:
  107. * ```
  108. * public $helpers = ['Form', 'Html', 'Time'];
  109. * ```
  110. *
  111. * @var array
  112. * @link https://book.cakephp.org/3.0/en/controllers.html#configuring-helpers-to-load
  113. *
  114. * @deprecated 3.0.0 You should configure helpers in your AppView::initialize() method.
  115. */
  116. public $helpers = [];
  117. /**
  118. * An instance of a \Cake\Http\ServerRequest object that contains information about the current request.
  119. * This object contains all the information about a request and several methods for reading
  120. * additional information about the request.
  121. *
  122. * Deprecated 3.6.0: The property will become protected in 4.0.0. Use getRequest()/setRequest instead.
  123. *
  124. * @var \Cake\Http\ServerRequest
  125. * @link https://book.cakephp.org/3.0/en/controllers/request-response.html#request
  126. */
  127. public $request;
  128. /**
  129. * An instance of a Response object that contains information about the impending response
  130. *
  131. * Deprecated 3.6.0: The property will become protected in 4.0.0. Use getResponse()/setResponse instead.
  132. * @var \Cake\Http\Response
  133. * @link https://book.cakephp.org/3.0/en/controllers/request-response.html#response
  134. */
  135. public $response;
  136. /**
  137. * The class name to use for creating the response object.
  138. *
  139. * @var string
  140. */
  141. protected $_responseClass = Response::class;
  142. /**
  143. * Settings for pagination.
  144. *
  145. * Used to pre-configure pagination preferences for the various
  146. * tables your controller will be paginating.
  147. *
  148. * @var array
  149. * @see \Cake\Controller\Component\PaginatorComponent
  150. */
  151. public $paginate = [];
  152. /**
  153. * Set to true to automatically render the view
  154. * after action logic.
  155. *
  156. * @var bool
  157. */
  158. protected $autoRender = true;
  159. /**
  160. * Instance of ComponentRegistry used to create Components
  161. *
  162. * @var \Cake\Controller\ComponentRegistry
  163. */
  164. protected $_components;
  165. /**
  166. * Array containing the names of components this controller uses. Component names
  167. * should not contain the "Component" portion of the class name.
  168. *
  169. * Example:
  170. * ```
  171. * public $components = ['RequestHandler', 'Acl'];
  172. * ```
  173. *
  174. * @var array
  175. * @link https://book.cakephp.org/3.0/en/controllers/components.html
  176. *
  177. * @deprecated 3.0.0 You should configure components in your Controller::initialize() method.
  178. */
  179. public $components = [];
  180. /**
  181. * Instance of the View created during rendering. Won't be set until after
  182. * Controller::render() is called.
  183. *
  184. * @var \Cake\View\View
  185. * @deprecated 3.1.0 Use viewBuilder() instead.
  186. */
  187. public $View;
  188. /**
  189. * These Controller properties will be passed from the Controller to the View as options.
  190. *
  191. * @var array
  192. * @see \Cake\View\View
  193. * @deprecated 3.7.0 Use ViewBuilder::setOptions() or any one of it's setter methods instead.
  194. */
  195. protected $_validViewOptions = [
  196. 'passedArgs'
  197. ];
  198. /**
  199. * Automatically set to the name of a plugin.
  200. *
  201. * @var string|null
  202. */
  203. protected $plugin;
  204. /**
  205. * Holds all passed params.
  206. *
  207. * @var array
  208. * @deprecated 3.1.0 Use `$this->request->getParam('pass')` instead.
  209. */
  210. public $passedArgs = [];
  211. /**
  212. * Constructor.
  213. *
  214. * Sets a number of properties based on conventions if they are empty. To override the
  215. * conventions CakePHP uses you can define properties in your class declaration.
  216. *
  217. * @param \Cake\Http\ServerRequest|null $request Request object for this controller. Can be null for testing,
  218. * but expect that features that use the request parameters will not work.
  219. * @param \Cake\Http\Response|null $response Response object for this controller.
  220. * @param string|null $name Override the name useful in testing when using mocks.
  221. * @param \Cake\Event\EventManager|null $eventManager The event manager. Defaults to a new instance.
  222. * @param \Cake\Controller\ComponentRegistry|null $components The component registry. Defaults to a new instance.
  223. */
  224. public function __construct(ServerRequest $request = null, Response $response = null, $name = null, $eventManager = null, $components = null)
  225. {
  226. if ($name !== null) {
  227. $this->name = $name;
  228. }
  229. if ($this->name === null && $request && $request->getParam('controller')) {
  230. $this->name = $request->getParam('controller');
  231. }
  232. if ($this->name === null) {
  233. list(, $name) = namespaceSplit(get_class($this));
  234. $this->name = substr($name, 0, -10);
  235. }
  236. $this->setRequest($request ?: new ServerRequest());
  237. $this->response = $response ?: new Response();
  238. if ($eventManager !== null) {
  239. $this->setEventManager($eventManager);
  240. }
  241. $this->modelFactory('Table', [$this->getTableLocator(), 'get']);
  242. $plugin = $this->request->getParam('plugin');
  243. $modelClass = ($plugin ? $plugin . '.' : '') . $this->name;
  244. $this->_setModelClass($modelClass);
  245. if ($components !== null) {
  246. $this->components($components);
  247. }
  248. $this->initialize();
  249. $this->_mergeControllerVars();
  250. $this->_loadComponents();
  251. $this->getEventManager()->on($this);
  252. }
  253. /**
  254. * Initialization hook method.
  255. *
  256. * Implement this method to avoid having to overwrite
  257. * the constructor and call parent.
  258. *
  259. * @return void
  260. */
  261. public function initialize()
  262. {
  263. }
  264. /**
  265. * Get the component registry for this controller.
  266. *
  267. * If called with the first parameter, it will be set as the controller $this->_components property
  268. *
  269. * @param \Cake\Controller\ComponentRegistry|null $components Component registry.
  270. *
  271. * @return \Cake\Controller\ComponentRegistry
  272. */
  273. public function components($components = null)
  274. {
  275. if ($components === null && $this->_components === null) {
  276. $this->_components = new ComponentRegistry($this);
  277. }
  278. if ($components !== null) {
  279. $components->setController($this);
  280. $this->_components = $components;
  281. }
  282. return $this->_components;
  283. }
  284. /**
  285. * Add a component to the controller's registry.
  286. *
  287. * This method will also set the component to a property.
  288. * For example:
  289. *
  290. * ```
  291. * $this->loadComponent('Acl.Acl');
  292. * ```
  293. *
  294. * Will result in a `Toolbar` property being set.
  295. *
  296. * @param string $name The name of the component to load.
  297. * @param array $config The config for the component.
  298. * @return \Cake\Controller\Component
  299. * @throws \Exception
  300. */
  301. public function loadComponent($name, array $config = [])
  302. {
  303. list(, $prop) = pluginSplit($name);
  304. return $this->{$prop} = $this->components()->load($name, $config);
  305. }
  306. /**
  307. * Magic accessor for model autoloading.
  308. *
  309. * @param string $name Property name
  310. * @return bool|object The model instance or false
  311. */
  312. public function __get($name)
  313. {
  314. $deprecated = [
  315. 'name' => 'getName',
  316. 'plugin' => 'getPlugin',
  317. 'autoRender' => 'isAutoRenderEnabled',
  318. ];
  319. if (isset($deprecated[$name])) {
  320. $method = $deprecated[$name];
  321. deprecationWarning(sprintf('Controller::$%s is deprecated. Use $this->%s() instead.', $name, $method));
  322. return $this->{$method}();
  323. }
  324. $deprecated = [
  325. 'layout' => 'getLayout',
  326. 'view' => 'getTemplate',
  327. 'theme' => 'getTheme',
  328. 'autoLayout' => 'isAutoLayoutEnabled',
  329. 'viewPath' => 'getTemplatePath',
  330. 'layoutPath' => 'getLayoutPath',
  331. ];
  332. if (isset($deprecated[$name])) {
  333. $method = $deprecated[$name];
  334. deprecationWarning(sprintf('Controller::$%s is deprecated. Use $this->viewBuilder()->%s() instead.', $name, $method));
  335. return $this->viewBuilder()->{$method}();
  336. }
  337. list($plugin, $class) = pluginSplit($this->modelClass, true);
  338. if ($class === $name) {
  339. return $this->loadModel($plugin . $class);
  340. }
  341. $trace = debug_backtrace();
  342. $parts = explode('\\', get_class($this));
  343. trigger_error(
  344. sprintf(
  345. 'Undefined property: %s::$%s in %s on line %s',
  346. array_pop($parts),
  347. $name,
  348. $trace[0]['file'],
  349. $trace[0]['line']
  350. ),
  351. E_USER_NOTICE
  352. );
  353. return false;
  354. }
  355. /**
  356. * Magic setter for removed properties.
  357. *
  358. * @param string $name Property name.
  359. * @param mixed $value Value to set.
  360. * @return void
  361. */
  362. public function __set($name, $value)
  363. {
  364. $deprecated = [
  365. 'name' => 'setName',
  366. 'plugin' => 'setPlugin'
  367. ];
  368. if (isset($deprecated[$name])) {
  369. $method = $deprecated[$name];
  370. deprecationWarning(sprintf('Controller::$%s is deprecated. Use $this->%s() instead.', $name, $method));
  371. $this->{$method}($value);
  372. return;
  373. }
  374. if ($name === 'autoRender') {
  375. $value ? $this->enableAutoRender() : $this->disableAutoRender();
  376. deprecationWarning(sprintf('Controller::$%s is deprecated. Use $this->enableAutoRender/disableAutoRender() instead.', $name));
  377. return;
  378. }
  379. $deprecated = [
  380. 'layout' => 'setLayout',
  381. 'view' => 'setTemplate',
  382. 'theme' => 'setTheme',
  383. 'autoLayout' => 'enableAutoLayout',
  384. 'viewPath' => 'setTemplatePath',
  385. 'layoutPath' => 'setLayoutPath',
  386. ];
  387. if (isset($deprecated[$name])) {
  388. $method = $deprecated[$name];
  389. deprecationWarning(sprintf('Controller::$%s is deprecated. Use $this->viewBuilder()->%s() instead.', $name, $method));
  390. $this->viewBuilder()->{$method}($value);
  391. return;
  392. }
  393. $this->{$name} = $value;
  394. }
  395. /**
  396. * Returns the controller name.
  397. *
  398. * @return string
  399. * @since 3.6.0
  400. */
  401. public function getName()
  402. {
  403. return $this->name;
  404. }
  405. /**
  406. * Sets the controller name.
  407. *
  408. * @param string $name Controller name.
  409. * @return $this
  410. * @since 3.6.0
  411. */
  412. public function setName($name)
  413. {
  414. $this->name = $name;
  415. return $this;
  416. }
  417. /**
  418. * Returns the plugin name.
  419. *
  420. * @return string|null
  421. * @since 3.6.0
  422. */
  423. public function getPlugin()
  424. {
  425. return $this->plugin;
  426. }
  427. /**
  428. * Sets the plugin name.
  429. *
  430. * @param string $name Plugin name.
  431. * @return $this
  432. * @since 3.6.0
  433. */
  434. public function setPlugin($name)
  435. {
  436. $this->plugin = $name;
  437. return $this;
  438. }
  439. /**
  440. * Returns true if an action should be rendered automatically.
  441. *
  442. * @return bool
  443. * @since 3.6.0
  444. */
  445. public function isAutoRenderEnabled()
  446. {
  447. return $this->autoRender;
  448. }
  449. /**
  450. * Enable automatic action rendering.
  451. *
  452. * @return $this
  453. * @since 3.6.0
  454. */
  455. public function enableAutoRender()
  456. {
  457. $this->autoRender = true;
  458. return $this;
  459. }
  460. /**
  461. * Disable automatic action rendering.
  462. *
  463. * @return $this
  464. * @since 3.6.0
  465. */
  466. public function disableAutoRender()
  467. {
  468. $this->autoRender = false;
  469. return $this;
  470. }
  471. /**
  472. * Gets the request instance.
  473. *
  474. * @return \Cake\Http\ServerRequest
  475. * @since 3.6.0
  476. */
  477. public function getRequest()
  478. {
  479. return $this->request;
  480. }
  481. /**
  482. * Sets the request objects and configures a number of controller properties
  483. * based on the contents of the request. Controller acts as a proxy for certain View variables
  484. * which must also be updated here. The properties that get set are:
  485. *
  486. * - $this->request - To the $request parameter
  487. * - $this->passedArgs - Same as $request->params['pass]
  488. *
  489. * @param \Cake\Http\ServerRequest $request Request instance.
  490. * @return $this
  491. */
  492. public function setRequest(ServerRequest $request)
  493. {
  494. $this->request = $request;
  495. $this->plugin = $request->getParam('plugin') ?: null;
  496. if ($request->getParam('pass')) {
  497. $this->passedArgs = $request->getParam('pass');
  498. }
  499. return $this;
  500. }
  501. /**
  502. * Gets the response instance.
  503. *
  504. * @return \Cake\Http\Response
  505. * @since 3.6.0
  506. */
  507. public function getResponse()
  508. {
  509. return $this->response;
  510. }
  511. /**
  512. * Sets the response instance.
  513. *
  514. * @param \Cake\Http\Response $response Response instance.
  515. * @return $this
  516. * @since 3.6.0
  517. */
  518. public function setResponse(Response $response)
  519. {
  520. $this->response = $response;
  521. return $this;
  522. }
  523. /**
  524. * Dispatches the controller action. Checks that the action
  525. * exists and isn't private.
  526. *
  527. * @return mixed The resulting response.
  528. * @throws \ReflectionException
  529. */
  530. public function invokeAction()
  531. {
  532. $request = $this->request;
  533. if (!$request) {
  534. throw new LogicException('No Request object configured. Cannot invoke action');
  535. }
  536. if (!$this->isAction($request->getParam('action'))) {
  537. throw new MissingActionException([
  538. 'controller' => $this->name . 'Controller',
  539. 'action' => $request->getParam('action'),
  540. 'prefix' => $request->getParam('prefix') ?: '',
  541. 'plugin' => $request->getParam('plugin'),
  542. ]);
  543. }
  544. /* @var callable $callable */
  545. $callable = [$this, $request->getParam('action')];
  546. $result = $callable(...array_values($request->getParam('pass')));
  547. if ($result instanceof Response) {
  548. $this->response = $result;
  549. }
  550. return $result;
  551. }
  552. /**
  553. * Merge components, helpers vars from
  554. * parent classes.
  555. *
  556. * @return void
  557. */
  558. protected function _mergeControllerVars()
  559. {
  560. $this->_mergeVars(
  561. ['components', 'helpers'],
  562. ['associative' => ['components', 'helpers']]
  563. );
  564. }
  565. /**
  566. * Returns a list of all events that will fire in the controller during its lifecycle.
  567. * You can override this function to add your own listener callbacks
  568. *
  569. * @return array
  570. */
  571. public function implementedEvents()
  572. {
  573. return [
  574. 'Controller.initialize' => 'beforeFilter',
  575. 'Controller.beforeRender' => 'beforeRender',
  576. 'Controller.beforeRedirect' => 'beforeRedirect',
  577. 'Controller.shutdown' => 'afterFilter',
  578. ];
  579. }
  580. /**
  581. * Loads the defined components using the Component factory.
  582. *
  583. * @return void
  584. */
  585. protected function _loadComponents()
  586. {
  587. if (empty($this->components)) {
  588. return;
  589. }
  590. $registry = $this->components();
  591. $components = $registry->normalizeArray($this->components);
  592. foreach ($components as $properties) {
  593. $this->loadComponent($properties['class'], $properties['config']);
  594. }
  595. }
  596. /**
  597. * Perform the startup process for this controller.
  598. * Fire the Components and Controller callbacks in the correct order.
  599. *
  600. * - Initializes components, which fires their `initialize` callback
  601. * - Calls the controller `beforeFilter`.
  602. * - triggers Component `startup` methods.
  603. *
  604. * @return \Cake\Http\Response|null
  605. */
  606. public function startupProcess()
  607. {
  608. $event = $this->dispatchEvent('Controller.initialize');
  609. if ($event->getResult() instanceof Response) {
  610. return $event->getResult();
  611. }
  612. $event = $this->dispatchEvent('Controller.startup');
  613. if ($event->getResult() instanceof Response) {
  614. return $event->getResult();
  615. }
  616. return null;
  617. }
  618. /**
  619. * Perform the various shutdown processes for this controller.
  620. * Fire the Components and Controller callbacks in the correct order.
  621. *
  622. * - triggers the component `shutdown` callback.
  623. * - calls the Controller's `afterFilter` method.
  624. *
  625. * @return \Cake\Http\Response|null
  626. */
  627. public function shutdownProcess()
  628. {
  629. $event = $this->dispatchEvent('Controller.shutdown');
  630. if ($event->getResult() instanceof Response) {
  631. return $event->getResult();
  632. }
  633. return null;
  634. }
  635. /**
  636. * Redirects to given $url, after turning off $this->autoRender.
  637. *
  638. * @param string|array $url A string or array-based URL pointing to another location within the app,
  639. * or an absolute URL
  640. * @param int $status HTTP status code (eg: 301)
  641. * @return \Cake\Http\Response|null
  642. * @link https://book.cakephp.org/3.0/en/controllers.html#Controller::redirect
  643. */
  644. public function redirect($url, $status = 302)
  645. {
  646. $this->autoRender = false;
  647. if ($status) {
  648. $this->response = $this->response->withStatus($status);
  649. }
  650. $event = $this->dispatchEvent('Controller.beforeRedirect', [$url, $this->response]);
  651. if ($event->getResult() instanceof Response) {
  652. return $this->response = $event->getResult();
  653. }
  654. if ($event->isStopped()) {
  655. return null;
  656. }
  657. $response = $this->response;
  658. if (!$response->getHeaderLine('Location')) {
  659. $response = $response->withLocation(Router::url($url, true));
  660. }
  661. return $this->response = $response;
  662. }
  663. /**
  664. * Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect()
  665. *
  666. * Examples:
  667. *
  668. * ```
  669. * setAction('another_action');
  670. * setAction('action_with_parameters', $parameter1);
  671. * ```
  672. *
  673. * @param string $action The new action to be 'redirected' to.
  674. * Any other parameters passed to this method will be passed as parameters to the new action.
  675. * @param array ...$args Arguments passed to the action
  676. * @return mixed Returns the return value of the called action
  677. */
  678. public function setAction($action, ...$args)
  679. {
  680. $this->setRequest($this->request->withParam('action', $action));
  681. return $this->$action(...$args);
  682. }
  683. /**
  684. * Instantiates the correct view class, hands it its data, and uses it to render the view output.
  685. *
  686. * @param string|null $view View to use for rendering
  687. * @param string|null $layout Layout to use
  688. * @return \Cake\Http\Response A response object containing the rendered view.
  689. * @link https://book.cakephp.org/3.0/en/controllers.html#rendering-a-view
  690. */
  691. public function render($view = null, $layout = null)
  692. {
  693. $builder = $this->viewBuilder();
  694. if (!$builder->getTemplatePath()) {
  695. $builder->setTemplatePath($this->_viewPath());
  696. }
  697. if ($this->request->getParam('bare')) {
  698. $builder->disableAutoLayout();
  699. }
  700. $this->autoRender = false;
  701. $event = $this->dispatchEvent('Controller.beforeRender');
  702. if ($event->getResult() instanceof Response) {
  703. return $event->getResult();
  704. }
  705. if ($event->isStopped()) {
  706. return $this->response;
  707. }
  708. if ($builder->getTemplate() === null && $this->request->getParam('action')) {
  709. $builder->setTemplate($this->request->getParam('action'));
  710. }
  711. $this->View = $this->createView();
  712. $contents = $this->View->render($view, $layout);
  713. $this->setResponse($this->View->getResponse()->withStringBody($contents));
  714. return $this->response;
  715. }
  716. /**
  717. * Get the viewPath based on controller name and request prefix.
  718. *
  719. * @return string
  720. */
  721. protected function _viewPath()
  722. {
  723. $viewPath = $this->name;
  724. if ($this->request->getParam('prefix')) {
  725. $prefixes = array_map(
  726. 'Cake\Utility\Inflector::camelize',
  727. explode('/', $this->request->getParam('prefix'))
  728. );
  729. $viewPath = implode(DIRECTORY_SEPARATOR, $prefixes) . DIRECTORY_SEPARATOR . $viewPath;
  730. }
  731. return $viewPath;
  732. }
  733. /**
  734. * Returns the referring URL for this request.
  735. *
  736. * @param string|array|null $default Default URL to use if HTTP_REFERER cannot be read from headers
  737. * @param bool $local If true, restrict referring URLs to local server
  738. * @return string Referring URL
  739. */
  740. public function referer($default = null, $local = false)
  741. {
  742. if (!$this->request) {
  743. return Router::url($default, !$local);
  744. }
  745. $referer = $this->request->referer($local);
  746. if ($referer === '/' && $default && $default !== $referer) {
  747. $url = Router::url($default, !$local);
  748. $base = $this->request->getAttribute('base');
  749. if ($local && $base && strpos($url, $base) === 0) {
  750. $url = substr($url, strlen($base));
  751. if ($url[0] !== '/') {
  752. $url = '/' . $url;
  753. }
  754. return $url;
  755. }
  756. return $url;
  757. }
  758. return $referer;
  759. }
  760. /**
  761. * Handles pagination of records in Table objects.
  762. *
  763. * Will load the referenced Table object, and have the PaginatorComponent
  764. * paginate the query using the request date and settings defined in `$this->paginate`.
  765. *
  766. * This method will also make the PaginatorHelper available in the view.
  767. *
  768. * @param \Cake\ORM\Table|string|\Cake\ORM\Query|null $object Table to paginate
  769. * (e.g: Table instance, 'TableName' or a Query object)
  770. * @param array $settings The settings/configuration used for pagination.
  771. * @return \Cake\ORM\ResultSet|\Cake\Datasource\ResultSetInterface Query results
  772. * @link https://book.cakephp.org/3.0/en/controllers.html#paginating-a-model
  773. * @throws \RuntimeException When no compatible table object can be found.
  774. */
  775. public function paginate($object = null, array $settings = [])
  776. {
  777. if (is_object($object)) {
  778. $table = $object;
  779. }
  780. if (is_string($object) || $object === null) {
  781. $try = [$object, $this->modelClass];
  782. foreach ($try as $tableName) {
  783. if (empty($tableName)) {
  784. continue;
  785. }
  786. $table = $this->loadModel($tableName);
  787. break;
  788. }
  789. }
  790. $this->loadComponent('Paginator');
  791. if (empty($table)) {
  792. throw new RuntimeException('Unable to locate an object compatible with paginate.');
  793. }
  794. $settings += $this->paginate;
  795. return $this->Paginator->paginate($table, $settings);
  796. }
  797. /**
  798. * Method to check that an action is accessible from a URL.
  799. *
  800. * Override this method to change which controller methods can be reached.
  801. * The default implementation disallows access to all methods defined on Cake\Controller\Controller,
  802. * and allows all public methods on all subclasses of this class.
  803. *
  804. * @param string $action The action to check.
  805. * @return bool Whether or not the method is accessible from a URL.
  806. * @throws \ReflectionException
  807. */
  808. public function isAction($action)
  809. {
  810. $baseClass = new ReflectionClass('Cake\Controller\Controller');
  811. if ($baseClass->hasMethod($action)) {
  812. return false;
  813. }
  814. try {
  815. $method = new ReflectionMethod($this, $action);
  816. } catch (ReflectionException $e) {
  817. return false;
  818. }
  819. return $method->isPublic();
  820. }
  821. /**
  822. * Called before the controller action. You can use this method to configure and customize components
  823. * or perform logic that needs to happen before each controller action.
  824. *
  825. * @param \Cake\Event\Event $event An Event instance
  826. * @return \Cake\Http\Response|null
  827. * @link https://book.cakephp.org/3.0/en/controllers.html#request-life-cycle-callbacks
  828. */
  829. public function beforeFilter(Event $event)
  830. {
  831. return null;
  832. }
  833. /**
  834. * Called after the controller action is run, but before the view is rendered. You can use this method
  835. * to perform logic or set view variables that are required on every request.
  836. *
  837. * @param \Cake\Event\Event $event An Event instance
  838. * @return \Cake\Http\Response|null
  839. * @link https://book.cakephp.org/3.0/en/controllers.html#request-life-cycle-callbacks
  840. */
  841. public function beforeRender(Event $event)
  842. {
  843. return null;
  844. }
  845. /**
  846. * The beforeRedirect method is invoked when the controller's redirect method is called but before any
  847. * further action.
  848. *
  849. * If the event is stopped the controller will not continue on to redirect the request.
  850. * The $url and $status variables have same meaning as for the controller's method.
  851. * You can set the event result to response instance or modify the redirect location
  852. * using controller's response instance.
  853. *
  854. * @param \Cake\Event\Event $event An Event instance
  855. * @param string|array $url A string or array-based URL pointing to another location within the app,
  856. * or an absolute URL
  857. * @param \Cake\Http\Response $response The response object.
  858. * @return \Cake\Http\Response|null
  859. * @link https://book.cakephp.org/3.0/en/controllers.html#request-life-cycle-callbacks
  860. */
  861. public function beforeRedirect(Event $event, $url, Response $response)
  862. {
  863. return null;
  864. }
  865. /**
  866. * Called after the controller action is run and rendered.
  867. *
  868. * @param \Cake\Event\Event $event An Event instance
  869. * @return \Cake\Http\Response|null
  870. * @link https://book.cakephp.org/3.0/en/controllers.html#request-life-cycle-callbacks
  871. */
  872. public function afterFilter(Event $event)
  873. {
  874. return null;
  875. }
  876. }