Module.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  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\ServiceLocator;
  10. /**
  11. * Module is the base class for module and application classes.
  12. *
  13. * A module represents a sub-application which contains MVC elements by itself, such as
  14. * models, views, controllers, etc.
  15. *
  16. * A module may consist of [[modules|sub-modules]].
  17. *
  18. * [[components|Components]] may be registered with the module so that they are globally
  19. * accessible within the module.
  20. *
  21. * For more details and usage information on Module, see the [guide article on modules](guide:structure-modules).
  22. *
  23. * @property-write array $aliases List of path aliases to be defined. The array keys are alias names (must
  24. * start with `@`) and the array values are the corresponding paths or aliases. See [[setAliases()]] for an
  25. * example.
  26. * @property string $basePath The root directory of the module.
  27. * @property string $controllerPath The directory that contains the controller classes.
  28. * @property string $layoutPath The root directory of layout files. Defaults to "[[viewPath]]/layouts".
  29. * @property array $modules The modules (indexed by their IDs).
  30. * @property-read string $uniqueId The unique ID of the module.
  31. * @property string $version The version of this module. Note that the type of this property differs in getter
  32. * and setter. See [[getVersion()]] and [[setVersion()]] for details.
  33. * @property string $viewPath The root directory of view files. Defaults to "[[basePath]]/views".
  34. *
  35. * @author Qiang Xue <qiang.xue@gmail.com>
  36. * @since 2.0
  37. */
  38. class Module extends ServiceLocator
  39. {
  40. /**
  41. * @event ActionEvent an event raised before executing a controller action.
  42. * You may set [[ActionEvent::isValid]] to be `false` to cancel the action execution.
  43. */
  44. const EVENT_BEFORE_ACTION = 'beforeAction';
  45. /**
  46. * @event ActionEvent an event raised after executing a controller action.
  47. */
  48. const EVENT_AFTER_ACTION = 'afterAction';
  49. /**
  50. * @var array custom module parameters (name => value).
  51. */
  52. public $params = [];
  53. /**
  54. * @var string an ID that uniquely identifies this module among other modules which have the same [[module|parent]].
  55. */
  56. public $id;
  57. /**
  58. * @var Module|null the parent module of this module. `null` if this module does not have a parent.
  59. */
  60. public $module;
  61. /**
  62. * @var string|bool|null the layout that should be applied for views within this module. This refers to a view name
  63. * relative to [[layoutPath]]. If this is not set, it means the layout value of the [[module|parent module]]
  64. * will be taken. If this is `false`, layout will be disabled within this module.
  65. */
  66. public $layout;
  67. /**
  68. * @var array mapping from controller ID to controller configurations.
  69. * Each name-value pair specifies the configuration of a single controller.
  70. * A controller configuration can be either a string or an array.
  71. * If the former, the string should be the fully qualified class name of the controller.
  72. * If the latter, the array must contain a `class` element which specifies
  73. * the controller's fully qualified class name, and the rest of the name-value pairs
  74. * in the array are used to initialize the corresponding controller properties. For example,
  75. *
  76. * ```php
  77. * [
  78. * 'account' => 'app\controllers\UserController',
  79. * 'article' => [
  80. * 'class' => 'app\controllers\PostController',
  81. * 'pageTitle' => 'something new',
  82. * ],
  83. * ]
  84. * ```
  85. */
  86. public $controllerMap = [];
  87. /**
  88. * @var string|null the namespace that controller classes are in.
  89. * This namespace will be used to load controller classes by prepending it to the controller
  90. * class name.
  91. *
  92. * If not set, it will use the `controllers` sub-namespace under the namespace of this module.
  93. * For example, if the namespace of this module is `foo\bar`, then the default
  94. * controller namespace would be `foo\bar\controllers`.
  95. *
  96. * See also the [guide section on autoloading](guide:concept-autoloading) to learn more about
  97. * defining namespaces and how classes are loaded.
  98. */
  99. public $controllerNamespace;
  100. /**
  101. * @var string the default route of this module. Defaults to `default`.
  102. * The route may consist of child module ID, controller ID, and/or action ID.
  103. * For example, `help`, `post/create`, `admin/post/create`.
  104. * If action ID is not given, it will take the default value as specified in
  105. * [[Controller::defaultAction]].
  106. */
  107. public $defaultRoute = 'default';
  108. /**
  109. * @var string the root directory of the module.
  110. */
  111. private $_basePath;
  112. /**
  113. * @var string The root directory that contains the controller classes for this module.
  114. */
  115. private $_controllerPath;
  116. /**
  117. * @var string the root directory that contains view files for this module
  118. */
  119. private $_viewPath;
  120. /**
  121. * @var string the root directory that contains layout view files for this module.
  122. */
  123. private $_layoutPath;
  124. /**
  125. * @var array child modules of this module
  126. */
  127. private $_modules = [];
  128. /**
  129. * @var string|callable|null the version of this module.
  130. * Version can be specified as a PHP callback, which can accept module instance as an argument and should
  131. * return the actual version. For example:
  132. *
  133. * ```php
  134. * function (Module $module) {
  135. * //return string|int
  136. * }
  137. * ```
  138. *
  139. * If not set, [[defaultVersion()]] will be used to determine actual value.
  140. *
  141. * @since 2.0.11
  142. */
  143. private $_version;
  144. /**
  145. * Constructor.
  146. * @param string $id the ID of this module.
  147. * @param Module|null $parent the parent module (if any).
  148. * @param array $config name-value pairs that will be used to initialize the object properties.
  149. *
  150. * @phpstan-param array<string, mixed> $config
  151. * @psalm-param array<string, mixed> $config
  152. */
  153. public function __construct($id, $parent = null, $config = [])
  154. {
  155. $this->id = $id;
  156. $this->module = $parent;
  157. parent::__construct($config);
  158. }
  159. /**
  160. * Returns the currently requested instance of this module class.
  161. * If the module class is not currently requested, `null` will be returned.
  162. * This method is provided so that you access the module instance from anywhere within the module.
  163. * @return static|null the currently requested instance of this module class, or `null` if the module class is not requested.
  164. */
  165. public static function getInstance()
  166. {
  167. $class = get_called_class();
  168. return isset(Yii::$app->loadedModules[$class]) ? Yii::$app->loadedModules[$class] : null;
  169. }
  170. /**
  171. * Sets the currently requested instance of this module class.
  172. * @param Module|null $instance the currently requested instance of this module class.
  173. * If it is `null`, the instance of the calling class will be removed, if any.
  174. */
  175. public static function setInstance($instance)
  176. {
  177. if ($instance === null) {
  178. unset(Yii::$app->loadedModules[get_called_class()]);
  179. } else {
  180. Yii::$app->loadedModules[get_class($instance)] = $instance;
  181. }
  182. }
  183. /**
  184. * Initializes the module.
  185. *
  186. * This method is called after the module is created and initialized with property values
  187. * given in configuration. The default implementation will initialize [[controllerNamespace]]
  188. * if it is not set.
  189. *
  190. * If you override this method, please make sure you call the parent implementation.
  191. */
  192. public function init()
  193. {
  194. if ($this->controllerNamespace === null) {
  195. $class = get_class($this);
  196. if (($pos = strrpos($class, '\\')) !== false) {
  197. $this->controllerNamespace = substr($class, 0, $pos) . '\\controllers';
  198. }
  199. }
  200. }
  201. /**
  202. * Returns an ID that uniquely identifies this module among all modules within the current application.
  203. * Note that if the module is an application, an empty string will be returned.
  204. * @return string the unique ID of the module.
  205. */
  206. public function getUniqueId()
  207. {
  208. return $this->module ? ltrim($this->module->getUniqueId() . '/' . $this->id, '/') : $this->id;
  209. }
  210. /**
  211. * Returns the root directory of the module.
  212. * It defaults to the directory containing the module class file.
  213. * @return string the root directory of the module.
  214. */
  215. public function getBasePath()
  216. {
  217. if ($this->_basePath === null) {
  218. $class = new \ReflectionClass($this);
  219. $this->_basePath = dirname($class->getFileName());
  220. }
  221. return $this->_basePath;
  222. }
  223. /**
  224. * Sets the root directory of the module.
  225. * This method can only be invoked at the beginning of the constructor.
  226. * @param string $path the root directory of the module. This can be either a directory name or a [path alias](guide:concept-aliases).
  227. * @throws InvalidArgumentException if the directory does not exist.
  228. */
  229. public function setBasePath($path)
  230. {
  231. $path = Yii::getAlias($path);
  232. $p = strncmp($path, 'phar://', 7) === 0 ? $path : realpath($path);
  233. if (is_string($p) && is_dir($p)) {
  234. $this->_basePath = $p;
  235. } else {
  236. throw new InvalidArgumentException("The directory does not exist: $path");
  237. }
  238. }
  239. /**
  240. * Returns the directory that contains the controller classes according to [[controllerNamespace]].
  241. * Note that in order for this method to return a value, you must define
  242. * an alias for the root namespace of [[controllerNamespace]].
  243. * @return string the directory that contains the controller classes.
  244. * @throws InvalidArgumentException if there is no alias defined for the root namespace of [[controllerNamespace]].
  245. */
  246. public function getControllerPath()
  247. {
  248. if ($this->_controllerPath === null) {
  249. $this->_controllerPath = Yii::getAlias('@' . str_replace('\\', '/', $this->controllerNamespace));
  250. }
  251. return $this->_controllerPath;
  252. }
  253. /**
  254. * Sets the directory that contains the controller classes.
  255. * @param string $path the root directory that contains the controller classes.
  256. * @throws InvalidArgumentException if the directory is invalid.
  257. * @since 2.0.44
  258. */
  259. public function setControllerPath($path)
  260. {
  261. $this->_controllerPath = Yii::getAlias($path);
  262. }
  263. /**
  264. * Returns the directory that contains the view files for this module.
  265. * @return string the root directory of view files. Defaults to "[[basePath]]/views".
  266. */
  267. public function getViewPath()
  268. {
  269. if ($this->_viewPath === null) {
  270. $this->_viewPath = $this->getBasePath() . DIRECTORY_SEPARATOR . 'views';
  271. }
  272. return $this->_viewPath;
  273. }
  274. /**
  275. * Sets the directory that contains the view files.
  276. * @param string $path the root directory of view files.
  277. * @throws InvalidArgumentException if the directory is invalid.
  278. */
  279. public function setViewPath($path)
  280. {
  281. $this->_viewPath = Yii::getAlias($path);
  282. }
  283. /**
  284. * Returns the directory that contains layout view files for this module.
  285. * @return string the root directory of layout files. Defaults to "[[viewPath]]/layouts".
  286. */
  287. public function getLayoutPath()
  288. {
  289. if ($this->_layoutPath === null) {
  290. $this->_layoutPath = $this->getViewPath() . DIRECTORY_SEPARATOR . 'layouts';
  291. }
  292. return $this->_layoutPath;
  293. }
  294. /**
  295. * Sets the directory that contains the layout files.
  296. * @param string $path the root directory or [path alias](guide:concept-aliases) of layout files.
  297. * @throws InvalidArgumentException if the directory is invalid
  298. */
  299. public function setLayoutPath($path)
  300. {
  301. $this->_layoutPath = Yii::getAlias($path);
  302. }
  303. /**
  304. * Returns current module version.
  305. * If version is not explicitly set, [[defaultVersion()]] method will be used to determine its value.
  306. * @return string the version of this module.
  307. * @since 2.0.11
  308. */
  309. public function getVersion()
  310. {
  311. if ($this->_version === null) {
  312. $this->_version = $this->defaultVersion();
  313. } else {
  314. if (!is_scalar($this->_version)) {
  315. $this->_version = call_user_func($this->_version, $this);
  316. }
  317. }
  318. return $this->_version;
  319. }
  320. /**
  321. * Sets current module version.
  322. * @param string|callable|null $version the version of this module.
  323. * Version can be specified as a PHP callback, which can accept module instance as an argument and should
  324. * return the actual version. For example:
  325. *
  326. * ```php
  327. * function (Module $module) {
  328. * //return string
  329. * }
  330. * ```
  331. *
  332. * @since 2.0.11
  333. */
  334. public function setVersion($version)
  335. {
  336. $this->_version = $version;
  337. }
  338. /**
  339. * Returns default module version.
  340. * Child class may override this method to provide more specific version detection.
  341. * @return string the version of this module.
  342. * @since 2.0.11
  343. */
  344. protected function defaultVersion()
  345. {
  346. if ($this->module === null) {
  347. return '1.0';
  348. }
  349. return $this->module->getVersion();
  350. }
  351. /**
  352. * Defines path aliases.
  353. * This method calls [[Yii::setAlias()]] to register the path aliases.
  354. * This method is provided so that you can define path aliases when configuring a module.
  355. * @property array list of path aliases to be defined. The array keys are alias names
  356. * (must start with `@`) and the array values are the corresponding paths or aliases.
  357. * See [[setAliases()]] for an example.
  358. * @param array $aliases list of path aliases to be defined. The array keys are alias names
  359. * (must start with `@`) and the array values are the corresponding paths or aliases.
  360. * For example,
  361. *
  362. * ```php
  363. * [
  364. * '@models' => '@app/models', // an existing alias
  365. * '@backend' => __DIR__ . '/../backend', // a directory
  366. * ]
  367. * ```
  368. */
  369. public function setAliases($aliases)
  370. {
  371. foreach ($aliases as $name => $alias) {
  372. Yii::setAlias($name, $alias);
  373. }
  374. }
  375. /**
  376. * Checks whether the child module of the specified ID exists.
  377. * This method supports checking the existence of both child and grand child modules.
  378. * @param string $id module ID. For grand child modules, use ID path relative to this module (e.g. `admin/content`).
  379. * @return bool whether the named module exists. Both loaded and unloaded modules
  380. * are considered.
  381. */
  382. public function hasModule($id)
  383. {
  384. if (($pos = strpos($id, '/')) !== false) {
  385. // sub-module
  386. $module = $this->getModule(substr($id, 0, $pos));
  387. return $module === null ? false : $module->hasModule(substr($id, $pos + 1));
  388. }
  389. return isset($this->_modules[$id]);
  390. }
  391. /**
  392. * Retrieves the child module of the specified ID.
  393. * This method supports retrieving both child modules and grand child modules.
  394. * @param string $id module ID (case-sensitive). To retrieve grand child modules,
  395. * use ID path relative to this module (e.g. `admin/content`).
  396. * @param bool $load whether to load the module if it is not yet loaded.
  397. * @return Module|null the module instance, `null` if the module does not exist.
  398. * @see hasModule()
  399. */
  400. public function getModule($id, $load = true)
  401. {
  402. if (($pos = strpos($id, '/')) !== false) {
  403. // sub-module
  404. $module = $this->getModule(substr($id, 0, $pos));
  405. return $module === null ? null : $module->getModule(substr($id, $pos + 1), $load);
  406. }
  407. if (isset($this->_modules[$id])) {
  408. if ($this->_modules[$id] instanceof self) {
  409. return $this->_modules[$id];
  410. } elseif ($load) {
  411. Yii::debug("Loading module: $id", __METHOD__);
  412. /** @var self $module */
  413. $module = Yii::createObject($this->_modules[$id], [$id, $this]);
  414. $module::setInstance($module);
  415. return $this->_modules[$id] = $module;
  416. }
  417. }
  418. return null;
  419. }
  420. /**
  421. * Adds a sub-module to this module.
  422. * @param string $id module ID.
  423. * @param Module|array|null $module the sub-module to be added to this module. This can
  424. * be one of the following:
  425. *
  426. * - a [[Module]] object
  427. * - a configuration array: when [[getModule()]] is called initially, the array
  428. * will be used to instantiate the sub-module
  429. * - `null`: the named sub-module will be removed from this module
  430. */
  431. public function setModule($id, $module)
  432. {
  433. if ($module === null) {
  434. unset($this->_modules[$id]);
  435. } else {
  436. $this->_modules[$id] = $module;
  437. if ($module instanceof self) {
  438. $module->module = $this;
  439. }
  440. }
  441. }
  442. /**
  443. * Returns the sub-modules in this module.
  444. * @param bool $loadedOnly whether to return the loaded sub-modules only. If this is set `false`,
  445. * then all sub-modules registered in this module will be returned, whether they are loaded or not.
  446. * Loaded modules will be returned as objects, while unloaded modules as configuration arrays.
  447. * @return array the modules (indexed by their IDs).
  448. */
  449. public function getModules($loadedOnly = false)
  450. {
  451. if ($loadedOnly) {
  452. $modules = [];
  453. foreach ($this->_modules as $module) {
  454. if ($module instanceof self) {
  455. $modules[] = $module;
  456. }
  457. }
  458. return $modules;
  459. }
  460. return $this->_modules;
  461. }
  462. /**
  463. * Registers sub-modules in the current module.
  464. *
  465. * Each sub-module should be specified as a name-value pair, where
  466. * name refers to the ID of the module and value the module or a configuration
  467. * array that can be used to create the module. In the latter case, [[Yii::createObject()]]
  468. * will be used to create the module.
  469. *
  470. * If a new sub-module has the same ID as an existing one, the existing one will be overwritten silently.
  471. *
  472. * The following is an example for registering two sub-modules:
  473. *
  474. * ```php
  475. * [
  476. * 'comment' => [
  477. * 'class' => 'app\modules\comment\CommentModule',
  478. * 'db' => 'db',
  479. * ],
  480. * 'booking' => ['class' => 'app\modules\booking\BookingModule'],
  481. * ]
  482. * ```
  483. *
  484. * @param array $modules modules (id => module configuration or instances).
  485. */
  486. public function setModules($modules)
  487. {
  488. foreach ($modules as $id => $module) {
  489. $this->_modules[$id] = $module;
  490. if ($module instanceof self) {
  491. $module->module = $this;
  492. }
  493. }
  494. }
  495. /**
  496. * Runs a controller action specified by a route.
  497. * This method parses the specified route and creates the corresponding child module(s), controller and action
  498. * instances. It then calls [[Controller::runAction()]] to run the action with the given parameters.
  499. * If the route is empty, the method will use [[defaultRoute]].
  500. * @param string $route the route that specifies the action.
  501. * @param array $params the parameters to be passed to the action
  502. * @return mixed the result of the action.
  503. * @throws InvalidRouteException if the requested route cannot be resolved into an action successfully.
  504. */
  505. public function runAction($route, $params = [])
  506. {
  507. $parts = $this->createController($route);
  508. if (is_array($parts)) {
  509. /** @var Controller $controller */
  510. list($controller, $actionID) = $parts;
  511. $oldController = Yii::$app->controller;
  512. Yii::$app->controller = $controller;
  513. $result = $controller->runAction($actionID, $params);
  514. if ($oldController !== null) {
  515. Yii::$app->controller = $oldController;
  516. }
  517. return $result;
  518. }
  519. $id = $this->getUniqueId();
  520. throw new InvalidRouteException('Unable to resolve the request "' . ($id === '' ? $route : $id . '/' . $route) . '".');
  521. }
  522. /**
  523. * Creates a controller instance based on the given route.
  524. *
  525. * The route should be relative to this module. The method implements the following algorithm
  526. * to resolve the given route:
  527. *
  528. * 1. If the route is empty, use [[defaultRoute]];
  529. * 2. If the first segment of the route is found in [[controllerMap]], create a controller
  530. * based on the corresponding configuration found in [[controllerMap]];
  531. * 3. If the first segment of the route is a valid module ID as declared in [[modules]],
  532. * call the module's `createController()` with the rest part of the route;
  533. * 4. The given route is in the format of `abc/def/xyz`. Try either `abc\DefController`
  534. * or `abc\def\XyzController` class within the [[controllerNamespace|controller namespace]].
  535. *
  536. * If any of the above steps resolves into a controller, it is returned together with the rest
  537. * part of the route which will be treated as the action ID. Otherwise, `false` will be returned.
  538. *
  539. * @param string $route the route consisting of module, controller and action IDs.
  540. * @return array|bool If the controller is created successfully, it will be returned together
  541. * with the requested action ID. Otherwise `false` will be returned.
  542. * @throws InvalidConfigException if the controller class and its file do not match.
  543. */
  544. public function createController($route)
  545. {
  546. if ($route === '') {
  547. $route = $this->defaultRoute;
  548. }
  549. // double slashes or leading/ending slashes may cause substr problem
  550. $route = trim($route, '/');
  551. if (strpos($route, '//') !== false) {
  552. return false;
  553. }
  554. if (strpos($route, '/') !== false) {
  555. list($id, $route) = explode('/', $route, 2);
  556. } else {
  557. $id = $route;
  558. $route = '';
  559. }
  560. // module and controller map take precedence
  561. if (isset($this->controllerMap[$id])) {
  562. $controller = Yii::createObject($this->controllerMap[$id], [$id, $this]);
  563. return [$controller, $route];
  564. }
  565. $module = $this->getModule($id);
  566. if ($module !== null) {
  567. return $module->createController($route);
  568. }
  569. if (($pos = strrpos($route, '/')) !== false) {
  570. $id .= '/' . substr($route, 0, $pos);
  571. $route = substr($route, $pos + 1);
  572. }
  573. $controller = $this->createControllerByID($id);
  574. if ($controller === null && $route !== '') {
  575. $controller = $this->createControllerByID($id . '/' . $route);
  576. $route = '';
  577. }
  578. return $controller === null ? false : [$controller, $route];
  579. }
  580. /**
  581. * Creates a controller based on the given controller ID.
  582. *
  583. * The controller ID is relative to this module. The controller class
  584. * should be namespaced under [[controllerNamespace]].
  585. *
  586. * Note that this method does not check [[modules]] or [[controllerMap]].
  587. *
  588. * @param string $id the controller ID.
  589. * @return Controller|null the newly created controller instance, or `null` if the controller ID is invalid.
  590. * @throws InvalidConfigException if the controller class and its file name do not match.
  591. * This exception is only thrown when in debug mode.
  592. */
  593. public function createControllerByID($id)
  594. {
  595. $pos = strrpos($id, '/');
  596. if ($pos === false) {
  597. $prefix = '';
  598. $className = $id;
  599. } else {
  600. $prefix = substr($id, 0, $pos + 1);
  601. $className = substr($id, $pos + 1);
  602. }
  603. if ($this->isIncorrectClassNameOrPrefix($className, $prefix)) {
  604. return null;
  605. }
  606. $className = preg_replace_callback('%-([a-z0-9_])%i', function ($matches) {
  607. return ucfirst($matches[1]);
  608. }, ucfirst($className)) . 'Controller';
  609. $className = ltrim($this->controllerNamespace . '\\' . str_replace('/', '\\', $prefix) . $className, '\\');
  610. if (strpos($className, '-') !== false || !class_exists($className)) {
  611. return null;
  612. }
  613. if (is_subclass_of($className, 'yii\base\Controller')) {
  614. $controller = Yii::createObject($className, [$id, $this]);
  615. return get_class($controller) === $className ? $controller : null;
  616. } elseif (YII_DEBUG) {
  617. throw new InvalidConfigException('Controller class must extend from \\yii\\base\\Controller.');
  618. }
  619. return null;
  620. }
  621. /**
  622. * Checks if class name or prefix is incorrect
  623. *
  624. * @param string $className
  625. * @param string $prefix
  626. * @return bool
  627. */
  628. private function isIncorrectClassNameOrPrefix($className, $prefix)
  629. {
  630. if (!preg_match('%^[a-z][a-z0-9\\-_]*$%', $className)) {
  631. return true;
  632. }
  633. if ($prefix !== '' && !preg_match('%^[a-z0-9_/]+$%i', $prefix)) {
  634. return true;
  635. }
  636. return false;
  637. }
  638. /**
  639. * This method is invoked right before an action within this module is executed.
  640. *
  641. * The method will trigger the [[EVENT_BEFORE_ACTION]] event. The return value of the method
  642. * will determine whether the action should continue to run.
  643. *
  644. * In case the action should not run, the request should be handled inside of the `beforeAction` code
  645. * by either providing the necessary output or redirecting the request. Otherwise the response will be empty.
  646. *
  647. * If you override this method, your code should look like the following:
  648. *
  649. * ```php
  650. * public function beforeAction($action)
  651. * {
  652. * if (!parent::beforeAction($action)) {
  653. * return false;
  654. * }
  655. *
  656. * // your custom code here
  657. *
  658. * return true; // or false to not run the action
  659. * }
  660. * ```
  661. *
  662. * @param Action $action the action to be executed.
  663. * @return bool whether the action should continue to be executed.
  664. */
  665. public function beforeAction($action)
  666. {
  667. $event = new ActionEvent($action);
  668. $this->trigger(self::EVENT_BEFORE_ACTION, $event);
  669. return $event->isValid;
  670. }
  671. /**
  672. * This method is invoked right after an action within this module is executed.
  673. *
  674. * The method will trigger the [[EVENT_AFTER_ACTION]] event. The return value of the method
  675. * will be used as the action return value.
  676. *
  677. * If you override this method, your code should look like the following:
  678. *
  679. * ```php
  680. * public function afterAction($action, $result)
  681. * {
  682. * $result = parent::afterAction($action, $result);
  683. * // your custom code here
  684. * return $result;
  685. * }
  686. * ```
  687. *
  688. * @param Action $action the action just executed.
  689. * @param mixed $result the action return result.
  690. * @return mixed the processed action result.
  691. */
  692. public function afterAction($action, $result)
  693. {
  694. $event = new ActionEvent($action);
  695. $event->result = $result;
  696. $this->trigger(self::EVENT_AFTER_ACTION, $event);
  697. return $event->result;
  698. }
  699. /**
  700. * {@inheritdoc}
  701. *
  702. * Since version 2.0.13, if a component isn't defined in the module, it will be looked up in the parent module.
  703. * The parent module may be the application.
  704. */
  705. public function get($id, $throwException = true)
  706. {
  707. if (!isset($this->module)) {
  708. return parent::get($id, $throwException);
  709. }
  710. $component = parent::get($id, false);
  711. if ($component === null) {
  712. $component = $this->module->get($id, $throwException);
  713. }
  714. return $component;
  715. }
  716. /**
  717. * {@inheritdoc}
  718. *
  719. * Since version 2.0.13, if a component isn't defined in the module, it will be looked up in the parent module.
  720. * The parent module may be the application.
  721. */
  722. public function has($id, $checkInstance = false)
  723. {
  724. return parent::has($id, $checkInstance) || (isset($this->module) && $this->module->has($id, $checkInstance));
  725. }
  726. }