Module   F
last analyzed

Complexity

Total Complexity 86

Size/Duplication

Total Lines 747
Duplicated Lines 0 %

Test Coverage

Coverage 83.89%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 86
eloc 172
c 1
b 0
f 0
dl 0
loc 747
ccs 151
cts 180
cp 0.8389
rs 2

30 Methods

Rating   Name   Duplication   Size   Complexity  
A setModules() 0 6 3
A setLayoutPath() 0 3 1
A afterAction() 0 6 1
A getLayoutPath() 0 7 2
A getControllerPath() 0 7 2
A setBasePath() 0 8 4
A runAction() 0 18 4
A get() 0 11 3
A beforeAction() 0 5 1
A getUniqueId() 0 3 2
A getModule() 0 22 6
A setViewPath() 0 3 1
A getInstance() 0 4 2
A setControllerPath() 0 3 1
A getBasePath() 0 8 2
A getViewPath() 0 7 2
A getVersion() 0 11 3
A getModules() 0 14 4
B createController() 0 41 10
A setModule() 0 8 3
A setAliases() 0 4 2
A hasModule() 0 10 3
A has() 0 3 3
A __construct() 0 5 1
A setInstance() 0 6 2
B createControllerByID() 0 31 8
A setVersion() 0 3 1
A init() 0 6 3
A isIncorrectClassNameOrPrefix() 0 10 4
A defaultVersion() 0 7 2

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.

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 https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://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-write array $aliases List of path aliases to be defined. The array keys are alias names (must
27
 * start with `@`) and the array values are the corresponding paths or aliases. See [[setAliases()]] for an
28
 * example.
29
 * @property string $basePath The root directory of the module.
30
 * @property string $controllerPath The directory that contains the controller classes.
31
 * @property string $layoutPath The root directory of layout files. Defaults to "[[viewPath]]/layouts".
32
 * @property array $modules The modules (indexed by their IDs).
33
 * @property-read string $uniqueId The unique ID of the module.
34
 * @property string $version The version of this module. Note that the type of this property differs in getter
35
 * and setter. See [[getVersion()]] and [[setVersion()]] for details.
36
 * @property string $viewPath The root directory of view files. Defaults to "[[basePath]]/views".
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|null the parent module of this module. `null` if this module does not have a parent.
63
     */
64
    public $module;
65
    /**
66
     * @var string|bool|null 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|null 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 the controller classes for this module.
119
     */
120
    private $_controllerPath;
121
    /**
122
     * @var string the root directory that contains view files for this module
123
     */
124
    private $_viewPath;
125
    /**
126
     * @var string the root directory that contains layout view files for this module.
127
     */
128
    private $_layoutPath;
129
    /**
130
     * @var array child modules of this module
131
     */
132
    private $_modules = [];
133
    /**
134
     * @var string|callable|null the version of this module.
135
     * Version can be specified as a PHP callback, which can accept module instance as an argument and should
136
     * return the actual version. For example:
137
     *
138
     * ```php
139
     * function (Module $module) {
140
     *     //return string|int
141
     * }
142
     * ```
143
     *
144
     * If not set, [[defaultVersion()]] will be used to determine actual value.
145
     *
146
     * @since 2.0.11
147
     */
148
    private $_version;
149
150
151
    /**
152
     * Constructor.
153
     * @param string $id the ID of this module.
154
     * @param Module|null $parent the parent module (if any).
155
     * @param array $config name-value pairs that will be used to initialize the object properties.
156
     *
157
     * @phpstan-param array<string, mixed> $config
158
     * @psalm-param array<string, mixed> $config
159
     */
160 106
    public function __construct($id, $parent = null, $config = [])
161
    {
162 106
        $this->id = $id;
163 106
        $this->module = $parent;
164 106
        parent::__construct($config);
165
    }
166
167
    /**
168
     * Returns the currently requested instance of this module class.
169
     * If the module class is not currently requested, `null` will be returned.
170
     * This method is provided so that you access the module instance from anywhere within the module.
171
     * @return static|null the currently requested instance of this module class, or `null` if the module class is not requested.
172
     */
173
    public static function getInstance()
174
    {
175
        $class = get_called_class();
176
        return isset(Yii::$app->loadedModules[$class]) ? Yii::$app->loadedModules[$class] : null;
177
    }
178
179
    /**
180
     * Sets the currently requested instance of this module class.
181
     * @param Module|null $instance the currently requested instance of this module class.
182
     * If it is `null`, the instance of the calling class will be removed, if any.
183
     */
