Completed
Push — master ( 155575...f6b9aa )
by Dmitry
31:24 queued 13:49
created

Module::setViewPath()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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

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

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

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

class Id
{
    public $id;

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

}

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

$account_id = false;

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

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

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

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

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

class Id
{
    public $id;

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

}

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

$account_id = false;

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

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

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

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

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

class Id
{
    public $id;

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

}

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

$account_id = false;

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

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