Controller.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. <?php
  2. /**
  3. * @link https://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license https://www.yiiframework.com/license/
  6. */
  7. namespace yii\base;
  8. use Yii;
  9. use yii\di\Instance;
  10. use yii\di\NotInstantiableException;
  11. /**
  12. * Controller is the base class for classes containing controller logic.
  13. *
  14. * For more details and usage information on Controller, see the [guide article on controllers](guide:structure-controllers).
  15. *
  16. * @property-read Module[] $modules All ancestor modules that this controller is located within.
  17. * @property-read string $route The route (module ID, controller ID and action ID) of the current request.
  18. * @property-read string $uniqueId The controller ID that is prefixed with the module ID (if any).
  19. * @property View|\yii\web\View $view The view object that can be used to render views or view files.
  20. * @property string $viewPath The directory containing the view files for this controller.
  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 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|null|false 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|null 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 Request|array|string The request.
  63. * @since 2.0.36
  64. */
  65. public $request = 'request';
  66. /**
  67. * @var Response|array|string The response.
  68. * @since 2.0.36
  69. */
  70. public $response = 'response';
  71. /**
  72. * @var View|null the view object that can be used to render views or view files.
  73. */
  74. private $_view;
  75. /**
  76. * @var string|null the root directory that contains view files for this controller.
  77. */
  78. private $_viewPath;
  79. /**
  80. * @param string $id the ID of this controller.
  81. * @param Module $module the module that this controller belongs to.
  82. * @param array $config name-value pairs that will be used to initialize the object properties.
  83. *
  84. * @phpstan-param array<string, mixed> $config
  85. * @psalm-param array<string, mixed> $config
  86. */
  87. public function __construct($id, $module, $config = [])
  88. {
  89. $this->id = $id;
  90. $this->module = $module;
  91. parent::__construct($config);
  92. }
  93. /**
  94. * {@inheritdoc}
  95. * @since 2.0.36
  96. */
  97. public function init()
  98. {
  99. parent::init();
  100. $this->request = Instance::ensure($this->request, Request::className());
  101. $this->response = Instance::ensure($this->response, Response::className());
  102. }
  103. /**
  104. * Declares external actions for the controller.
  105. *
  106. * This method is meant to be overwritten to declare external actions for the controller.
  107. * It should return an array, with array keys being action IDs, and array values the corresponding
  108. * action class names or action configuration arrays. For example,
  109. *
  110. * ```php
  111. * return [
  112. * 'action1' => 'app\components\Action1',
  113. * 'action2' => [
  114. * 'class' => 'app\components\Action2',
  115. * 'property1' => 'value1',
  116. * 'property2' => 'value2',
  117. * ],
  118. * ];
  119. * ```
  120. *
  121. * [[\Yii::createObject()]] will be used later to create the requested action
  122. * using the configuration provided here.
  123. * @return array
  124. *
  125. * @phpstan-return array<array-key, class-string|array{class: class-string, ...}>
  126. * @psalm-return array<array-key, class-string|array{class: class-string, ...}>
  127. */
  128. public function actions()
  129. {
  130. return [];
  131. }
  132. /**
  133. * Runs an action within this controller with the specified action ID and parameters.
  134. * If the action ID is empty, the method will use [[defaultAction]].
  135. * @param string $id the ID of the action to be executed.
  136. * @param array $params the parameters (name-value pairs) to be passed to the action.
  137. * @return mixed the result of the action.
  138. * @throws InvalidRouteException if the requested action ID cannot be resolved into an action successfully.
  139. * @see createAction()
  140. */
  141. public function runAction($id, $params = [])
  142. {
  143. $action = $this->createAction($id);
  144. if ($action === null) {
  145. throw new InvalidRouteException('Unable to resolve the request: ' . $this->getUniqueId() . '/' . $id);
  146. }
  147. Yii::debug('Route to run: ' . $action->getUniqueId(), __METHOD__);
  148. if (Yii::$app->requestedAction === null) {
  149. Yii::$app->requestedAction = $action;
  150. }
  151. $oldAction = $this->action;
  152. $this->action = $action;
  153. $modules = [];
  154. $runAction = true;
  155. // call beforeAction on modules
  156. foreach ($this->getModules() as $module) {
  157. if ($module->beforeAction($action)) {
  158. array_unshift($modules, $module);
  159. } else {
  160. $runAction = false;
  161. break;
  162. }
  163. }
  164. $result = null;
  165. if ($runAction && $this->beforeAction($action)) {
  166. // run the action
  167. $result = $action->runWithParams($params);
  168. $result = $this->afterAction($action, $result);
  169. // call afterAction on modules
  170. foreach ($modules as $module) {
  171. /** @var Module $module */
  172. $result = $module->afterAction($action, $result);
  173. }
  174. }
  175. if ($oldAction !== null) {
  176. $this->action = $oldAction;
  177. }
  178. return $result;
  179. }
  180. /**
  181. * Runs a request specified in terms of a route.
  182. * The route can be either an ID of an action within this controller or a complete route consisting
  183. * of module IDs, controller ID and action ID. If the route starts with a slash '/', the parsing of
  184. * the route will start from the application; otherwise, it will start from the parent module of this controller.
  185. * @param string $route the route to be handled, e.g., 'view', 'comment/view', '/admin/comment/view'.
  186. * @param array $params the parameters to be passed to the action.
  187. * @return mixed the result of the action.
  188. * @see runAction()
  189. */
  190. public function run($route, $params = [])
  191. {
  192. $pos = strpos($route, '/');
  193. if ($pos === false) {
  194. return $this->runAction($route, $params);
  195. } elseif ($pos > 0) {
  196. return $this->module->runAction($route, $params);
  197. }
  198. return Yii::$app->runAction(ltrim($route, '/'), $params);
  199. }
  200. /**
  201. * Binds the parameters to the action.
  202. * This method is invoked by [[Action]] when it begins to run with the given parameters.
  203. * @param Action $action the action to be bound with parameters.
  204. * @param array $params the parameters to be bound to the action.
  205. * @return array the valid parameters that the action can run with.
  206. */
  207. public function bindActionParams($action, $params)
  208. {
  209. return [];
  210. }
  211. /**
  212. * Creates an action based on the given action ID.
  213. * The method first checks if the action ID has been declared in [[actions()]]. If so,
  214. * it will use the configuration declared there to create the action object.
  215. * If not, it will look for a controller method whose name is in the format of `actionXyz`
  216. * where `xyz` is the action ID. If found, an [[InlineAction]] representing that
  217. * method will be created and returned.
  218. * @param string $id the action ID.
  219. * @return Action|null the newly created action instance. Null if the ID doesn't resolve into any action.
  220. */
  221. public function createAction($id)
  222. {
  223. if ($id === '') {
  224. $id = $this->defaultAction;
  225. }
  226. $actionMap = $this->actions();
  227. if (isset($actionMap[$id])) {
  228. return Yii::createObject($actionMap[$id], [$id, $this]);
  229. }
  230. if (preg_match('/^(?:[a-z0-9_]+-)*[a-z0-9_]+$/', $id)) {
  231. $methodName = 'action' . str_replace(' ', '', ucwords(str_replace('-', ' ', $id)));
  232. if (method_exists($this, $methodName)) {
  233. $method = new \ReflectionMethod($this, $methodName);
  234. if ($method->isPublic() && $method->getName() === $methodName) {
  235. return new InlineAction($id, $this, $methodName);
  236. }
  237. }
  238. }
  239. return null;
  240. }
  241. /**
  242. * This method is invoked right before an action is executed.
  243. *
  244. * The method will trigger the [[EVENT_BEFORE_ACTION]] event. The return value of the method
  245. * will determine whether the action should continue to run.
  246. *
  247. * In case the action should not run, the request should be handled inside of the `beforeAction` code
  248. * by either providing the necessary output or redirecting the request. Otherwise the response will be empty.
  249. *
  250. * If you override this method, your code should look like the following:
  251. *
  252. * ```php
  253. * public function beforeAction($action)
  254. * {
  255. * // your custom code here, if you want the code to run before action filters,
  256. * // which are triggered on the [[EVENT_BEFORE_ACTION]] event, e.g. PageCache or AccessControl
  257. *
  258. * if (!parent::beforeAction($action)) {
  259. * return false;
  260. * }
  261. *
  262. * // other custom code here
  263. *
  264. * return true; // or false to not run the action
  265. * }
  266. * ```
  267. *
  268. * @param Action $action the action to be executed.
  269. * @return bool whether the action should continue to run.
  270. */
  271. public function beforeAction($action)
  272. {
  273. $event = new ActionEvent($action);
  274. $this->trigger(self::EVENT_BEFORE_ACTION, $event);
  275. return $event->isValid;
  276. }
  277. /**
  278. * This method is invoked right after an action is executed.
  279. *
  280. * The method will trigger the [[EVENT_AFTER_ACTION]] event. The return value of the method
  281. * will be used as the action return value.
  282. *
  283. * If you override this method, your code should look like the following:
  284. *
  285. * ```php
  286. * public function afterAction($action, $result)
  287. * {
  288. * $result = parent::afterAction($action, $result);
  289. * // your custom code here
  290. * return $result;
  291. * }
  292. * ```
  293. *
  294. * @param Action $action the action just executed.
  295. * @param mixed $result the action return result.
  296. * @return mixed the processed action result.
  297. */
  298. public function afterAction($action, $result)
  299. {
  300. $event = new ActionEvent($action);
  301. $event->result = $result;
  302. $this->trigger(self::EVENT_AFTER_ACTION, $event);
  303. return $event->result;
  304. }
  305. /**
  306. * Returns all ancestor modules of this controller.
  307. * The first module in the array is the outermost one (i.e., the application instance),
  308. * while the last is the innermost one.
  309. * @return Module[] all ancestor modules that this controller is located within.
  310. */
  311. public function getModules()
  312. {
  313. $modules = [$this->module];
  314. $module = $this->module;
  315. while ($module->module !== null) {
  316. array_unshift($modules, $module->module);
  317. $module = $module->module;
  318. }
  319. return $modules;
  320. }
  321. /**
  322. * Returns the unique ID of the controller.
  323. * @return string the controller ID that is prefixed with the module ID (if any).
  324. */
  325. public function getUniqueId()
  326. {
  327. return $this->module instanceof Application ? $this->id : $this->module->getUniqueId() . '/' . $this->id;
  328. }
  329. /**
  330. * Returns the route of the current request.
  331. * @return string the route (module ID, controller ID and action ID) of the current request.
  332. */
  333. public function getRoute()
  334. {
  335. return $this->action !== null ? $this->action->getUniqueId() : $this->getUniqueId();
  336. }
  337. /**
  338. * Renders a view and applies layout if available.
  339. *
  340. * The view to be rendered can be specified in one of the following formats:
  341. *
  342. * - [path alias](guide:concept-aliases) (e.g. "@app/views/site/index");
  343. * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes.
  344. * The actual view file will be looked for under the [[Application::viewPath|view path]] of the application.
  345. * - absolute path within module (e.g. "/site/index"): the view name starts with a single slash.
  346. * The actual view file will be looked for under the [[Module::viewPath|view path]] of [[module]].
  347. * - relative path (e.g. "index"): the actual view file will be looked for under [[viewPath]].
  348. *
  349. * To determine which layout should be applied, the following two steps are conducted:
  350. *
  351. * 1. In the first step, it determines the layout name and the context module:
  352. *
  353. * - If [[layout]] is specified as a string, use it as the layout name and [[module]] as the context module;
  354. * - If [[layout]] is null, search through all ancestor modules of this controller and find the first
  355. * module whose [[Module::layout|layout]] is not null. The layout and the corresponding module
  356. * are used as the layout name and the context module, respectively. If such a module is not found
  357. * or the corresponding layout is not a string, it will return false, meaning no applicable layout.
  358. *
  359. * 2. In the second step, it determines the actual layout file according to the previously found layout name
  360. * and context module. The layout name can be:
  361. *
  362. * - a [path alias](guide:concept-aliases) (e.g. "@app/views/layouts/main");
  363. * - an absolute path (e.g. "/main"): the layout name starts with a slash. The actual layout file will be
  364. * looked for under the [[Application::layoutPath|layout path]] of the application;
  365. * - a relative path (e.g. "main"): the actual layout file will be looked for under the
  366. * [[Module::layoutPath|layout path]] of the context module.
  367. *
  368. * If the layout name does not contain a file extension, it will use the default one `.php`.
  369. *
  370. * @param string $view the view name.
  371. * @param array $params the parameters (name-value pairs) that should be made available in the view.
  372. * These parameters will not be available in the layout.
  373. * @return string the rendering result.
  374. * @throws InvalidArgumentException if the view file or the layout file does not exist.
  375. */
  376. public function render($view, $params = [])
  377. {
  378. $content = $this->getView()->render($view, $params, $this);
  379. return $this->renderContent($content);
  380. }
  381. /**
  382. * Renders a static string by applying a layout.
  383. * @param string $content the static string being rendered
  384. * @return string the rendering result of the layout with the given static string as the `$content` variable.
  385. * If the layout is disabled, the string will be returned back.
  386. * @since 2.0.1
  387. */
  388. public function renderContent($content)
  389. {
  390. $layoutFile = $this->findLayoutFile($this->getView());
  391. if ($layoutFile !== false) {
  392. return $this->getView()->renderFile($layoutFile, ['content' => $content], $this);
  393. }
  394. return $content;
  395. }
  396. /**
  397. * Renders a view without applying layout.
  398. * This method differs from [[render()]] in that it does not apply any layout.
  399. * @param string $view the view name. Please refer to [[render()]] on how to specify a view name.
  400. * @param array $params the parameters (name-value pairs) that should be made available in the view.
  401. * @return string the rendering result.
  402. * @throws InvalidArgumentException if the view file does not exist.
  403. */
  404. public function renderPartial($view, $params = [])
  405. {
  406. return $this->getView()->render($view, $params, $this);
  407. }
  408. /**
  409. * Renders a view file.
  410. * @param string $file the view file to be rendered. This can be either a file path or a [path alias](guide:concept-aliases).
  411. * @param array $params the parameters (name-value pairs) that should be made available in the view.
  412. * @return string the rendering result.
  413. * @throws InvalidArgumentException if the view file does not exist.
  414. */
  415. public function renderFile($file, $params = [])
  416. {
  417. return $this->getView()->renderFile($file, $params, $this);
  418. }
  419. /**
  420. * Returns the view object that can be used to render views or view files.
  421. * The [[render()]], [[renderPartial()]] and [[renderFile()]] methods will use
  422. * this view object to implement the actual view rendering.
  423. * If not set, it will default to the "view" application component.
  424. * @return View|\yii\web\View the view object that can be used to render views or view files.
  425. */
  426. public function getView()
  427. {
  428. if ($this->_view === null) {
  429. $this->_view = Yii::$app->getView();
  430. }
  431. return $this->_view;
  432. }
  433. /**
  434. * Sets the view object to be used by this controller.
  435. * @param View|\yii\web\View $view the view object that can be used to render views or view files.
  436. */
  437. public function setView($view)
  438. {
  439. $this->_view = $view;
  440. }
  441. /**
  442. * Returns the directory containing view files for this controller.
  443. * The default implementation returns the directory named as controller [[id]] under the [[module]]'s
  444. * [[viewPath]] directory.
  445. * @return string the directory containing the view files for this controller.
  446. */
  447. public function getViewPath()
  448. {
  449. if ($this->_viewPath === null) {
  450. $this->_viewPath = $this->module->getViewPath() . DIRECTORY_SEPARATOR . $this->id;
  451. }
  452. return $this->_viewPath;
  453. }
  454. /**
  455. * Sets the directory that contains the view files.
  456. * @param string $path the root directory of view files.
  457. * @throws InvalidArgumentException if the directory is invalid
  458. * @since 2.0.7
  459. */
  460. public function setViewPath($path)
  461. {
  462. $this->_viewPath = Yii::getAlias($path);
  463. }
  464. /**
  465. * Finds the applicable layout file.
  466. * @param View $view the view object to render the layout file.
  467. * @return string|bool the layout file path, or false if layout is not needed.
  468. * Please refer to [[render()]] on how to specify this parameter.
  469. * @throws InvalidArgumentException if an invalid path alias is used to specify the layout.
  470. */
  471. public function findLayoutFile($view)
  472. {
  473. $module = $this->module;
  474. $layout = null;
  475. if (is_string($this->layout)) {
  476. $layout = $this->layout;
  477. } elseif ($this->layout === null) {
  478. while ($module !== null && $module->layout === null) {
  479. $module = $module->module;
  480. }
  481. if ($module !== null && is_string($module->layout)) {
  482. $layout = $module->layout;
  483. }
  484. }
  485. if ($layout === null) {
  486. return false;
  487. }
  488. if (strncmp($layout, '@', 1) === 0) {
  489. $file = Yii::getAlias($layout);
  490. } elseif (strncmp($layout, '/', 1) === 0) {
  491. $file = Yii::$app->getLayoutPath() . DIRECTORY_SEPARATOR . substr($layout, 1);
  492. } else {
  493. $file = $module->getLayoutPath() . DIRECTORY_SEPARATOR . $layout;
  494. }
  495. if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
  496. return $file;
  497. }
  498. $path = $file . '.' . $view->defaultExtension;
  499. if ($view->defaultExtension !== 'php' && !is_file($path)) {
  500. $path = $file . '.php';
  501. }
  502. return $path;
  503. }
  504. /**
  505. * Fills parameters based on types and names in action method signature.
  506. * @param \ReflectionNamedType $type The reflected type of the action parameter.
  507. * @param string $name The name of the parameter.
  508. * @param array &$args The array of arguments for the action, this function may append items to it.
  509. * @param array &$requestedParams The array with requested params, this function may write specific keys to it.
  510. * @throws ErrorException when we cannot load a required service.
  511. * @throws InvalidConfigException Thrown when there is an error in the DI configuration.
  512. * @throws NotInstantiableException Thrown when a definition cannot be resolved to a concrete class
  513. * (for example an interface type hint) without a proper definition in the container.
  514. * @since 2.0.36
  515. */
  516. final protected function bindInjectedParams(\ReflectionNamedType $type, $name, &$args, &$requestedParams)
  517. {
  518. // Since it is not a builtin type it must be DI injection.
  519. $typeName = $type->getName();
  520. if (($component = $this->module->get($name, false)) instanceof $typeName) {
  521. $args[] = $component;
  522. $requestedParams[$name] = 'Component: ' . get_class($component) . " \$$name";
  523. } elseif ($this->module->has($typeName) && ($service = $this->module->get($typeName)) instanceof $typeName) {
  524. $args[] = $service;
  525. $requestedParams[$name] = 'Module ' . get_class($this->module) . " DI: $typeName \$$name";
  526. } elseif (\Yii::$container->has($typeName) && ($service = \Yii::$container->get($typeName)) instanceof $typeName) {
  527. $args[] = $service;
  528. $requestedParams[$name] = "Container DI: $typeName \$$name";
  529. } elseif ($type->allowsNull()) {
  530. $args[] = null;
  531. $requestedParams[$name] = "Unavailable service: $name";
  532. } else {
  533. throw new Exception('Could not load required service: ' . $name);
  534. }
  535. }
  536. }