Issues (915)

framework/base/Module.php (10 issues)

1
<?php
2
3
/**
4
 * @link https://www.yiiframework.com/
5
 * @copyright Copyright (c) 2008 Yii Software LLC
6
 * @license https://www.yiiframework.com/license/
7
 */
8
9
namespace yii\base;
10
11
use Yii;
12
use yii\di\ServiceLocator;
13
14
/**
15
 * Module is the base class for module and application classes.
16
 *
17
 * A module represents a sub-application which contains MVC elements by itself, such as
18
 * models, views, controllers, etc.
19
 *
20
 * A module may consist of [[modules|sub-modules]].
21
 *
22
 * [[components|Components]] may be registered with the module so that they are globally
23
 * accessible within the module.
24
 *
25
 * For more details and usage information on Module, see the [guide article on modules](guide:structure-modules).
26
 *
27
 * @property-write array $aliases List of path aliases to be defined. The array keys are alias names (must
28
 * start with `@`) and the array values are the corresponding paths or aliases. See [[setAliases()]] for an
29
 * example.
30
 * @property string $basePath The root directory of the module.
31
 * @property string $controllerPath The directory that contains the controller classes.
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-read string $uniqueId The unique ID of the module.
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|null the parent module of this module. `null` if this module does not have a parent.
64
     */
65
    public $module;
66
    /**
67
     * @var string|bool|null 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|null 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 the controller classes for this module.
120
     */
121
    private $_controllerPath;
122
    /**
123
     * @var string the root directory that contains view files for this module
124
     */
125
    private $_viewPath;
126
    /**
127
     * @var string the root directory that contains layout view files for this module.
128
     */
129
    private $_layoutPath;
130
    /**
131
     * @var array child modules of this module
132
     */
133
    private $_modules = [];
134
    /**
135
     * @var string|callable|null the version of this module.
136
     * Version can be specified as a PHP callback, which can accept module instance as an argument and should
137
     * return the actual version. For example:
138
     *
139
     * ```php
140
     * function (Module $module) {
141
     *     //return string|int
142
     * }
143
     * ```
144
     *
145
     * If not set, [[defaultVersion()]] will be used to determine actual value.
146
     *
147
     * @since 2.0.11
148
     */
149
    private $_version;
150
151
152
    /**
153
     * Constructor.
154
     * @param string $id the ID of this module.
155
     * @param Module|null $parent the parent module (if any).
156
     * @param array $config name-value pairs that will be used to initialize the object properties.
157
     */
158 229
    public function __construct($id, $parent = null, $config = [])
159
    {
160 229
        $this->id = $id;
161 229
        $this->module = $parent;
162 229
        parent::__construct($config);
163
    }
164
165
    /**
166
     * Returns the currently requested instance of this module class.
167
     * If the module class is not currently requested, `null` will be returned.
168
     * This method is provided so that you access the module instance from anywhere within the module.
169
     * @return static|null the currently requested instance of this module class, or `null` if the module class is not requested.
170
     */
171
    public static function getInstance()
172
    {
173
        $class = get_called_class();
174
        return isset(Yii::$app->loadedModules[$class]) ? Yii::$app->loadedModules[$class] : null;
175
    }
176
177
    /**
178
     * Sets the currently requested instance of this module class.
179
     * @param Module|null $instance the currently requested instance of this module class.
180
     * If it is `null`, the instance of the calling class will be removed, if any.
181
     */
182 4509
    public static function setInstance($instance)
183
    {
184 4509
        if ($instance === null) {
185
            unset(Yii::$app->loadedModules[get_called_class()]);
186
        } else {
187 4509
            Yii::$app->loadedModules[get_class($instance)] = $instance;
188
        }
189
    }
190
191
    /**
192
     * Initializes the module.
193
     *
194
     * This method is called after the module is created and initialized with property values
195
     * given in configuration. The default implementation will initialize [[controllerNamespace]]
196
     * if it is not set.
197
     *
198
     * If you override this method, please make sure you call the parent implementation.
199
     */
200 229
    public function init()
201
    {
202 229
        if ($this->controllerNamespace === null) {
203 229
            $class = get_class($this);
204 229
            if (($pos = strrpos($class, '\\')) !== false) {
205 22
                $this->controllerNamespace = substr($class, 0, $pos) . '\\controllers';
206
            }
207
        }
208
    }
209
210
    /**
211
     * Returns an ID that uniquely identifies this module among all modules within the current application.
212
     * Note that if the module is an application, an empty string will be returned.
213
     * @return string the unique ID of the module.
214
     */
215 188
    public function getUniqueId()
216
    {
217 188
        return $this->module ? ltrim($this->module->getUniqueId() . '/' . $this->id, '/') : $this->id;
218
    }
219
220
    /**
221
     * Returns the root directory of the module.
222
     * It defaults to the directory containing the module class file.
223
     * @return string the root directory of the module.
224
     */
225 4509
    public function getBasePath()
226
    {
227 4509
        if ($this->_basePath === null) {
228
            $class = new \ReflectionClass($this);
229
            $this->_basePath = dirname($class->getFileName());
230
        }
231
232 4509
        return $this->_basePath;
233
    }
234
235
    /**
236
     * Sets the root directory of the module.
237
     * This method can only be invoked at the beginning of the constructor.
238
     * @param string $path the root directory of the module. This can be either a directory name or a [path alias](guide:concept-aliases).
239
     * @throws InvalidArgumentException if the directory does not exist.
240
     */
241 4509
    public function setBasePath($path)
242
    {
243 4509
        $path = Yii::getAlias($path);
244 4509
        $p = strncmp($path, 'phar://', 7) === 0 ? $path : realpath($path);
0 ignored issues
show
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

244
        $p = strncmp($path, 'phar://', 7) === 0 ? $path : realpath(/** @scrutinizer ignore-type */ $path);
Loading history...
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

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

772
            /** @scrutinizer ignore-call */ 
773
            $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...
773
        }
774 3
        return $component;
775
    }
776
777
    /**
778
     * {@inheritdoc}
779
     *
780
     * Since version 2.0.13, if a component isn't defined in the module, it will be looked up in the parent module.
781
     * The parent module may be the application.
782
     */
783 4445
    public function has($id, $checkInstance = false)
784
    {
785 4445
        return parent::has($id, $checkInstance) || (isset($this->module) && $this->module->has($id, $checkInstance));
786
    }
787
}
788