Controller   F
last analyzed

Complexity

Total Complexity 62

Size/Duplication

Total Lines 551
Duplicated Lines 0 %

Test Coverage

Coverage 87.05%

Importance

Changes 0
Metric Value
eloc 132
dl 0
loc 551
ccs 121
cts 139
cp 0.8705
rs 3.44
c 0
b 0
f 0
wmc 62

22 Methods

Rating   Name   Duplication   Size   Complexity  
A bindActionParams() 0 3 1
A actions() 0 3 1
A getViewPath() 0 7 2
A run() 0 10 3
A getRoute() 0 3 2
A setViewPath() 0 3 1
A render() 0 4 1
A getUniqueId() 0 3 2
A afterAction() 0 6 1
A getModules() 0 10 2
A beforeAction() 0 5 1
A renderFile() 0 3 1
A renderPartial() 0 3 1
A setView() 0 3 1
A renderContent() 0 8 2
A getView() 0 7 2
B createAction() 0 22 7
B bindInjectedParams() 0 18 7
A init() 0 5 1
B runAction() 0 49 9
A __construct() 0 5 1
C findLayoutFile() 0 36 13

How to fix   Complexity   

Complex Class

Complex classes like Controller often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

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

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

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\Instance;
13
use yii\di\NotInstantiableException;
14
15
/**
16
 * Controller is the base class for classes containing controller logic.
17
 *
18
 * For more details and usage information on Controller, see the [guide article on controllers](guide:structure-controllers).
19
 *
20
 * @property-read Module[] $modules All ancestor modules that this controller is located within.
21
 * @property-read string $route The route (module ID, controller ID and action ID) of the current request.
22
 * @property-read string $uniqueId The controller ID that is prefixed with the module ID (if any).
23
 * @property View|\yii\web\View $view The view object that can be used to render views or view files.
24
 * @property string $viewPath The directory containing the view files for this controller.
25
 *
26
 * @author Qiang Xue <[email protected]>
27
 * @since 2.0
28
 */
