You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

492 lines
18KB

  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\base;
  8. use Yii;
  9. /**
  10. * Controller is the base class for classes containing controller logic.
  11. *
  12. * @property Module[] $modules All ancestor modules that this controller is located within. This property is
  13. * read-only.
  14. * @property string $route The route (module ID, controller ID and action ID) of the current request. This
  15. * property is read-only.
  16. * @property string $uniqueId The controller ID that is prefixed with the module ID (if any). This property is
  17. * read-only.
  18. * @property View|\yii\web\View $view The view object that can be used to render views or view files.
  19. * @property string $viewPath The directory containing the view files for this controller. This property is
  20. * read-only.
  21. *
  22. * @author Qiang Xue <qiang.xue@gmail.com>
  23. * @since 2.0
  24. */
  25. class Controller extends Component implements ViewContextInterface
  26. {
  27. /**
  28. * @event ActionEvent an event raised right before executing a controller action.
  29. * You may set [[ActionEvent::isValid]] to be false to cancel the action execution.
  30. */
  31. const EVENT_BEFORE_ACTION = 'beforeAction';
  32. /**
  33. * @event ActionEvent an event raised right after executing a controller action.
  34. */
  35. const EVENT_AFTER_ACTION = 'afterAction';
  36. /**
  37. * @var string the ID of this controller.
  38. */
  39. public $id;
  40. /**
  41. * @var Module $module the module that this controller belongs to.
  42. */
  43. public $module;
  44. /**
  45. * @var string the ID of the action that is used when the action ID is not specified
  46. * in the request. Defaults to 'index'.
  47. */
  48. public $defaultAction = 'index';
  49. /**
  50. * @var string|boolean the name of the layout to be applied to this controller's views.
  51. * This property mainly affects the behavior of [[render()]].
  52. * Defaults to null, meaning the actual layout value should inherit that from [[module]]'s layout value.
  53. * If false, no layout will be applied.
  54. */
  55. public $layout;
  56. /**
  57. * @var Action the action that is currently being executed. This property will be set
  58. * by [[run()]] when it is called by [[Application]] to run an action.
  59. */
  60. public $action;
  61. /**
  62. * @var View the view object that can be used to render views or view files.
  63. */
  64. private $_view;
  65. /**
  66. * @param string $id the ID of this controller.
  67. * @param Module $module the module that this controller belongs to.
  68. * @param array $config name-value pairs that will be used to initialize the object properties.
  69. */
  70. public function __construct($id, $module, $config = [])
  71. {
  72. $this->id = $id;
  73. $this->module = $module;
  74. parent::__construct($config);
  75. }
  76. /**
  77. * Declares external actions for the controller.
  78. * This method is meant to be overwritten to declare external actions for the controller.
  79. * It should return an array, with array keys being action IDs, and array values the corresponding
  80. * action class names or action configuration arrays. For example,
  81. *
  82. * ~~~
  83. * return [
  84. * 'action1' => 'app\components\Action1',
  85. * 'action2' => [
  86. * 'class' => 'app\components\Action2',
  87. * 'property1' => 'value1',
  88. * 'property2' => 'value2',
  89. * ],
  90. * ];
  91. * ~~~
  92. *
  93. * [[\Yii::createObject()]] will be used later to create the requested action
  94. * using the configuration provided here.
  95. */
  96. public function actions()
  97. {
  98. return [];
  99. }
  100. /**
  101. * Runs an action within this controller with the specified action ID and parameters.
  102. * If the action ID is empty, the method will use [[defaultAction]].
  103. * @param string $id the ID of the action to be executed.
  104. * @param array $params the parameters (name-value pairs) to be passed to the action.
  105. * @return mixed the result of the action.
  106. * @throws InvalidRouteException if the requested action ID cannot be resolved into an action successfully.
  107. * @see createAction()
  108. */
  109. public function runAction($id, $params = [])
  110. {
  111. $action = $this->createAction($id);
  112. if ($action === null) {
  113. throw new InvalidRouteException('Unable to resolve the request: ' . $this->getUniqueId() . '/' . $id);
  114. }
  115. Yii::trace("Route to run: " . $action->getUniqueId(), __METHOD__);
  116. if (Yii::$app->requestedAction === null) {
  117. Yii::$app->requestedAction = $action;
  118. }
  119. $oldAction = $this->action;
  120. $this->action = $action;
  121. $modules = [];
  122. $runAction = true;
  123. // call beforeAction on modules
  124. foreach ($this->getModules() as $module) {
  125. if ($module->beforeAction($action)) {
  126. array_unshift($modules, $module);
  127. } else {
  128. $runAction = false;
  129. break;
  130. }
  131. }
  132. $result = null;
  133. if ($runAction && $this->beforeAction($action)) {
  134. // run the action
  135. $result = $action->runWithParams($params);
  136. $result = $this->afterAction($action, $result);
  137. // call afterAction on modules
  138. foreach ($modules as $module) {
  139. /* @var $module Module */
  140. $result = $module->afterAction($action, $result);
  141. }
  142. }
  143. $this->action = $oldAction;
  144. return $result;
  145. }
  146. /**
  147. * Runs a request specified in terms of a route.
  148. * The route can be either an ID of an action within this controller or a complete route consisting
  149. * of module IDs, controller ID and action ID. If the route starts with a slash '/', the parsing of
  150. * the route will start from the application; otherwise, it will start from the parent module of this controller.
  151. * @param string $route the route to be handled, e.g., 'view', 'comment/view', '/admin/comment/view'.
  152. * @param array $params the parameters to be passed to the action.
  153. * @return mixed the result of the action.
  154. * @see runAction()
  155. */
  156. public function run($route, $params = [])
  157. {
  158. $pos = strpos($route, '/');
  159. if ($pos === false) {
  160. return $this->runAction($route, $params);
  161. } elseif ($pos > 0) {
  162. return $this->module->runAction($route, $params);
  163. } else {
  164. return Yii::$app->runAction(ltrim($route, '/'), $params);
  165. }
  166. }
  167. /**
  168. * Binds the parameters to the action.
  169. * This method is invoked by [[Action]] when it begins to run with the given parameters.
  170. * @param Action $action the action to be bound with parameters.
  171. * @param array $params the parameters to be bound to the action.
  172. * @return array the valid parameters that the action can run with.
  173. */
  174. public function bindActionParams($action, $params)
  175. {
  176. return [];
  177. }
  178. /**
  179. * Creates an action based on the given action ID.
  180. * The method first checks if the action ID has been declared in [[actions()]]. If so,
  181. * it will use the configuration declared there to create the action object.
  182. * If not, it will look for a controller method whose name is in the format of `actionXyz`
  183. * where `Xyz` stands for the action ID. If found, an [[InlineAction]] representing that
  184. * method will be created and returned.
  185. * @param string $id the action ID.
  186. * @return Action the newly created action instance. Null if the ID doesn't resolve into any action.
  187. */
  188. public function createAction($id)
  189. {
  190. if ($id === '') {
  191. $id = $this->defaultAction;
  192. }
  193. $actionMap = $this->actions();
  194. if (isset($actionMap[$id])) {
  195. return Yii::createObject($actionMap[$id], [$id, $this]);
  196. } elseif (preg_match('/^[a-z0-9\\-_]+$/', $id) && strpos($id, '--') === false && trim($id, '-') === $id) {
  197. $methodName = 'action' . str_replace(' ', '', ucwords(implode(' ', explode('-', $id))));
  198. if (method_exists($this, $methodName)) {
  199. $method = new \ReflectionMethod($this, $methodName);
  200. if ($method->isPublic() && $method->getName() === $methodName) {
  201. return new InlineAction($id, $this, $methodName);
  202. }
  203. }
  204. }
  205. return null;
  206. }
  207. /**
  208. * This method is invoked right before an action is executed.
  209. *
  210. * The method will trigger the [[EVENT_BEFORE_ACTION]] event. The return value of the method
  211. * will determine whether the action should continue to run.
  212. *
  213. * If you override this method, your code should look like the following:
  214. *
  215. * ```php
  216. * public function beforeAction($action)
  217. * {
  218. * if (parent::beforeAction($action)) {
  219. * // your custom code here
  220. * return true; // or false if needed
  221. * } else {
  222. * return false;
  223. * }
  224. * }
  225. * ```
  226. *
  227. * @param Action $action the action to be executed.
  228. * @return boolean whether the action should continue to run.
  229. */
  230. public function beforeAction($action)
  231. {
  232. $event = new ActionEvent($action);
  233. $this->trigger(self::EVENT_BEFORE_ACTION, $event);
  234. return $event->isValid;
  235. }
  236. /**
  237. * This method is invoked right after an action is executed.
  238. *
  239. * The method will trigger the [[EVENT_AFTER_ACTION]] event. The return value of the method
  240. * will be used as the action return value.
  241. *
  242. * If you override this method, your code should look like the following:
  243. *
  244. * ```php
  245. * public function afterAction($action, $result)
  246. * {
  247. * $result = parent::afterAction($action, $result);
  248. * // your custom code here
  249. * return $result;
  250. * }
  251. * ```
  252. *
  253. * @param Action $action the action just executed.
  254. * @param mixed $result the action return result.
  255. * @return mixed the processed action result.
  256. */
  257. public function afterAction($action, $result)
  258. {
  259. $event = new ActionEvent($action);
  260. $event->result = $result;
  261. $this->trigger(self::EVENT_AFTER_ACTION, $event);
  262. return $event->result;
  263. }
  264. /**
  265. * Returns all ancestor modules of this controller.
  266. * The first module in the array is the outermost one (i.e., the application instance),
  267. * while the last is the innermost one.
  268. * @return Module[] all ancestor modules that this controller is located within.
  269. */
  270. public function getModules()
  271. {
  272. $modules = [$this->module];
  273. $module = $this->module;
  274. while ($module->module !== null) {
  275. array_unshift($modules, $module->module);
  276. $module = $module->module;
  277. }
  278. return $modules;
  279. }
  280. /**
  281. * @return string the controller ID that is prefixed with the module ID (if any).
  282. */
  283. public function getUniqueId()
  284. {
  285. return $this->module instanceof Application ? $this->id : $this->module->getUniqueId() . '/' . $this->id;
  286. }
  287. /**
  288. * Returns the route of the current request.
  289. * @return string the route (module ID, controller ID and action ID) of the current request.
  290. */
  291. public function getRoute()
  292. {
  293. return $this->action !== null ? $this->action->getUniqueId() : $this->getUniqueId();
  294. }
  295. /**
  296. * Renders a view and applies layout if available.
  297. *
  298. * The view to be rendered can be specified in one of the following formats:
  299. *
  300. * - path alias (e.g. "@app/views/site/index");
  301. * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes.
  302. * The actual view file will be looked for under the [[Application::viewPath|view path]] of the application.
  303. * - absolute path within module (e.g. "/site/index"): the view name starts with a single slash.
  304. * The actual view file will be looked for under the [[Module::viewPath|view path]] of [[module]].
  305. * - relative path (e.g. "index"): the actual view file will be looked for under [[viewPath]].
  306. *
  307. * To determine which layout should be applied, the following two steps are conducted:
  308. *
  309. * 1. In the first step, it determines the layout name and the context module:
  310. *
  311. * - If [[layout]] is specified as a string, use it as the layout name and [[module]] as the context module;
  312. * - If [[layout]] is null, search through all ancestor modules of this controller and find the first
  313. * module whose [[Module::layout|layout]] is not null. The layout and the corresponding module
  314. * are used as the layout name and the context module, respectively. If such a module is not found
  315. * or the corresponding layout is not a string, it will return false, meaning no applicable layout.
  316. *
  317. * 2. In the second step, it determines the actual layout file according to the previously found layout name
  318. * and context module. The layout name can be:
  319. *
  320. * - a path alias (e.g. "@app/views/layouts/main");
  321. * - an absolute path (e.g. "/main"): the layout name starts with a slash. The actual layout file will be
  322. * looked for under the [[Application::layoutPath|layout path]] of the application;
  323. * - a relative path (e.g. "main"): the actual layout file will be looked for under the
  324. * [[Module::layoutPath|layout path]] of the context module.
  325. *
  326. * If the layout name does not contain a file extension, it will use the default one `.php`.
  327. *
  328. * @param string $view the view name.
  329. * @param array $params the parameters (name-value pairs) that should be made available in the view.
  330. * These parameters will not be available in the layout.
  331. * @return string the rendering result.
  332. * @throws InvalidParamException if the view file or the layout file does not exist.
  333. */
  334. public function render($view, $params = [])
  335. {
  336. $content = $this->getView()->render($view, $params, $this);
  337. return $this->renderContent($content);
  338. }
  339. /**
  340. * Renders a static string by applying a layout.
  341. * @param string $content the static string being rendered
  342. * @return string the rendering result of the layout with the given static string as the `$content` variable.
  343. * If the layout is disabled, the string will be returned back.
  344. * @since 2.0.1
  345. */
  346. public function renderContent($content)
  347. {
  348. $layoutFile = $this->findLayoutFile($this->getView());
  349. if ($layoutFile !== false) {
  350. return $this->getView()->renderFile($layoutFile, ['content' => $content], $this);
  351. } else {
  352. return $content;
  353. }
  354. }
  355. /**
  356. * Renders a view without applying layout.
  357. * This method differs from [[render()]] in that it does not apply any layout.
  358. * @param string $view the view name. Please refer to [[render()]] on how to specify a view name.
  359. * @param array $params the parameters (name-value pairs) that should be made available in the view.
  360. * @return string the rendering result.
  361. * @throws InvalidParamException if the view file does not exist.
  362. */
  363. public function renderPartial($view, $params = [])
  364. {
  365. return $this->getView()->render($view, $params, $this);
  366. }
  367. /**
  368. * Renders a view file.
  369. * @param string $file the view file to be rendered. This can be either a file path or a path alias.
  370. * @param array $params the parameters (name-value pairs) that should be made available in the view.
  371. * @return string the rendering result.
  372. * @throws InvalidParamException if the view file does not exist.
  373. */
  374. public function renderFile($file, $params = [])
  375. {
  376. return $this->getView()->renderFile($file, $params, $this);
  377. }
  378. /**
  379. * Returns the view object that can be used to render views or view files.
  380. * The [[render()]], [[renderPartial()]] and [[renderFile()]] methods will use
  381. * this view object to implement the actual view rendering.
  382. * If not set, it will default to the "view" application component.
  383. * @return View|\yii\web\View the view object that can be used to render views or view files.
  384. */
  385. public function getView()
  386. {
  387. if ($this->_view === null) {
  388. $this->_view = Yii::$app->getView();
  389. }
  390. return $this->_view;
  391. }
  392. /**
  393. * Sets the view object to be used by this controller.
  394. * @param View|\yii\web\View $view the view object that can be used to render views or view files.
  395. */
  396. public function setView($view)
  397. {
  398. $this->_view = $view;
  399. }
  400. /**
  401. * Returns the directory containing view files for this controller.
  402. * The default implementation returns the directory named as controller [[id]] under the [[module]]'s
  403. * [[viewPath]] directory.
  404. * @return string the directory containing the view files for this controller.
  405. */
  406. public function getViewPath()
  407. {
  408. return $this->module->getViewPath() . DIRECTORY_SEPARATOR . $this->id;
  409. }
  410. /**
  411. * Finds the applicable layout file.
  412. * @param View $view the view object to render the layout file.
  413. * @return string|boolean the layout file path, or false if layout is not needed.
  414. * Please refer to [[render()]] on how to specify this parameter.
  415. * @throws InvalidParamException if an invalid path alias is used to specify the layout.
  416. */
  417. public function findLayoutFile($view)
  418. {
  419. $module = $this->module;
  420. if (is_string($this->layout)) {
  421. $layout = $this->layout;
  422. } elseif ($this->layout === null) {
  423. while ($module !== null && $module->layout === null) {
  424. $module = $module->module;
  425. }
  426. if ($module !== null && is_string($module->layout)) {
  427. $layout = $module->layout;
  428. }
  429. }
  430. if (!isset($layout)) {
  431. return false;
  432. }
  433. if (strncmp($layout, '@', 1) === 0) {
  434. $file = Yii::getAlias($layout);
  435. } elseif (strncmp($layout, '/', 1) === 0) {
  436. $file = Yii::$app->getLayoutPath() . DIRECTORY_SEPARATOR . substr($layout, 1);
  437. } else {
  438. $file = $module->getLayoutPath() . DIRECTORY_SEPARATOR . $layout;
  439. }
  440. if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
  441. return $file;
  442. }
  443. $path = $file . '.' . $view->defaultExtension;
  444. if ($view->defaultExtension !== 'php' && !is_file($path)) {
  445. $path = $file . '.php';
  446. }
  447. return $path;
  448. }
  449. }