GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 2ab419...940f7c )
by Robert
32:50
created

Module::init()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

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