Passed
Push — master ( d75500...2e21a8 )
by Alexander
82:53 queued 79:39
created

Controller::bindInjectedParams()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 18
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
eloc 15
nc 5
nop 4
dl 0
loc 18
ccs 15
cts 15
cp 1
crap 7
rs 8.8333
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\base;
9
10
use Yii;
11
use yii\di\Instance;
12
13
/**
14
 * Controller is the base class for classes containing controller logic.
15
 *
16
 * For more details and usage information on Controller, see the [guide article on controllers](guide:structure-controllers).
17
 *
18
 * @property Module[] $modules All ancestor modules that this controller is located within. This property is
19
 * read-only.
20
 * @property string $route The route (module ID, controller ID and action ID) of the current request. This
21
 * property is read-only.
22
 * @property string $uniqueId The controller ID that is prefixed with the module ID (if any). This property is
23
 * read-only.
24
 * @property View|\yii\web\View $view The view object that can be used to render views or view files.
25
 * @property string $viewPath The directory containing the view files for this controller.
26
 *
27
 * @author Qiang Xue <[email protected]>
28
 * @since 2.0
29
 */
30
class Controller extends Component implements ViewContextInterface
31
{
32
    /**
33
     * @event ActionEvent an event raised right before executing a controller action.
34
     * You may set [[ActionEvent::isValid]] to be false to cancel the action execution.
35
     */
36
    const EVENT_BEFORE_ACTION = 'beforeAction';
37
    /**
38
     * @event ActionEvent an event raised right after executing a controller action.
39
     */
40
    const EVENT_AFTER_ACTION = 'afterAction';
41
42
    /**
43
     * @var string the ID of this controller.
44
     */
45
    public $id;
46
    /**
47
     * @var Module the module that this controller belongs to.
48
     */
49
    public $module;
50
    /**
51
     * @var string the ID of the action that is used when the action ID is not specified
52
     * in the request. Defaults to 'index'.
53
     */
54
    public $defaultAction = 'index';
55
    /**
56
     * @var null|string|false the name of the layout to be applied to this controller's views.
57
     * This property mainly affects the behavior of [[render()]].
58
     * Defaults to null, meaning the actual layout value should inherit that from [[module]]'s layout value.
59
     * If false, no layout will be applied.
60
     */
61
    public $layout;
62
    /**
63
     * @var Action the action that is currently being executed. This property will be set
64
     * by [[run()]] when it is called by [[Application]] to run an action.
65
     */
66
    public $action;
67
    /**
68
     * @var Request|array|string The request
69
     * @since 2.0.36
70
     */
71
    public $request = 'request';
72
    /**
73
     * @var Response|array|string
74
     * @since 2.0.36
75
     */
76
    public $response = 'response';
77
78
    /**
79
     * @var View the view object that can be used to render views or view files.
80
     */
81
    private $_view;
82
    /**
83
     * @var string the root directory that contains view files for this controller.
84
     */
85
    private $_viewPath;
86
87
88
    /**
89
     * @param string $id the ID of this controller.
90
     * @param Module $module the module that this controller belongs to.
91
     * @param array $config name-value pairs that will be used to initialize the object properties.
92
     */
93 456
    public function __construct($id, $module, $config = [])
94
    {
95 456
        $this->id = $id;
96 456
        $this->module = $module;
97 456
        parent::__construct($config);
98 456
    }
99
100
    /**
101
     * {@inheritdoc}
102
     * @since 2.0.36
103
     */
104 456
    public function init()
105
    {
106 456
        parent::init();
107 456
        $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

107
        $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...
108 456
        $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

108
        $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...
109 456
    }
110
111
    /**
112
     * Declares external actions for the controller.
113
     *
114
     * This method is meant to be overwritten to declare external actions for the controller.
115
     * It should return an array, with array keys being action IDs, and array values the corresponding
116
     * action class names or action configuration arrays. For example,
117
     *
118
     * ```php
119
     * return [
120
     *     'action1' => 'app\components\Action1',
121
     *     'action2' => [
122
     *         'class' => 'app\components\Action2',
123
     *         'property1' => 'value1',
124
     *         'property2' => 'value2',
125
     *     ],
126
     * ];
127
     * ```
128
     *
129
     * [[\Yii::createObject()]] will be used later to create the requested action
130
     * using the configuration provided here.
131
     */
132 308
    public function actions()
133
    {
134 308
        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 284
    public function runAction($id, $params = [])
147
    {
148 284
        $action = $this->createAction($id);
149 284
        if ($action === null) {
150
            throw new InvalidRouteException('Unable to resolve the request: ' . $this->getUniqueId() . '/' . $id);
151
        }
152
153 284
        Yii::debug('Route to run: ' . $action->getUniqueId(), __METHOD__);
154
155 284
        if (Yii::$app->requestedAction === null) {
156 284
            Yii::$app->requestedAction = $action;
157
        }
158
159 284
        $oldAction = $this->action;
160 284
        $this->action = $action;
161
162 284
        $modules = [];
163 284
        $runAction = true;
164
165
        // call beforeAction on modules
166 284
        foreach ($this->getModules() as $module) {
167 284
            if ($module->beforeAction($action)) {
168 284
                array_unshift($modules, $module);
169
            } else {
170
                $runAction = false;
171 284
                break;
172
            }
173
        }
174
175 284
        $result = null;
176
177 284
        if ($runAction && $this->beforeAction($action)) {
178
            // run the action
179 282
            $result = $action->runWithParams($params);
180
181 276
            $result = $this->afterAction($action, $result);
182
183
            // call afterAction on modules
184 276
            foreach ($modules as $module) {
185
                /* @var $module Module */
186 276
                $result = $module->afterAction($action, $result);
187
            }
188
        }
189
190 276
        if ($oldAction !== null) {
191 5
            $this->action = $oldAction;
192
        }
193
194 276
        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 263
    public function run($route, $params = [])
208
    {
209 263
        $pos = strpos($route, '/');
210 263
        if ($pos === false) {
211 262
            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 317
    public function createAction($id)
242
    {
243 317
        if ($id === '') {
244 3
            $id = $this->defaultAction;
245
        }
246
247 317
        $actionMap = $this->actions();
248 317
        if (isset($actionMap[$id])) {
249 9
            return Yii::createObject($actionMap[$id], [$id, $this]);
250
        }
251
252 308
        if (preg_match('/^(?:[a-z0-9_]+-)*[a-z0-9_]+$/', $id)) {
253 308
            $methodName = 'action' . str_replace(' ', '', ucwords(str_replace('-', ' ', $id)));
254 308
            if (method_exists($this, $methodName)) {
255 307
                $method = new \ReflectionMethod($this, $methodName);
256 307
                if ($method->isPublic() && $method->getName() === $methodName) {
257 307
                    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 284
    public function beforeAction($action)
296
    {
297 284
        $event = new ActionEvent($action);
298 284
        $this->trigger(self::EVENT_BEFORE_ACTION, $event);
299 282
        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 276
    public function afterAction($action, $result)
324
    {
325 276
        $event = new ActionEvent($action);
326 276
        $event->result = $result;
327 276
        $this->trigger(self::EVENT_AFTER_ACTION, $event);
328 276
        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 284
    public function getModules()
338
    {
339 284
        $modules = [$this->module];
340 284
        $module = $this->module;
341 284
        while ($module->module !== null) {
342
            array_unshift($modules, $module->module);
343
            $module = $module->module;
344
        }
345
346 284
        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 317
    public function getUniqueId()
354
    {
355 317
        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 4
    public function getRoute()
363
    {
364 4
        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);
0 ignored issues
show
Bug introduced by
It seems like $layoutFile can also be of type true; however, parameter $viewFile of yii\base\View::renderFile() 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

423
            return $this->getView()->renderFile(/** @scrutinizer ignore-type */ $layoutFile, ['content' => $content], $this);
Loading history...
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 82
    public function renderFile($file, $params = [])
450
    {
451 82
        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 90
    public function getView()
462
    {
463 90
        if ($this->_view === null) {
464 90
            $this->_view = Yii::$app->getView();
465
        }
466
467 90
        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 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...
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
        if (is_string($this->layout)) {
516 2
            $layout = $this->layout;
517 5
        } elseif ($this->layout === null) {
518
            while ($module !== null && $module->layout === null) {
519
                $module = $module->module;
520
            }
521
            if ($module !== null && is_string($module->layout)) {
522
                $layout = $module->layout;
523
            }
524
        }
525
526 7
        if (!isset($layout)) {
527 5
            return false;
528
        }
529
530 2
        if (strncmp($layout, '@', 1) === 0) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $layout does not seem to be defined for all execution paths leading up to this point.
Loading history...
531 1
            $file = Yii::getAlias($layout);
532 1
        } elseif (strncmp($layout, '/', 1) === 0) {
533
            $file = Yii::$app->getLayoutPath() . DIRECTORY_SEPARATOR . substr($layout, 1);
534
        } else {
535 1
            $file = $module->getLayoutPath() . DIRECTORY_SEPARATOR . $layout;
536
        }
537
538 2
        if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
539 1
            return $file;
540
        }
541 1
        $path = $file . '.' . $view->defaultExtension;
542 1
        if ($view->defaultExtension !== 'php' && !is_file($path)) {
543
            $path = $file . '.php';
544
        }
545
546 1
        return $path;
547
    }
548
549
    /**
550
     * Fills parameters based on types and names in action method signature.
551
     * @param \ReflectionType $type The reflected type of the action parameter.
552
     * @param string $name The name of the parameter.
553
     * @param array &$args The array of arguments for the action, this function may append items to it.
554
     * @param array &$requestedParams The array with requested params, this function may write specific keys to it.
555
     * @throws ErrorException when we cannot load a required service.
556
     * @throws \yii\base\InvalidConfigException Thrown when there is an error in the DI configuration.
557
     * @throws \yii\di\NotInstantiableException Thrown when a definition cannot be resolved to a concrete class
558
     * (for example an interface type hint) without a proper definition in the container.
559
     * @since 2.0.36
560
     */
561 10
    final protected function bindInjectedParams(\ReflectionType $type, $name, &$args, &$requestedParams)
562
    {
563
        // Since it is not a builtin type it must be DI injection.
564 10
        $typeName = $type->getName();
565 10
        if (($component = $this->module->get($name, false)) instanceof $typeName) {
566 8
            $args[] = $component;
567 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; 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

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