Completed
Push — master ( a5b393...b0162d )
by Dmitry
11:08
created

framework/base/Module.php (3 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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
8
namespace yii\base;
9
10
use Yii;
11
use yii\di\ServiceLocator;
12
13
/**
14
 * Module is the base class for module and application classes.
15
 *
16
 * A module represents a sub-application which contains MVC elements by itself, such as
17
 * models, views, controllers, etc.
18
 *
19
 * A module may consist of [[modules|sub-modules]].
20
 *
21
 * [[components|Components]] may be registered with the module so that they are globally
22
 * accessible within the module.
23
 *
24
 * For more details and usage information on Module, see the [guide article on modules](guide:structure-modules).
25
 *
26
 * @property array $aliases List of path aliases to be defined. The array keys are alias names (must start
27
 * with `@`) and the array values are the corresponding paths or aliases. See [[setAliases()]] for an example.
28
 * This property is write-only.
29
 * @property string $basePath The root directory of the module.
30
 * @property string $controllerPath The directory that contains the controller classes. This property is
31
 * read-only.
32
 * @property string $layoutPath The root directory of layout files. Defaults to "[[viewPath]]/layouts".
33
 * @property array $modules The modules (indexed by their IDs).
34
 * @property string $uniqueId The unique ID of the module. This property is read-only.
35
 * @property string $version The version of this module. Note that the type of this property differs in getter
36
 * and setter. See [[getVersion()]] and [[setVersion()]] for details.
37
 * @property string $viewPath The root directory of view files. Defaults to "[[basePath]]/views".
38
 *
39
 * @author Qiang Xue <[email protected]>
40
 * @since 2.0
41
 */
42
class Module extends ServiceLocator
43
{
44
    /**
45
     * @event ActionEvent an event raised before executing a controller action.
46
     * You may set [[ActionEvent::isValid]] to be `false` to cancel the action execution.
47
     */
48
    const EVENT_BEFORE_ACTION = 'beforeAction';
49
    /**
50
     * @event ActionEvent an event raised after executing a controller action.
51
     */
52
    const EVENT_AFTER_ACTION = 'afterAction';
53
54
    /**
55
     * @var array custom module parameters (name => value).
56
     */
57
    public $params = [];
58
    /**
59
     * @var string an ID that uniquely identifies this module among other modules which have the same [[module|parent]].
60
     */
61
    public $id;
62
    /**
63
     * @var Module the parent module of this module. `null` if this module does not have a parent.
64
     */
65
    public $module;
66
    /**
67
     * @var string|bool the layout that should be applied for views within this module. This refers to a view name
68
     * relative to [[layoutPath]]. If this is not set, it means the layout value of the [[module|parent module]]
69
     * will be taken. If this is `false`, layout will be disabled within this module.
70
     */
71
    public $layout;
72
    /**
73
     * @var array mapping from controller ID to controller configurations.
74
     * Each name-value pair specifies the configuration of a single controller.
75
     * A controller configuration can be either a string or an array.
76
     * If the former, the string should be the fully qualified class name of the controller.
77
     * If the latter, the array must contain a `class` element which specifies
78
     * the controller's fully qualified class name, and the rest of the name-value pairs
79
     * in the array are used to initialize the corresponding controller properties. For example,
80
     *
81
     * ```php
82
     * [
83
     *   'account' => 'app\controllers\UserController',
84
     *   'article' => [
85
     *      'class' => 'app\controllers\PostController',
86
     *      'pageTitle' => 'something new',
87
     *   ],
88
     * ]
89
     * ```
90
     */
91
    public $controllerMap = [];
92
    /**
93
     * @var string the namespace that controller classes are in.
94
     * This namespace will be used to load controller classes by prepending it to the controller
95
     * class name.
96
     *
97
     * If not set, it will use the `controllers` sub-namespace under the namespace of this module.
98
     * For example, if the namespace of this module is `foo\bar`, then the default
99
     * controller namespace would be `foo\bar\controllers`.
100
     *
101
     * See also the [guide section on autoloading](guide:concept-autoloading) to learn more about
102
     * defining namespaces and how classes are loaded.
103
     */
104
    public $controllerNamespace;
105
    /**
106
     * @var string the default route of this module. Defaults to `default`.
107
     * The route may consist of child module ID, controller ID, and/or action ID.
108
     * For example, `help`, `post/create`, `admin/post/create`.
109
     * If action ID is not given, it will take the default value as specified in
110
     * [[Controller::defaultAction]].
111
     */
112
    public $defaultRoute = 'default';
113
114
    /**
115
     * @var string the root directory of the module.
116
     */
117
    private $_basePath;
118
    /**
119
     * @var string the root directory that contains view files for this module
120
     */
121
    private $_viewPath;
122
    /**
123
     * @var string the root directory that contains layout view files for this module.
124
     */
125
    private $_layoutPath;
126
    /**
127
     * @var array child modules of this module
128
     */
129
    private $_modules = [];
130
    /**
131
     * @var string|callable the version of this module.
132
     * Version can be specified as a PHP callback, which can accept module instance as an argument and should
133
     * return the actual version. For example:
134
     *
135
     * ```php
136
     * function (Module $module) {
137
     *     //return string|int
138
     * }
139
     * ```
140
     *
141
     * If not set, [[defaultVersion()]] will be used to determine actual value.
142
     *
143
     * @since 2.0.11
144
     */
145
    private $_version;
146
147
148
    /**
149
     * Constructor.
150
     * @param string $id the ID of this module.
151
     * @param Module $parent the parent module (if any).
152
     * @param array $config name-value pairs that will be used to initialize the object properties.
153
     */
154 101
    public function __construct($id, $parent = null, $config = [])
155
    {
156 101
        $this->id = $id;
157 101
        $this->module = $parent;
158 101
        parent::__construct($config);
159 101
    }
160
161
    /**
162
     * Returns the currently requested instance of this module class.
163
     * If the module class is not currently requested, `null` will be returned.
164
     * This method is provided so that you access the module instance from anywhere within the module.
165
     * @return static|null the currently requested instance of this module class, or `null` if the module class is not requested.
166
     */
167
    public static function getInstance()
168
    {
169
        $class = get_called_class();
170
        return isset(Yii::$app->loadedModules[$class]) ? Yii::$app->loadedModules[$class] : null;
171
    }
172
173
    /**
174
     * Sets the currently requested instance of this module class.
175
     * @param Module|null $instance the currently requested instance of this module class.
176
     * If it is `null`, the instance of the calling class will be removed, if any.
177
     */
178 2762
    public static function setInstance($instance)
179
    {
180 2762
        if ($instance === null) {
181
            unset(Yii::$app->loadedModules[get_called_class()]);
182
        } else {
183 2762
            Yii::$app->loadedModules[get_class($instance)] = $instance;
184
        }
185 2762
    }
186
187
    /**
188
     * Initializes the module.
189
     *
190
     * This method is called after the module is created and initialized with property values
191
     * given in configuration. The default implementation will initialize [[controllerNamespace]]
192
     * if it is not set.
193
     *
194
     * If you override this method, please make sure you call the parent implementation.
195
     */
196 101
    public function init()
197
    {
198 101
        if ($this->controllerNamespace === null) {
199 101
            $class = get_class($this);
200 101
            if (($pos = strrpos($class, '\\')) !== false) {
201 6
                $this->controllerNamespace = substr($class, 0, $pos) . '\\controllers';
202
            }
203
        }
204 101
    }
205
206
    /**
207
     * Returns an ID that uniquely identifies this module among all modules within the current application.
208
     * Note that if the module is an application, an empty string will be returned.
209
     * @return string the unique ID of the module.
210
     */
211 74
    public function getUniqueId()
212
    {
213 74
        return $this->module ? ltrim($this->module->getUniqueId() . '/' . $this->id, '/') : $this->id;
214
    }
215
216
    /**
217
     * Returns the root directory of the module.
218
     * It defaults to the directory containing the module class file.
219
     * @return string the root directory of the module.
220
     */
221 2762
    public function getBasePath()
222
    {
223 2762
        if ($this->_basePath === null) {
224
            $class = new \ReflectionClass($this);
225
            $this->_basePath = dirname($class->getFileName());
226
        }
227
228 2762
        return $this->_basePath;
229
    }
230
231
    /**
232
     * Sets the root directory of the module.
233
     * This method can only be invoked at the beginning of the constructor.
234
     * @param string $path the root directory of the module. This can be either a directory name or a [path alias](guide:concept-aliases).
235
     * @throws InvalidParamException if the directory does not exist.
236
     */
237 2762
    public function setBasePath($path)
238
    {
239 2762
        $path = Yii::getAlias($path);
240 2762
        $p = strncmp($path, 'phar://', 7) === 0 ? $path : realpath($path);
241 2762
        if ($p !== false && is_dir($p)) {
242 2762
            $this->_basePath = $p;
0 ignored issues
show
Documentation Bug introduced by
It seems like $p can also be of type boolean. However, the property $_basePath is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
243
        } else {
244
            throw new InvalidParamException("The directory does not exist: $path");
245
        }
246 2762
    }
247
248
    /**
249
     * Returns the directory that contains the controller classes according to [[controllerNamespace]].
250
     * Note that in order for this method to return a value, you must define
251
     * an alias for the root namespace of [[controllerNamespace]].
252
     * @return string the directory that contains the controller classes.
253
     * @throws InvalidParamException if there is no alias defined for the root namespace of [[controllerNamespace]].
254
     */
255 18
    public function getControllerPath()
256
    {
257 18
        return Yii::getAlias('@' . str_replace('\\', '/', $this->controllerNamespace));
258
    }
259
260
    /**
261
     * Returns the directory that contains the view files for this module.
262
     * @return string the root directory of view files. Defaults to "[[basePath]]/views".
263
     */
264 1
    public function getViewPath()
265
    {
266 1
        if ($this->_viewPath === null) {
267 1
            $this->_viewPath = $this->getBasePath() . DIRECTORY_SEPARATOR . 'views';
268
        }
269 1
        return $this->_viewPath;
270
    }
271
272
    /**
273
     * Sets the directory that contains the view files.
274
     * @param string $path the root directory of view files.
275
     * @throws InvalidParamException if the directory is invalid.
276
     */
277
    public function setViewPath($path)
278
    {
279
        $this->_viewPath = Yii::getAlias($path);
0 ignored issues
show
Documentation Bug introduced by
It seems like \Yii::getAlias($path) can also be of type boolean. However, the property $_viewPath is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
280
    }
281
282
    /**
283
     * Returns the directory that contains layout view files for this module.
284
     * @return string the root directory of layout files. Defaults to "[[viewPath]]/layouts".
285
     */
286
    public function getLayoutPath()
287
    {
288
        if ($this->_layoutPath === null) {
289
            $this->_layoutPath = $this->getViewPath() . DIRECTORY_SEPARATOR . 'layouts';
290
        }
291
292
        return $this->_layoutPath;
293
    }
294
295
    /**
296
     * Sets the directory that contains the layout files.
297
     * @param string $path the root directory or [path alias](guide:concept-aliases) of layout files.
298
     * @throws InvalidParamException if the directory is invalid
299
     */
300
    public function setLayoutPath($path)
301
    {
302
        $this->_layoutPath = Yii::getAlias($path);
0 ignored issues
show
Documentation Bug introduced by
It seems like \Yii::getAlias($path) can also be of type boolean. However, the property $_layoutPath is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
303
    }
304
305
    /**
306
     * Returns current module version.
307
     * If version is not explicitly set, [[defaultVersion()]] method will be used to determine its value.
308
     * @return string the version of this module.
309
     * @since 2.0.11
310
     */
311 2
    public function getVersion()
312
    {
313 2
        if ($this->_version === null) {
314 1
            $this->_version = $this->defaultVersion();
315
        } else {
316 1
            if (!is_scalar($this->_version)) {
317 1
                $this->_version = call_user_func($this->_version, $this);
318
            }
319
        }
320 2
        return $this->_version;
321
    }
322
323
    /**
324
     * Sets current module version.
325
     * @param string|callable $version the version of this module.
326
     * Version can be specified as a PHP callback, which can accept module instance as an argument and should
327
     * return the actual version. For example:
328
     *
329
     * ```php
330
     * function (Module $module) {
331
     *     //return string
332
     * }
333
     * ```
334
     *
335
     * @since 2.0.11
336
     */
337 1
    public function setVersion($version)
338
    {
339 1
        $this->_version = $version;
340 1
    }
341
342
    /**
343
     * Returns default module version.
344
     * Child class may override this method to provide more specific version detection.
345
     * @return string the version of this module.
346
     * @since 2.0.11
347
     */
348 1
    protected function defaultVersion()
349
    {
350 1
        if ($this->module === null) {
351 1
            return '1.0';
352
        }
353
        return $this->module->getVersion();
354
    }
355
356
    /**
357
     * Defines path aliases.
358
     * This method calls [[Yii::setAlias()]] to register the path aliases.
359
     * This method is provided so that you can define path aliases when configuring a module.
360
     * @property array list of path aliases to be defined. The array keys are alias names
361
     * (must start with `@`) and the array values are the corresponding paths or aliases.
362
     * See [[setAliases()]] for an example.
363
     * @param array $aliases list of path aliases to be defined. The array keys are alias names
364
     * (must start with `@`) and the array values are the corresponding paths or aliases.
365
     * For example,
366
     *
367
     * ```php
368
     * [
369
     *     '@models' => '@app/models', // an existing alias
370
     *     '@backend' => __DIR__ . '/../backend',  // a directory
371
     * ]
372
     * ```
373
     */
374 226
    public function setAliases($aliases)
375
    {
376 226
        foreach ($aliases as $name => $alias) {
377 226
            Yii::setAlias($name, $alias);
378
        }
379 226
    }
380
381
    /**
382
     * Checks whether the child module of the specified ID exists.
383
     * This method supports checking the existence of both child and grand child modules.
384
     * @param string $id module ID. For grand child modules, use ID path relative to this module (e.g. `admin/content`).
385
     * @return bool whether the named module exists. Both loaded and unloaded modules
386
     * are considered.
387
     */
388
    public function hasModule($id)
389
    {
390
        if (($pos = strpos($id, '/')) !== false) {
391
            // sub-module
392
            $module = $this->getModule(substr($id, 0, $pos));
393
394
            return $module === null ? false : $module->hasModule(substr($id, $pos + 1));
395
        }
396
        return isset($this->_modules[$id]);
397
    }
398
399
    /**
400
     * Retrieves the child module of the specified ID.
401
     * This method supports retrieving both child modules and grand child modules.
402
     * @param string $id module ID (case-sensitive). To retrieve grand child modules,
403
     * use ID path relative to this module (e.g. `admin/content`).
404
     * @param bool $load whether to load the module if it is not yet loaded.
405
     * @return Module|null the module instance, `null` if the module does not exist.
406
     * @see hasModule()
407
     */
408
    public function getModule($id, $load = true)
409
    {
410
        if (($pos = strpos($id, '/')) !== false) {
411
            // sub-module
412
            $module = $this->getModule(substr($id, 0, $pos));
413
414
            return $module === null ? null : $module->getModule(substr($id, $pos + 1), $load);
415
        }
416
417
        if (isset($this->_modules[$id])) {
418
            if ($this->_modules[$id] instanceof self) {
419
                return $this->_modules[$id];
420
            } elseif ($load) {
421
                Yii::trace("Loading module: $id", __METHOD__);
422
                /* @var $module Module */
423
                $module = Yii::createObject($this->_modules[$id], [$id, $this]);
424
                $module->setInstance($module);
425
                return $this->_modules[$id] = $module;
426
            }
427
        }
428
429
        return null;
430
    }
431
432
    /**
433
     * Adds a sub-module to this module.
434
     * @param string $id module ID.
435
     * @param Module|array|null $module the sub-module to be added to this module. This can
436
     * be one of the following:
437
     *
438
     * - a [[Module]] object
439
     * - a configuration array: when [[getModule()]] is called initially, the array
440
     *   will be used to instantiate the sub-module
441
     * - `null`: the named sub-module will be removed from this module
442
     */
443
    public function setModule($id, $module)
444
    {
445
        if ($module === null) {
446
            unset($this->_modules[$id]);
447
        } else {
448
            $this->_modules[$id] = $module;
449
        }
450
    }
451
452
    /**
453
     * Returns the sub-modules in this module.
454
     * @param bool $loadedOnly whether to return the loaded sub-modules only. If this is set `false`,
455
     * then all sub-modules registered in this module will be returned, whether they are loaded or not.
456
     * Loaded modules will be returned as objects, while unloaded modules as configuration arrays.
457
     * @return array the modules (indexed by their IDs).
458
     */
459 17
    public function getModules($loadedOnly = false)
460
    {
461 17
        if ($loadedOnly) {
462
            $modules = [];
463
            foreach ($this->_modules as $module) {
464
                if ($module instanceof self) {
465
                    $modules[] = $module;
466
                }
467
            }
468
469
            return $modules;
470
        }
471 17
        return $this->_modules;
472
    }
473
474
    /**
475
     * Registers sub-modules in the current module.
476
     *
477
     * Each sub-module should be specified as a name-value pair, where
478
     * name refers to the ID of the module and value the module or a configuration
479
     * array that can be used to create the module. In the latter case, [[Yii::createObject()]]
480
     * will be used to create the module.
481
     *
482
     * If a new sub-module has the same ID as an existing one, the existing one will be overwritten silently.
483
     *
484
     * The following is an example for registering two sub-modules:
485
     *
486
     * ```php
487
     * [
488
     *     'comment' => [
489
     *         'class' => 'app\modules\comment\CommentModule',
490
     *         'db' => 'db',
491
     *     ],
492
     *     'booking' => ['class' => 'app\modules\booking\BookingModule'],
493
     * ]
494
     * ```
495
     *
496
     * @param array $modules modules (id => module configuration or instances).
497
     */
498
    public function setModules($modules)
499
    {
500
        foreach ($modules as $id => $module) {
501
            $this->_modules[$id] = $module;
502
        }
503
    }
504
505
    /**
506
     * Runs a controller action specified by a route.
507
     * This method parses the specified route and creates the corresponding child module(s), controller and action
508
     * instances. It then calls [[Controller::runAction()]] to run the action with the given parameters.
509
     * If the route is empty, the method will use [[defaultRoute]].
510
     * @param string $route the route that specifies the action.
511
     * @param array $params the parameters to be passed to the action
512
     * @return mixed the result of the action.
513
     * @throws InvalidRouteException if the requested route cannot be resolved into an action successfully.
514
     */
515 11
    public function runAction($route, $params = [])
516
    {
517 11
        $parts = $this->createController($route);
518 11
        if (is_array($parts)) {
519
            /* @var $controller Controller */
520 11
            list($controller, $actionID) = $parts;
521 11
            $oldController = Yii::$app->controller;
522 11
            Yii::$app->controller = $controller;
523 11
            $result = $controller->runAction($actionID, $params);
524 11
            if ($oldController !== null) {
525 9
                Yii::$app->controller = $oldController;
526
            }
527
528 11
            return $result;
529
        }
530
531
        $id = $this->getUniqueId();
532
        throw new InvalidRouteException('Unable to resolve the request "' . ($id === '' ? $route : $id . '/' . $route) . '".');
533
    }
534
535
    /**
536
     * Creates a controller instance based on the given route.
537
     *
538
     * The route should be relative to this module. The method implements the following algorithm
539
     * to resolve the given route:
540
     *
541
     * 1. If the route is empty, use [[defaultRoute]];
542
     * 2. If the first segment of the route is a valid module ID as declared in [[modules]],
543
     *    call the module's `createController()` with the rest part of the route;
544
     * 3. If the first segment of the route is found in [[controllerMap]], create a controller
545
     *    based on the corresponding configuration found in [[controllerMap]];
546
     * 4. The given route is in the format of `abc/def/xyz`. Try either `abc\DefController`
547
     *    or `abc\def\XyzController` class within the [[controllerNamespace|controller namespace]].
548
     *
549
     * If any of the above steps resolves into a controller, it is returned together with the rest
550
     * part of the route which will be treated as the action ID. Otherwise, `false` will be returned.
551
     *
552
     * @param string $route the route consisting of module, controller and action IDs.
553
     * @return array|bool If the controller is created successfully, it will be returned together
554
     * with the requested action ID. Otherwise `false` will be returned.
555
     * @throws InvalidConfigException if the controller class and its file do not match.
556
     */
557 55
    public function createController($route)
558
    {
559 55
        if ($route === '') {
560
            $route = $this->defaultRoute;
561
        }
562
563
        // double slashes or leading/ending slashes may cause substr problem
564 55
        $route = trim($route, '/');
565 55
        if (strpos($route, '//') !== false) {
566
            return false;
567
        }
568
569 55
        if (strpos($route, '/') !== false) {
570 12
            list($id, $route) = explode('/', $route, 2);
571
        } else {
572 44
            $id = $route;
573 44
            $route = '';
574
        }
575
576
        // module and controller map take precedence
577 55
        if (isset($this->controllerMap[$id])) {
578 55
            $controller = Yii::createObject($this->controllerMap[$id], [$id, $this]);
579 55
            return [$controller, $route];
580
        }
581
        $module = $this->getModule($id);
582
        if ($module !== null) {
583
            return $module->createController($route);
584
        }
585
586
        if (($pos = strrpos($route, '/')) !== false) {
587
            $id .= '/' . substr($route, 0, $pos);
588
            $route = substr($route, $pos + 1);
589
        }
590
591
        $controller = $this->createControllerByID($id);
592
        if ($controller === null && $route !== '') {
593
            $controller = $this->createControllerByID($id . '/' . $route);
594
            $route = '';
595
        }
596
597
        return $controller === null ? false : [$controller, $route];
598
    }
599
600
    /**
601
     * Creates a controller based on the given controller ID.
602
     *
603
     * The controller ID is relative to this module. The controller class
604
     * should be namespaced under [[controllerNamespace]].
605
     *
606
     * Note that this method does not check [[modules]] or [[controllerMap]].
607
     *
608
     * @param string $id the controller ID.
609
     * @return Controller|null the newly created controller instance, or `null` if the controller ID is invalid.
610
     * @throws InvalidConfigException if the controller class and its file name do not match.
611
     * This exception is only thrown when in debug mode.
612
     */
613
    public function createControllerByID($id)
614
    {
615
        $pos = strrpos($id, '/');
616
        if ($pos === false) {
617
            $prefix = '';
618
            $className = $id;
619
        } else {
620
            $prefix = substr($id, 0, $pos + 1);
621
            $className = substr($id, $pos + 1);
622
        }
623
624
        if (!preg_match('%^[a-z][a-z0-9\\-_]*$%', $className)) {
625
            return null;
626
        }
627
        if ($prefix !== '' && !preg_match('%^[a-z0-9_/]+$%i', $prefix)) {
628
            return null;
629
        }
630
631
        $className = str_replace(' ', '', ucwords(str_replace('-', ' ', $className))) . 'Controller';
632
        $className = ltrim($this->controllerNamespace . '\\' . str_replace('/', '\\', $prefix) . $className, '\\');
633
        if (strpos($className, '-') !== false || !class_exists($className)) {
634
            return null;
635
        }
636
637
        if (is_subclass_of($className, 'yii\base\Controller')) {
638
            $controller = Yii::createObject($className, [$id, $this]);
639
            return get_class($controller) === $className ? $controller : null;
640
        } elseif (YII_DEBUG) {
641
            throw new InvalidConfigException('Controller class must extend from \\yii\\base\\Controller.');
642
        }
643
        return null;
644
    }
645
646
    /**
647
     * This method is invoked right before an action within this module is executed.
648
     *
649
     * The method will trigger the [[EVENT_BEFORE_ACTION]] event. The return value of the method
650
     * will determine whether the action should continue to run.
651
     *
652
     * In case the action should not run, the request should be handled inside of the `beforeAction` code
653
     * by either providing the necessary output or redirecting the request. Otherwise the response will be empty.
654
     *
655
     * If you override this method, your code should look like the following:
656
     *
657
     * ```php
658
     * public function beforeAction($action)
659
     * {
660
     *     if (!parent::beforeAction($action)) {
661
     *         return false;
662
     *     }
663
     *
664
     *     // your custom code here
665
     *
666
     *     return true; // or false to not run the action
667
     * }
668
     * ```
669
     *
670
     * @param Action $action the action to be executed.
671
     * @return bool whether the action should continue to be executed.
672
     */
673 114
    public function beforeAction($action)
674
    {
675 114
        $event = new ActionEvent($action);
676 114
        $this->trigger(self::EVENT_BEFORE_ACTION, $event);
677 114
        return $event->isValid;
678
    }
679
680
    /**
681
     * This method is invoked right after an action within this module is executed.
682
     *
683
     * The method will trigger the [[EVENT_AFTER_ACTION]] event. The return value of the method
684
     * will be used as the action return value.
685
     *
686
     * If you override this method, your code should look like the following:
687
     *
688
     * ```php
689
     * public function afterAction($action, $result)
690
     * {
691
     *     $result = parent::afterAction($action, $result);
692
     *     // your custom code here
693
     *     return $result;
694
     * }
695
     * ```
696
     *
697
     * @param Action $action the action just executed.
698
     * @param mixed $result the action return result.
699
     * @return mixed the processed action result.
700
     */
701 110
    public function afterAction($action, $result)
702
    {
703 110
        $event = new ActionEvent($action);
704 110
        $event->result = $result;
705 110
        $this->trigger(self::EVENT_AFTER_ACTION, $event);
706 110
        return $event->result;
707
    }
708
}
709