Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

517 lines
19KB

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