29
class Controller extends Component implements ViewContextInterface
30
{
31
    /**
32
     * @event ActionEvent an event raised right before executing a controller action.
33
     * You may set [[ActionEvent::isValid]] to be false to cancel the action execution.
34
     */
35
    const EVENT_BEFORE_ACTION = 'beforeAction';
36
    /**
37
     * @event ActionEvent an event raised right after executing a controller action.
38
     */
39
    const EVENT_AFTER_ACTION = 'afterAction';
40
41
    /**
42
     * @var string the ID of this controller.
43
     */
44
    public $id;
45
    /**
46
     * @var Module the module that this controller belongs to.
47
     */
48
    public $module;
49
    /**
50
     * @var string the ID of the action that is used when the action ID is not specified
51
     * in the request. Defaults to 'index'.
52
     */
53
    public $defaultAction = 'index';
54
    /**
55
     * @var string|null|false the name of the layout to be applied to this controller's views.
56
     * This property mainly affects the behavior of [[render()]].
57
     * Defaults to null, meaning the actual layout value should inherit that from [[module]]'s layout value.
58
     * If false, no layout will be applied.
59
     */
60
    public $layout;
61
    /**
62
     * @var Action|null the action that is currently being executed. This property will be set
63
     * by [[run()]] when it is called by [[Application]] to run an action.
64
     */
65
    public $action;
66
    /**
67
     * @var Request|array|string The request.
68
     * @since 2.0.36
69
     */
70
    public $request = 'request';
71
    /**
72
     * @var Response|array|string The response.
73
     * @since 2.0.36
74
     */
75
    public $response = 'response';
76
77
    /**
78
     * @var View|null the view object that can be used to render views or view files.
79
     */
80
    private $_view;
81
    /**
82
     * @var string|null the root directory that contains view files for this controller.
83
     */
84
    private $_viewPath;
85
86
87
    /**
88
     * @param string $id the ID of this controller.
89
     * @param Module $module the module that this controller belongs to.
90
     * @param array $config name-value pairs that will be used to initialize the object properties.
91
     */
92 493
    public function __construct($id, $module, $config = [])
93
    {
94 493
        $this->id = $id;
95 493
        $this->module = $module;
96 493
        parent::__construct($config);
97
    }
98
99
    /**
100
     * {@inheritdoc}
101
     * @since 2.0.36
102
     */
103 493
    public function init()
104
    {
105 493
        parent::init();
106 493
        $this->request = Instance::ensure($this->request, Request::className());
0 ignored issues
show
Deprecated Code introduced by
The function yii\base\BaseObject::className() has been deprecated: since 2.0.14. On PHP >=5.5, use `::class` instead. ( Ignorable by Annotation )

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

106
        $this->request = Instance::ensure($this->request, /** @scrutinizer ignore-deprecated */ Request::className());

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
107 493
        $this->response = Instance::ensure($this->response, Response::className());
0 ignored issues
show
Deprecated Code introduced by
The function yii\base\BaseObject::className() has been deprecated: since 2.0.14. On PHP >=5.5, use `::class` instead. ( Ignorable by Annotation )

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

107
        $this->response = Instance::ensure($this->response, /** @scrutinizer ignore-deprecated */ Response::className());

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
108
    }
109
110
    /**
111
     * Declares external actions for the controller.
112
     *
113
     * This method is meant to be overwritten to declare external actions for the controller.
114
     * It should return an array, with array keys being action IDs, and array values the corresponding
115
     * action class names or action configuration arrays. For example,
116
     *
117
     * ```php
118
     * return [
119
     *     'action1' => 'app\components\Action1',
120
     *     'action2' => [
121
     *         'class' => 'app\components\Action2',
122
     *         'property1' => 'value1',
123
     *         'property2' => 'value2',
124
     *     ],
125
     * ];
126
     * ```
127
     *
128
     * [[\Yii::createObject()]] will be used later to create the requested action
129
     * using the configuration provided here.
130
     * @return array
131
     */
132 331
    public function actions()
133
    {
134 331
        return [];
135
    }
136
137
    /**
138
     * Runs an action within this controller with the specified action ID and parameters.
139
     * If the action ID is empty, the method will use [[defaultAction]].
140
     * @param string $id the ID of the action to be executed.
141
     * @param array $params the parameters (name-value pairs) to be passed to the action.
142
     * @return mixed the result of the action.
143
     * @throws InvalidRouteException if the requested action ID cannot be resolved into an action successfully.
144
     * @see createAction()
145
     */
146 308
    public function runAction($id, $params = [])
147
    {
148 308
        $action = $this->createAction($id);
149 308
        if ($action === null) {
150
            throw new InvalidRouteException('Unable to resolve the request: ' . $this->getUniqueId() . '/' . $id);
151
        }
152
153 308
        Yii::debug('Route to run: ' . $action->getUniqueId(), __METHOD__);
154
155 308
        if (Yii::$app->requestedAction === null) {
156 308
            Yii::$app->requestedAction = $action;
157
        }
158
159 308
        $oldAction = $this->action;
160 308
        $this->action = $action;
161
162 308
        $modules = [];
163 308
        $runAction = true;
164
165
        // call beforeAction on modules
166 308
        foreach ($this->getModules() as $module) {
167 308
            if ($module->beforeAction($action)) {
168 308
                array_unshift($modules, $module);
169
            } else {
170
                $runAction = false;
171
                break;
172
            }
173
        }
174
175 308
        $result = null;
176
177 308
        if ($runAction && $this->beforeAction($action)) {
178
            // run the action
179 302
            $result = $action->runWithParams($params);
180
181 296
            $result = $this->afterAction($action, $result);
182
183
            // call afterAction on modules
184 296
            foreach ($modules as $module) {
185
                /* @var $module Module */
186 296
                $result = $module->afterAction($action, $result);
187
            }
188
        }
189
190 296
        if ($oldAction !== null) {
191 7
            $this->action = $oldAction;
192
        }
193
194 296
        return $result;
195
    }
196
197
    /**
198
     * Runs a request specified in terms of a route.
199
     * The route can be either an ID of an action within this controller or a complete route consisting
200
     * of module IDs, controller ID and action ID. If the route starts with a slash '/', the parsing of
201
     * the route will start from the application; otherwise, it will start from the parent module of this controller.
202
     * @param string $route the route to be handled, e.g., 'view', 'comment/view', '/admin/comment/view'.
203
     * @param array $params the parameters to be passed to the action.
204
     * @return mixed the result of the action.
205
     * @see runAction()
206
     */
207 286
    public function run($route, $params = [])
208
    {
209 286
        $pos = strpos($route, '/');
210 286
        if ($pos === false) {
211 285
            return $this->runAction($route, $params);
212 1
        } elseif ($pos > 0) {
213 1
            return $this->module->runAction($route, $params);
214
        }
215
216
        return Yii::$app->runAction(ltrim($route, '/'), $params);
217
    }
218
219
    /**
220
     * Binds the parameters to the action.
221
     * This method is invoked by [[Action]] when it begins to run with the given parameters.
222
     * @param Action $action the action to be bound with parameters.
223
     * @param array $params the parameters to be bound to the action.
224
     * @return array the valid parameters that the action can run with.
225
     */
226 3
    public function bindActionParams($action, $params)
227
    {
228 3
        return [];
229
    }
230
231
    /**
232
     * Creates an action based on the given action ID.
233
     * The method first checks if the action ID has been declared in [[actions()]]. If so,
234
     * it will use the configuration declared there to create the action object.
235
     * If not, it will look for a controller method whose name is in the format of `actionXyz`
236
     * where `xyz` is the action ID. If found, an [[InlineAction]] representing that
237
     * method will be created and returned.
238
     * @param string $id the action ID.
239
     * @return Action|null the newly created action instance. Null if the ID doesn't resolve into any action.
240
     */
241 346
    public function createAction($id)
242
    {
243 346
        if ($id === '') {
244 3
            $id = $this->defaultAction;
245
        }
246
247 346
        $actionMap = $this->actions();
248 346
        if (isset($actionMap[$id])) {
249 15
            return Yii::createObject($actionMap[$id], [$id, $this]);
250
        }
251
252 331
        if (preg_match('/^(?:[a-z0-9_]+-)*[a-z0-9_]+$/', $id)) {
253 331
            $methodName = 'action' . str_replace(' ', '', ucwords(str_replace('-', ' ', $id)));
254 331
            if (method_exists($this, $methodName)) {
255 330
                $method = new \ReflectionMethod($this, $methodName);
256 330
                if ($method->isPublic() && $method->getName() === $methodName) {
257 330
                    return new InlineAction($id, $this, $methodName);
258
                }
259
            }
260
        }
261
262 19
        return null;
263
    }
264
265
    /**
266
     * This method is invoked right before an action is executed.
267
     *
268
     * The method will trigger the [[EVENT_BEFORE_ACTION]] event. The return value of the method
269
     * will determine whether the action should continue to run.
270
     *
271
     * In case the action should not run, the request should be handled inside of the `beforeAction` code
272
     * by either providing the necessary output or redirecting the request. Otherwise the response will be empty.
273
     *
274
     * If you override this method, your code should look like the following:
275
     *
276
     * ```php
277
     * public function beforeAction($action)
278
     * {
279
     *     // your custom code here, if you want the code to run before action filters,
280
     *     // which are triggered on the [[EVENT_BEFORE_ACTION]] event, e.g. PageCache or AccessControl
281
     *
282
     *     if (!parent::beforeAction($action)) {
283
     *         return false;
284
     *     }
285
     *
286
     *     // other custom code here
287
     *
288
     *     return true; // or false to not run the action
289
     * }
290
     * ```
291
     *
292
     * @param Action $action the action to be executed.
293
     * @return bool whether the action should continue to run.
294
     */
295 308
    public function beforeAction($action)
296
    {
297 308
        $event = new ActionEvent($action);
298 308
        $this->trigger(self::EVENT_BEFORE_ACTION, $event);
299 302
        return $event->isValid;
300
    }
301
302
    /**
303
     * This method is invoked right after an action is executed.
304
     *
305
     * The method will trigger the [[EVENT_AFTER_ACTION]] event. The return value of the method
306
     * will be used as the action return value.
307
     *
308
     * If you override this method, your code should look like the following:
309
     *
310
     * ```php
311
     * public function afterAction($action, $result)
312
     * {
313
     *     $result = parent::afterAction($action, $result);
314
     *     // your custom code here
315
     *     return $result;
316
     * }
317
     * ```
318
     *
319
     * @param Action $action the action just executed.
320
     * @param mixed $result the action return result.
321
     * @return mixed the processed action result.
322
     */
323 296
    public function afterAction($action, $result)
324
    {
325 296
        $event = new ActionEvent($action);
326 296
        $event->result = $result;
327 296
        $this->trigger(self::EVENT_AFTER_ACTION, $event);
328 296
        return $event->result;
329
    }
330
331
    /**
332
     * Returns all ancestor modules of this controller.
333
     * The first module in the array is the outermost one (i.e., the application instance),
334
     * while the last is the innermost one.
335
     * @return Module[] all ancestor modules that this controller is located within.
336
     */
337 308
    public function getModules()
338
    {
339 308
        $modules = [$this->module];
340 308
        $module = $this->module;
341 308
        while ($module->module !== null) {
342
            array_unshift($modules, $module->module);
343
            $module = $module->module;
344
        }
345
346 308
        return $modules;
347
    }
348
349
    /**
350
     * Returns the unique ID of the controller.
351
     * @return string the controller ID that is prefixed with the module ID (if any).
352
     */
353 341
    public function getUniqueId()
354
    {
355 341
        return $this->module instanceof Application ? $this->id : $this->module->getUniqueId() . '/' . $this->id;
356
    }
357
358
    /**
359
     * Returns the route of the current request.
360
     * @return string the route (module ID, controller ID and action ID) of the current request.
361
     */
362 5
    public function getRoute()
363
    {
364 5
        return $this->action !== null ? $this->action->getUniqueId() : $this->getUniqueId();
365
    }
366
367
    /**
368
     * Renders a view and applies layout if available.
369
     *
370
     * The view to be rendered can be specified in one of the following formats:
371
     *
372
     * - [path alias](guide:concept-aliases) (e.g. "@app/views/site/index");
373
     * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes.
374
     *   The actual view file will be looked for under the [[Application::viewPath|view path]] of the application.
375
     * - absolute path within module (e.g. "/site/index"): the view name starts with a single slash.
376
     *   The actual view file will be looked for under the [[Module::viewPath|view path]] of [[module]].
377
     * - relative path (e.g. "index"): the actual view file will be looked for under [[viewPath]].
378
     *
379
     * To determine which layout should be applied, the following two steps are conducted:
380
     *
381
     * 1. In the first step, it determines the layout name and the context module:
382
     *
383
     * - If [[layout]] is specified as a string, use it as the layout name and [[module]] as the context module;
384
     * - If [[layout]] is null, search through all ancestor modules of this controller and find the first
385
     *   module whose [[Module::layout|layout]] is not null. The layout and the corresponding module
386
     *   are used as the layout name and the context module, respectively. If such a module is not found
387
     *   or the corresponding layout is not a string, it will return false, meaning no applicable layout.
388
     *
389
     * 2. In the second step, it determines the actual layout file according to the previously found layout name
390
     *    and context module. The layout name can be:
391
     *
392
     * - a [path alias](guide:concept-aliases) (e.g. "@app/views/layouts/main");
393
     * - an absolute path (e.g. "/main"): the layout name starts with a slash. The actual layout file will be
394
     *   looked for under the [[Application::layoutPath|layout path]] of the application;
395
     * - a relative path (e.g. "main"): the actual layout file will be looked for under the
396
     *   [[Module::layoutPath|layout path]] of the context module.
397
     *
398
     * If the layout name does not contain a file extension, it will use the default one `.php`.
399
     *
400
     * @param string $view the view name.
401
     * @param array $params the parameters (name-value pairs) that should be made available in the view.
402
     * These parameters will not be available in the layout.
403
     * @return string the rendering result.
404
     * @throws InvalidArgumentException if the view file or the layout file does not exist.
405
     */
406 8
    public function render($view, $params = [])
407
    {
408 8
        $content = $this->getView()->render($view, $params, $this);
409 7
        return $this->renderContent($content);
410
    }
411
412
    /**
413
     * Renders a static string by applying a layout.
414
     * @param string $content the static string being rendered
415
     * @return string the rendering result of the layout with the given static string as the `$content` variable.
416
     * If the layout is disabled, the string will be returned back.
417
     * @since 2.0.1
418
     */
419 7
    public function renderContent($content)
420
    {
421 7
        $layoutFile = $this->findLayoutFile($this->getView());
422 7
        if ($layoutFile !== false) {
423 2
            return $this->getView()->renderFile($layoutFile, ['content' => $content], $this);
424
        }
425
426 5
        return $content;
427
    }
428
429
    /**
430
     * Renders a view without applying layout.
431
     * This method differs from [[render()]] in that it does not apply any layout.
432
     * @param string $view the view name. Please refer to [[render()]] on how to specify a view name.
433
     * @param array $params the parameters (name-value pairs) that should be made available in the view.
434
     * @return string the rendering result.
435
     * @throws InvalidArgumentException if the view file does not exist.
436
     */
437
    public function renderPartial($view, $params = [])
438
    {
439
        return $this->getView()->render($view, $params, $this);
440
    }
441
442
    /**
443
     * Renders a view file.
444
     * @param string $file the view file to be rendered. This can be either a file path or a [path alias](guide:concept-aliases).
445
     * @param array $params the parameters (name-value pairs) that should be made available in the view.
446
     * @return string the rendering result.
447
     * @throws InvalidArgumentException if the view file does not exist.
448
     */
449 84
    public function renderFile($file, $params = [])
450
    {
451 84
        return $this->getView()->renderFile($file, $params, $this);
452
    }
453
454
    /**
455
     * Returns the view object that can be used to render views or view files.
456
     * The [[render()]], [[renderPartial()]] and [[renderFile()]] methods will use
457
     * this view object to implement the actual view rendering.
458
     * If not set, it will default to the "view" application component.
459
     * @return View|\yii\web\View the view object that can be used to render views or view files.
460
     */
461 92
    public function getView()
462
    {
463 92
        if ($this->_view === null) {
464 92
            $this->_view = Yii::$app->getView();
465
        }
466
467 92
        return $this->_view;
468
    }
469
470
    /**
471
     * Sets the view object to be used by this controller.
472
     * @param View|\yii\web\View $view the view object that can be used to render views or view files.
473
     */
474
    public function setView($view)
475
    {
476
        $this->_view = $view;
477
    }
478
479
    /**
480
     * Returns the directory containing view files for this controller.
481
     * The default implementation returns the directory named as controller [[id]] under the [[module]]'s
482
     * [[viewPath]] directory.
483
     * @return string the directory containing the view files for this controller.
484
     */
485 1
    public function getViewPath()
486
    {
487 1
        if ($this->_viewPath === null) {
488 1
            $this->_viewPath = $this->module->getViewPath() . DIRECTORY_SEPARATOR . $this->id;
489
        }
490
491 1
        return $this->_viewPath;
492
    }
493
494
    /**
495
     * Sets the directory that contains the view files.
496
     * @param string $path the root directory of view files.
497
     * @throws InvalidArgumentException if the directory is invalid
498
     * @since 2.0.7
499
     */
500
    public function setViewPath($path)
501
    {
502
        $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 null|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...
503
    }
504
505
    /**
506
     * Finds the applicable layout file.
507
     * @param View $view the view object to render the layout file.
508
     * @return string|bool the layout file path, or false if layout is not needed.
509
     * Please refer to [[render()]] on how to specify this parameter.
510
     * @throws InvalidArgumentException if an invalid path alias is used to specify the layout.
511
     */
512 7
    public function findLayoutFile($view)
513
    {
514 7
        $module = $this->module;
515 7
        $layout = null;
516 7
        if (is_string($this->layout)) {
517 2
            $layout = $this->layout;
518 5
        } elseif ($this->layout === null) {
519
            while ($module !== null && $module->layout === null) {
520
                $module = $module->module;
521
            }
522
            if ($module !== null && is_string($module->layout)) {
523
                $layout = $module->layout;
524
            }
525
        }
526
527 7
        if ($layout === null) {
528 5
            return false;
529
        }
530
531 2
        if (strncmp($layout, '@', 1) === 0) {
532 1
            $file = Yii::getAlias($layout);
533 1
        } elseif (strncmp($layout, '/', 1) === 0) {
534
            $file = Yii::$app->getLayoutPath() . DIRECTORY_SEPARATOR . substr($layout, 1);
535
        } else {
536 1
            $file = $module->getLayoutPath() . DIRECTORY_SEPARATOR . $layout;
0 ignored issues
show
Bug introduced by
The method getLayoutPath() 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

536
            $file = $module->/** @scrutinizer ignore-call */ getLayoutPath() . DIRECTORY_SEPARATOR . $layout;

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...
537
        }
538
539 2
        if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
0 ignored issues
show
Bug introduced by
It seems like $file can also be of type false; however, parameter $path of pathinfo() 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

539
        if (pathinfo(/** @scrutinizer ignore-type */ $file, PATHINFO_EXTENSION) !== '') {
Loading history...
540 1
            return $file;
541
        }
542 1
        $path = $file . '.' . $view->defaultExtension;
0 ignored issues
show
Bug introduced by
Are you sure $file of type false|string can be used in concatenation? ( Ignorable by Annotation )

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

542
        $path = /** @scrutinizer ignore-type */ $file . '.' . $view->defaultExtension;
Loading history...
543 1
        if ($view->defaultExtension !== 'php' && !is_file($path)) {
544
            $path = $file . '.php';
545
        }
546
547 1
        return $path;
548
    }
549
550
    /**
551
     * Fills parameters based on types and names in action method signature.
552
     * @param \ReflectionType $type The reflected type of the action parameter.
553
     * @param string $name The name of the parameter.
554
     * @param array &$args The array of arguments for the action, this function may append items to it.
555
     * @param array &$requestedParams The array with requested params, this function may write specific keys to it.
556
     * @throws ErrorException when we cannot load a required service.
557
     * @throws InvalidConfigException Thrown when there is an error in the DI configuration.
558
     * @throws NotInstantiableException Thrown when a definition cannot be resolved to a concrete class
559
     * (for example an interface type hint) without a proper definition in the container.
560
     * @since 2.0.36
561
     */
562 11
    final protected function bindInjectedParams(\ReflectionType $type, $name, &$args, &$requestedParams)
563
    {
564
        // Since it is not a builtin type it must be DI injection.
565 11
        $typeName = $type->getName();
0 ignored issues
show
Bug introduced by
The method getName() does not exist on ReflectionType. It seems like you code against a sub-type of ReflectionType such as ReflectionNamedType. ( Ignorable by Annotation )

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

565
        /** @scrutinizer ignore-call */ 
566
        $typeName = $type->getName();
Loading history...
566 11
        if (($component = $this->module->get($name, false)) instanceof $typeName) {
567 8
            $args[] = $component;
568 8
            $requestedParams[$name] = 'Component: ' . get_class($component) . " \$$name";
0 ignored issues
show
Bug introduced by
It seems like $component can also be of type mixed and null; however, parameter $object of get_class() does only seem to accept object, 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

568
            $requestedParams[$name] = 'Component: ' . get_class(/** @scrutinizer ignore-type */ $component) . " \$$name";
Loading history...
569 11
        } elseif ($this->module->has($typeName) && ($service = $this->module->get($typeName)) instanceof $typeName) {
570 2
            $args[] = $service;
571 2
            $requestedParams[$name] = 'Module ' . get_class($this->module) . " DI: $typeName \$$name";
572 9
        } elseif (\Yii::$container->has($typeName) && ($service = \Yii::$container->get($typeName)) instanceof $typeName) {
573 2
            $args[] = $service;
574 2
            $requestedParams[$name] = "Container DI: $typeName \$$name";
575 6
        } elseif ($type->allowsNull()) {
576 4
            $args[] = null;
577 4
            $requestedParams[$name] = "Unavailable service: $name";
578
        } else {
579 2
            throw new Exception('Could not load required service: ' . $name);
580
        }
581
    }
582
}
583