Issues (836)

framework/base/Controller.php (5 issues)

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

541
            $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...
542
        }
543
544 2
        if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
0 ignored issues
show
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

544
        if (pathinfo(/** @scrutinizer ignore-type */ $file, PATHINFO_EXTENSION) !== '') {
Loading history...
545 1
            return $file;
546
        }
547 1
        $path = $file . '.' . $view->defaultExtension;
0 ignored issues
show
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

547
        $path = /** @scrutinizer ignore-type */ $file . '.' . $view->defaultExtension;
Loading history...
548 1
        if ($view->defaultExtension !== 'php' && !is_file($path)) {
549
            $path = $file . '.php';
550
        }
551
552 1
        return $path;
553
    }
554
555
    /**
556
     * Fills parameters based on types and names in action method signature.
557
     * @param \ReflectionNamedType $type The reflected type of the action parameter.
558
     * @param string $name The name of the parameter.
559
     * @param array &$args The array of arguments for the action, this function may append items to it.
560
     * @param array &$requestedParams The array with requested params, this function may write specific keys to it.
561
     * @throws ErrorException when we cannot load a required service.
562
     * @throws InvalidConfigException Thrown when there is an error in the DI configuration.
563
     * @throws NotInstantiableException Thrown when a definition cannot be resolved to a concrete class
564
     * (for example an interface type hint) without a proper definition in the container.
565
     * @since 2.0.36
566
     */
567 11
    final protected function bindInjectedParams(\ReflectionNamedType $type, $name, &$args, &$requestedParams)
568
    {
569
        // Since it is not a builtin type it must be DI injection.
570 11
        $typeName = $type->getName();
571 11
        if (($component = $this->module->get($name, false)) instanceof $typeName) {
572 8
            $args[] = $component;
573 8
            $requestedParams[$name] = 'Component: ' . get_class($component) . " \$$name";
0 ignored issues
show
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

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