184 2216
    public static function setInstance($instance)
185
    {
186 2216
        if ($instance === null) {
187
            unset(Yii::$app->loadedModules[get_called_class()]);
188
        } else {
189 2216
            Yii::$app->loadedModules[get_class($instance)] = $instance;
190
        }
191
    }
192
193
    /**
194
     * Initializes the module.
195
     *
196
     * This method is called after the module is created and initialized with property values
197
     * given in configuration. The default implementation will initialize [[controllerNamespace]]
198
     * if it is not set.
199
     *
200
     * If you override this method, please make sure you call the parent implementation.
201
     */
202 106
    public function init()
203
    {
204 106
        if ($this->controllerNamespace === null) {
205 106
            $class = get_class($this);
206 106
            if (($pos = strrpos($class, '\\')) !== false) {
207 22
                $this->controllerNamespace = substr($class, 0, $pos) . '\\controllers';
208
            }
209
        }
210
    }
211
212
    /**
213
     * Returns an ID that uniquely identifies this module among all modules within the current application.
214
     * Note that if the module is an application, an empty string will be returned.
215
     * @return string the unique ID of the module.
216
     */
217 65
    public function getUniqueId()
218
    {
219 65
        return $this->module ? ltrim($this->module->getUniqueId() . '/' . $this->id, '/') : $this->id;
220
    }
221
222
    /**
223
     * Returns the root directory of the module.
224
     * It defaults to the directory containing the module class file.
225
     * @return string the root directory of the module.
226
     */
227 2216
    public function getBasePath()
228
    {
229 2216
        if ($this->_basePath === null) {
230
            $class = new \ReflectionClass($this);
231
            $this->_basePath = dirname($class->getFileName());
232
        }
233
234 2216
        return $this->_basePath;
235
    }
236
237
    /**
238
     * Sets the root directory of the module.
239
     * This method can only be invoked at the beginning of the constructor.
240
     * @param string $path the root directory of the module. This can be either a directory name or a [path alias](guide:concept-aliases).
241
     * @throws InvalidArgumentException if the directory does not exist.
242
     */
243 2216
    public function setBasePath($path)
244
    {
245 2216
        $path = Yii::getAlias($path);
246 2216
        $p = strncmp($path, 'phar://', 7) === 0 ? $path : realpath($path);
0 ignored issues
show
Bug introduced by
It seems like $path can also be of type false; however, parameter $string1 of strncmp() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

246
        $p = strncmp(/** @scrutinizer ignore-type */ $path, 'phar://', 7) === 0 ? $path : realpath($path);
Loading history...
Bug introduced by
It seems like $path can also be of type false; however, parameter $path of realpath() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

246
        $p = strncmp($path, 'phar://', 7) === 0 ? $path : realpath(/** @scrutinizer ignore-type */ $path);
Loading history...
247 2216
        if (is_string($p) && is_dir($p)) {
248 2216
            $this->_basePath = $p;
249
        } else {
250
            throw new InvalidArgumentException("The directory does not exist: $path");
251
        }
252
    }
253
254
    /**
255
     * Returns the directory that contains the controller classes according to [[controllerNamespace]].
256
     * Note that in order for this method to return a value, you must define
257
     * an alias for the root namespace of [[controllerNamespace]].
258
     * @return string the directory that contains the controller classes.
259
     * @throws InvalidArgumentException if there is no alias defined for the root namespace of [[controllerNamespace]].
260
     */
261 23
    public function getControllerPath()
262
    {
263 23
        if ($this->_controllerPath === null) {
264 22
            $this->_controllerPath = Yii::getAlias('@' . str_replace('\\', '/', $this->controllerNamespace));
0 ignored issues
show
Documentation Bug introduced by
It seems like Yii::getAlias('@' . str_...->controllerNamespace)) can also be of type false. However, the property $_controllerPath 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...
265
        }
266
267 23
        return $this->_controllerPath;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->_controllerPath could also return false which is incompatible with the documented return type string. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

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

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

774
            /** @scrutinizer ignore-call */ 
775
            $component = $this->module->get($id, $throwException);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
775
        }
776 3
        return $component;
777
    }
778
779
    /**
780
     * {@inheritdoc}
781
     *
782
     * Since version 2.0.13, if a component isn't defined in the module, it will be looked up in the parent module.
783
     * The parent module may be the application.
784
     */
785 2165
    public function has($id, $checkInstance = false)
786
    {
787 2165
        return parent::has($id, $checkInstance) || (isset($this->module) && $this->module->has($id, $checkInstance));
788
    }
789
}
790