Passed
Push — scrutinizer-migrate-to-new-eng... ( 58afd6 )
by Alexander
18:11
created

Module::getModule()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6.1308

Importance

Changes 0
Metric Value
cc 6
eloc 12
nc 6
nop 2
dl 0
loc 22
ccs 11
cts 13
cp 0.8462
crap 6.1308
rs 9.2222
c 0
b 0
f 0
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 136
    public function __construct($id, $parent = null, $config = [])
155
    {
156 136
        $this->id = $id;
157 136
        $this->module = $parent;
158 136
        parent::__construct($config);
159 136
    }
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 3387
    public static function setInstance($instance)
179
    {
180 3387
        if ($instance === null) {
181
            unset(Yii::$app->loadedModules[get_called_class()]);
182
        } else {
183 3387
            Yii::$app->loadedModules[get_class($instance)] = $instance;
184
        }
185 3387
    }
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 136
    public function init()
197
    {
198 136
        if ($this->controllerNamespace === null) {
199 136
            $class = get_class($this);
200 136
            if (($pos = strrpos($class, '\\')) !== false) {
201 11
                $this->controllerNamespace = substr($class, 0, $pos) . '\\controllers';
202
            }
203
        }
204 136
    }
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 106
    public function getUniqueId()
212
    {
213 106
        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 3387
    public function getBasePath()
222
    {
223 3387
        if ($this->_basePath === null) {
224
            $class = new \ReflectionClass($this);
225
            $this->_basePath = dirname($class->getFileName());
226
        }
227
228 3387
        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 InvalidArgumentException if the directory does not exist.
236
     */
237 3387
    public function setBasePath($path)
238
    {
239 3387
        $path = Yii::getAlias($path);
240 3387
        $p = strncmp($path, 'phar://', 7) === 0 ? $path : realpath($path);
241 3387
        if ($p !== false && is_dir($p)) {
0 ignored issues
show
Bug introduced by
It seems like $p can also be of type true; however, parameter $filename of is_dir() 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

241
        if ($p !== false && is_dir(/** @scrutinizer ignore-type */ $p)) {
Loading history...
242 3387
            $this->_basePath = $p;
0 ignored issues
show
Documentation Bug introduced by
It seems like $p can also be of type true. 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 InvalidArgumentException("The directory does not exist: $path");
245
        }
246 3387
    }
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 InvalidArgumentException if there is no alias defined for the root namespace of [[controllerNamespace]].
254
     */
255 19
    public function getControllerPath()
256
    {
257 19
        return Yii::getAlias('@' . str_replace('\\', '/', $this->controllerNamespace));
0 ignored issues
show
Bug Best Practice introduced by
The expression return Yii::getAlias('@'...->controllerNamespace)) also could return the type boolean which is incompatible with the documented return type string.
Loading history...
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 2
    public function getViewPath()
265
    {
266 2
        if ($this->_viewPath === null) {
267 2
            $this->_viewPath = $this->getBasePath() . DIRECTORY_SEPARATOR . 'views';
268
        }
269
270 2
        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 InvalidArgumentException 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 1
    public function getLayoutPath()
288
    {
289 1
        if ($this->_layoutPath === null) {
290 1
            $this->_layoutPath = $this->getViewPath() . DIRECTORY_SEPARATOR . 'layouts';
291
        }
292
293 1
        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 InvalidArgumentException 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 300
    public function setAliases($aliases)
378
    {
379 300
        foreach ($aliases as $name => $alias) {
380 300
            Yii::setAlias($name, $alias);
381
        }
382 300
    }
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 3
    public function getModule($id, $load = true)
413
    {
414 3
        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 3
        if (isset($this->_modules[$id])) {
422 3
            if ($this->_modules[$id] instanceof self) {
423 2
                return $this->_modules[$id];
424 2
            } elseif ($load) {
425 2
                Yii::debug("Loading module: $id", __METHOD__);
426
                /* @var $module Module */
427 2
                $module = Yii::createObject($this->_modules[$id], [$id, $this]);
428 2
                $module->setInstance($module);
429 2
                return $this->_modules[$id] = $module;
430
            }
431
        }
432
433 2
        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 1
    public function setModule($id, $module)
448
    {
449 1
        if ($module === null) {
450
            unset($this->_modules[$id]);
451
        } else {
452 1
            $this->_modules[$id] = $module;
453
        }
454 1
    }
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 18
    public function getModules($loadedOnly = false)
464
    {
465 18
        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 18
        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 2
    public function setModules($modules)
504
    {
505 2
        foreach ($modules as $id => $module) {
506 2
            $this->_modules[$id] = $module;
507
        }
508 2
    }
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;
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...
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 95
    public function createController($route)
563
    {
564 95
        if ($route === '') {
565 1
            $route = $this->defaultRoute;
566
        }
567
568
        // double slashes or leading/ending slashes may cause substr problem
569 95
        $route = trim($route, '/');
570 95
        if (strpos($route, '//') !== false) {
571
            return false;
572
        }
573
574 95
        if (strpos($route, '/') !== false) {
575 14
            list($id, $route) = explode('/', $route, 2);
576
        } else {
577 84
            $id = $route;
578 84
            $route = '';
579
        }
580
581
        // module and controller map take precedence
582 95
        if (isset($this->controllerMap[$id])) {
583 95
            $controller = Yii::createObject($this->controllerMap[$id], [$id, $this]);
584 95
            return [$controller, $route];
585
        }
586 2
        $module = $this->getModule($id);
587 2
        if ($module !== null) {
588 2
            return $module->createController($route);
589
        }
590
591 2
        if (($pos = strrpos($route, '/')) !== false) {
592 1
            $id .= '/' . substr($route, 0, $pos);
593 1
            $route = substr($route, $pos + 1);
594
        }
595
596 2
        $controller = $this->createControllerByID($id);
597 2
        if ($controller === null && $route !== '') {
598 2
            $controller = $this->createControllerByID($id . '/' . $route);
599 2
            $route = '';
600
        }
601
602 2
        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 3
    public function createControllerByID($id)
619
    {
620 3
        $pos = strrpos($id, '/');
621 3
        if ($pos === false) {
622 3
            $prefix = '';
623 3
            $className = $id;
624
        } else {
625 2
            $prefix = substr($id, 0, $pos + 1);
626 2
            $className = substr($id, $pos + 1);
627
        }
628
629 3
        if ($this->isIncorrectClassNameOrPrefix($className, $prefix)) {
630 2
            return null;
631
        }
632
633 3
        $className = preg_replace_callback('%-([a-z0-9_])%i', function ($matches) {
634 2
                return ucfirst($matches[1]);
635 3
            }, ucfirst($className)) . 'Controller';
636 3
        $className = ltrim($this->controllerNamespace . '\\' . str_replace('/', '\\', $prefix) . $className, '\\');
637 3
        if (strpos($className, '-') !== false || !class_exists($className)) {
638 2
            return null;
639
        }
640
641 2
        if (is_subclass_of($className, 'yii\base\Controller')) {
642 2
            $controller = Yii::createObject($className, [$id, $this]);
643 2
            return get_class($controller) === $className ? $controller : null;
644
        } elseif (YII_DEBUG) {
645
            throw new InvalidConfigException('Controller class must extend from \\yii\\base\\Controller.');
646
        }
647
648
        return null;
649
    }
650
651
    /**
652
     * Checks if class name or prefix is incorrect
653
     *
654
     * @param string $className
655
     * @param string $prefix
656
     * @return bool
657
     */
658 3
    private function isIncorrectClassNameOrPrefix($className, $prefix)
659
    {
660 3
        if (!preg_match('%^[a-z][a-z0-9\\-_]*$%', $className)) {
661 2
            return true;
662
        }
663 3
        if ($prefix !== '' && !preg_match('%^[a-z0-9_/]+$%i', $prefix)) {
664
            return true;
665
        }
666
667 3
        return false;
668
    }
669
670
    /**
671
     * This method is invoked right before an action within this module is executed.
672
     *
673
     * The method will trigger the [[EVENT_BEFORE_ACTION]] event. The return value of the method
674
     * will determine whether the action should continue to run.
675
     *
676
     * In case the action should not run, the request should be handled inside of the `beforeAction` code
677
     * by either providing the necessary output or redirecting the request. Otherwise the response will be empty.
678
     *
679
     * If you override this method, your code should look like the following:
680
     *
681
     * ```php
682
     * public function beforeAction($action)
683
     * {
684
     *     if (!parent::beforeAction($action)) {
685
     *         return false;
686
     *     }
687
     *
688
     *     // your custom code here
689
     *
690
     *     return true; // or false to not run the action
691
     * }
692
     * ```
693
     *
694
     * @param Action $action the action to be executed.
695
     * @return bool whether the action should continue to be executed.
696
     */
697 203
    public function beforeAction($action)
698
    {
699 203
        $event = new ActionEvent($action);
700 203
        $this->trigger(self::EVENT_BEFORE_ACTION, $event);
701 203
        return $event->isValid;
702
    }
703
704
    /**
705
     * This method is invoked right after an action within this module is executed.
706
     *
707
     * The method will trigger the [[EVENT_AFTER_ACTION]] event. The return value of the method
708
     * will be used as the action return value.
709
     *
710
     * If you override this method, your code should look like the following:
711
     *
712
     * ```php
713
     * public function afterAction($action, $result)
714
     * {
715
     *     $result = parent::afterAction($action, $result);
716
     *     // your custom code here
717
     *     return $result;
718
     * }
719
     * ```
720
     *
721
     * @param Action $action the action just executed.
722
     * @param mixed $result the action return result.
723
     * @return mixed the processed action result.
724
     */
725 195
    public function afterAction($action, $result)
726
    {
727 195
        $event = new ActionEvent($action);
728 195
        $event->result = $result;
729 195
        $this->trigger(self::EVENT_AFTER_ACTION, $event);
730 195
        return $event->result;
731
    }
732
733
    /**
734
     * {@inheritdoc}
735
     *
736
     * Since version 2.0.13, if a component isn't defined in the module, it will be looked up in the parent module.
737
     * The parent module may be the application.
738
     */
739 1109
    public function get($id, $throwException = true)
740
    {
741 1109
        if (!isset($this->module)) {
742 1109
            return parent::get($id, $throwException);
743
        }
744
745 1
        $component = parent::get($id, false);
746 1
        if ($component === null) {
747 1
            $component = $this->module->get($id, $throwException);
748
        }
749 1
        return $component;
750
    }
751
752
    /**
753
     * {@inheritdoc}
754
     *
755
     * Since version 2.0.13, if a component isn't defined in the module, it will be looked up in the parent module.
756
     * The parent module may be the application.
757
     */
758 3220
    public function has($id, $checkInstance = false)
759
    {
760 3220
        return parent::has($id, $checkInstance) || (isset($this->module) && $this->module->has($id, $checkInstance));
761
    }
762
}
763