Completed
Push — master ( b6b02f...04281c )
by Alexander
38:41 queued 36:06
created

Module   D

Complexity

Total Complexity 80

Size/Duplication

Total Lines 703
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 7

Test Coverage

Coverage 60.22%

Importance

Changes 0
Metric Value
wmc 80
lcom 2
cbo 7
dl 0
loc 703
ccs 106
cts 176
cp 0.6022
rs 4.4444
c 0
b 0
f 0

28 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A getInstance() 0 5 2
A getUniqueId() 0 4 2
A getControllerPath() 0 4 1
A setBasePath() 0 10 4
A beforeAction() 0 6 1
A afterAction() 0 7 1
A setInstance() 0 8 2
A init() 0 9 3
A getBasePath() 0 9 2
A getViewPath() 0 8 2
A setViewPath() 0 4 1
A getLayoutPath() 0 8 2
A setLayoutPath() 0 4 1
A getVersion() 0 12 3
A setVersion() 0 4 1
A defaultVersion() 0 8 2
A setAliases() 0 6 2
A hasModule() 0 11 3
B getModule() 0 23 6
A setModule() 0 8 2
A getModules() 0 15 4
A setModules() 0 6 2
A runAction() 0 19 4
D createController() 0 42 10
D createControllerByID() 0 33 10
A get() 0 12 3
A has() 0 4 3

How to fix   Complexity   

Complex Class

Complex classes like Module often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Module, and based on these observations, apply Extract Interface, too.

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