Completed
Push — after-request-controller-actio... ( 242fe7 )
by Carsten
13:53 queued 07:04
created

Controller   C

Complexity

Total Complexity 56

Size/Duplication

Total Lines 490
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 57.55%

Importance

Changes 0
Metric Value
wmc 56
lcom 1
cbo 8
dl 0
loc 490
ccs 80
cts 139
cp 0.5755
rs 6.5957
c 0
b 0
f 0

20 Methods

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

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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

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
 * @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
12
/**
13
 * Controller is the base class for classes containing controller logic.
14
 *
15
 * For more details and usage information on Controller, see the [guide article on controllers](guide:structure-controllers).
16
 *
17
 * @property Module[] $modules All ancestor modules that this controller is located within. This property is
18
 * read-only.
19
 * @property string $route The route (module ID, controller ID and action ID) of the current request. This
20
 * property is read-only.
21
 * @property string $uniqueId The controller ID that is prefixed with the module ID (if any). This property is
22
 * read-only.
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 $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 null|string|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 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
    /**
68
     * @var View the view object that can be used to render views or view files.
69
     */
70
    private $_view;
71
    /**
72
     * @var string the root directory that contains view files for this controller.
73
     */
74
    private $_viewPath;
75
76
77
    /**
78
     * @param string $id the ID of this controller.
79
     * @param Module $module the module that this controller belongs to.
80
     * @param array $config name-value pairs that will be used to initialize the object properties.
81
     */
82 177
    public function __construct($id, $module, $config = [])
83
    {
84 177
        $this->id = $id;
85 177
        $this->module = $module;
86 177
        parent::__construct($config);
87 177
    }
88
89
    /**
90
     * Declares external actions for the controller.
91
     * This method is meant to be overwritten to declare external actions for the controller.
92
     * It should return an array, with array keys being action IDs, and array values the corresponding
93
     * action class names or action configuration arrays. For example,
94
     *
95
     * ```php
96
     * return [
97
     *     'action1' => 'app\components\Action1',
98
     *     'action2' => [
99
     *         'class' => 'app\components\Action2',
100
     *         'property1' => 'value1',
101
     *         'property2' => 'value2',
102
     *     ],
103
     * ];
104
     * ```
105
     *
106
     * [[\Yii::createObject()]] will be used later to create the requested action
107
     * using the configuration provided here.
108
     */
109 104
    public function actions()
110
    {
111 104
        return [];
112
    }
113
114
    /**
115
     * Runs an action within this controller with the specified action ID and parameters.
116
     * If the action ID is empty, the method will use [[defaultAction]].
117
     * @param string $id the ID of the action to be executed.
118
     * @param array $params the parameters (name-value pairs) to be passed to the action.
119
     * @return mixed the result of the action.
120
     * @throws InvalidRouteException if the requested action ID cannot be resolved into an action successfully.
121
     * @see createAction()
122
     */
123 83
    public function runAction($id, $params = [])
124
    {
125 83
        $action = $this->createAction($id);
126 83
        if ($action === null) {
127
            throw new InvalidRouteException('Unable to resolve the request: ' . $this->getUniqueId() . '/' . $id);
128
        }
129
130 83
        Yii::trace('Route to run: ' . $action->getUniqueId(), __METHOD__);
131
132 83
        if (Yii::$app->requestedAction === null) {
133 83
            Yii::$app->requestedAction = $action;
134 83
        }
135
136 83
        $oldAction = $this->action;
137 83
        $this->action = $action;
138
139 83
        $modules = [];
140 83
        $runAction = true;
141
142
        // call beforeAction on modules
143 83
        foreach ($this->getModules() as $module) {
144 83
            if ($module->beforeAction($action)) {
145 83
                array_unshift($modules, $module);
146 83
            } else {
147
                $runAction = false;
148
                break;
149
            }
150 83
        }
151
152 83
        $result = null;
153
154 83
        if ($runAction && $this->beforeAction($action)) {
155
            // run the action
156 83
            $result = $action->runWithParams($params);
157
158 80
            $result = $this->afterAction($action, $result);
159
160
            // call afterAction on modules
161 80
            foreach ($modules as $module) {
162
                /* @var $module Module */
163 80
                $result = $module->afterAction($action, $result);
164 80
            }
165 80
        }
166
167 80
        if ($oldAction !== null) {
168 4
            $this->action = $oldAction;
169 4
        }
170
171 80
        return $result;
172
    }
173
174
    /**
175
     * Runs a request specified in terms of a route.
176
     * The route can be either an ID of an action within this controller or a complete route consisting
177
     * of module IDs, controller ID and action ID. If the route starts with a slash '/', the parsing of
178
     * the route will start from the application; otherwise, it will start from the parent module of this controller.
179
     * @param string $route the route to be handled, e.g., 'view', 'comment/view', '/admin/comment/view'.
180
     * @param array $params the parameters to be passed to the action.
181
     * @return mixed the result of the action.
182
     * @see runAction()
183
     */
184 76
    public function run($route, $params = [])
185
    {
186 76
        $pos = strpos($route, '/');
187 76
        if ($pos === false) {
188 75
            return $this->runAction($route, $params);
189 1
        } elseif ($pos > 0) {
190 1
            return $this->module->runAction($route, $params);
191
        }
192
        return Yii::$app->runAction(ltrim($route, '/'), $params);
193
    }
194
195
    /**
196
     * Binds the parameters to the action.
197
     * This method is invoked by [[Action]] when it begins to run with the given parameters.
198
     * @param Action $action the action to be bound with parameters.
199
     * @param array $params the parameters to be bound to the action.
200
     * @return array the valid parameters that the action can run with.
201
     */
202 3
    public function bindActionParams($action, $params)
203
    {
204 3
        return [];
205
    }
206
207
    /**
208
     * Creates an action based on the given action ID.
209
     * The method first checks if the action ID has been declared in [[actions()]]. If so,
210
     * it will use the configuration declared there to create the action object.
211
     * If not, it will look for a controller method whose name is in the format of `actionXyz`
212
     * where `Xyz` stands for the action ID. If found, an [[InlineAction]] representing that
213
     * method will be created and returned.
214
     * @param string $id the action ID.
215
     * @return Action the newly created action instance. Null if the ID doesn't resolve into any action.
216
     */
217 89
    public function createAction($id)
218
    {
219 89
        if ($id === '') {
220 3
            $id = $this->defaultAction;
221 3
        }
222
223 89
        $actionMap = $this->actions();
224 89
        if (isset($actionMap[$id])) {
225
            return Yii::createObject($actionMap[$id], [$id, $this]);
226 89
        } elseif (preg_match('/^[a-z0-9\\-_]+$/', $id) && strpos($id, '--') === false && trim($id, '-') === $id) {
227 89
            $methodName = 'action' . str_replace(' ', '', ucwords(implode(' ', explode('-', $id))));
228 89
            if (method_exists($this, $methodName)) {
229 89
                $method = new \ReflectionMethod($this, $methodName);
230 89
                if ($method->isPublic() && $method->getName() === $methodName) {
231 89
                    return new InlineAction($id, $this, $methodName);
232
                }
233
            }
234
        }
235
236
        return null;
237
    }
238
239
    /**
240
     * This method is invoked right before an action is executed.
241
     *
242
     * The method will trigger the [[EVENT_BEFORE_ACTION]] event. The return value of the method
243
     * will determine whether the action should continue to run.
244
     *
245
     * In case the action should not run, the request should be handled inside of the `beforeAction` code
246
     * by either providing the necessary output or redirecting the request. Otherwise the response will be empty.
247
     *
248
     * If you override this method, your code should look like the following:
249
     *
250
     * ```php
251
     * public function beforeAction($action)
252
     * {
253
     *     // your custom code here, if you want the code to run before action filters,
254
     *     // which are triggered on the [[EVENT_BEFORE_ACTION]] event, e.g. PageCache or AccessControl
255
     *
256
     *     if (!parent::beforeAction($action)) {
257
     *         return false;
258
     *     }
259
     *
260
     *     // other custom code here
261
     *
262
     *     return true; // or false to not run the action
263
     * }
264
     * ```
265
     *
266
     * @param Action $action the action to be executed.
267
     * @return bool whether the action should continue to run.
268
     */
269 83
    public function beforeAction($action)
270
    {
271 83
        $event = new ActionEvent($action);
272 83
        $this->trigger(self::EVENT_BEFORE_ACTION, $event);
273 83
        return $event->isValid;
274
    }
275
276
    /**
277
     * This method is invoked right after an action is executed.
278
     *
279
     * The method will trigger the [[EVENT_AFTER_ACTION]] event. The return value of the method
280
     * will be used as the action return value.
281
     *
282
     * If you override this method, your code should look like the following:
283
     *
284
     * ```php
285
     * public function afterAction($action, $result)
286
     * {
287
     *     $result = parent::afterAction($action, $result);
288
     *     // your custom code here
289
     *     return $result;
290
     * }
291
     * ```
292
     *
293
     * @param Action $action the action just executed.
294
     * @param mixed $result the action return result.
295
     * @return mixed the processed action result.
296
     */
297 80
    public function afterAction($action, $result)
298
    {
299 80
        $event = new ActionEvent($action);
300 80
        $event->result = $result;
301 80
        $this->trigger(self::EVENT_AFTER_ACTION, $event);
302 80
        return $event->result;
303
    }
304
305
    /**
306
     * Returns all ancestor modules of this controller.
307
     * The first module in the array is the outermost one (i.e., the application instance),
308
     * while the last is the innermost one.
309
     * @return Module[] all ancestor modules that this controller is located within.
310
     */
311 83
    public function getModules()
312
    {
313 83
        $modules = [$this->module];
314 83
        $module = $this->module;
315 83
        while ($module->module !== null) {
316
            array_unshift($modules, $module->module);
317
            $module = $module->module;
318
        }
319 83
        return $modules;
320
    }
321
322
    /**
323
     * Returns the unique ID of the controller.
324
     * @return string the controller ID that is prefixed with the module ID (if any).
325
     */
326 107
    public function getUniqueId()
327
    {
328 107
        return $this->module instanceof Application ? $this->id : $this->module->getUniqueId() . '/' . $this->id;
329
    }
330
331
    /**
332
     * Returns the route of the current request.
333
     * @return string the route (module ID, controller ID and action ID) of the current request.
334
     */
335 4
    public function getRoute()
336
    {
337 4
        return $this->action !== null ? $this->action->getUniqueId() : $this->getUniqueId();
338
    }
339
340
    /**
341
     * Renders a view and applies layout if available.
342
     *
343
     * The view to be rendered can be specified in one of the following formats:
344
     *
345
     * - path alias (e.g. "@app/views/site/index");
346
     * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes.
347
     *   The actual view file will be looked for under the [[Application::viewPath|view path]] of the application.
348
     * - absolute path within module (e.g. "/site/index"): the view name starts with a single slash.
349
     *   The actual view file will be looked for under the [[Module::viewPath|view path]] of [[module]].
350
     * - relative path (e.g. "index"): the actual view file will be looked for under [[viewPath]].
351
     *
352
     * To determine which layout should be applied, the following two steps are conducted:
353
     *
354
     * 1. In the first step, it determines the layout name and the context module:
355
     *
356
     * - If [[layout]] is specified as a string, use it as the layout name and [[module]] as the context module;
357
     * - If [[layout]] is null, search through all ancestor modules of this controller and find the first
358
     *   module whose [[Module::layout|layout]] is not null. The layout and the corresponding module
359
     *   are used as the layout name and the context module, respectively. If such a module is not found
360
     *   or the corresponding layout is not a string, it will return false, meaning no applicable layout.
361
     *
362
     * 2. In the second step, it determines the actual layout file according to the previously found layout name
363
     *    and context module. The layout name can be:
364
     *
365
     * - a path alias (e.g. "@app/views/layouts/main");
366
     * - an absolute path (e.g. "/main"): the layout name starts with a slash. The actual layout file will be
367
     *   looked for under the [[Application::layoutPath|layout path]] of the application;
368
     * - a relative path (e.g. "main"): the actual layout file will be looked for under the
369
     *   [[Module::layoutPath|layout path]] of the context module.
370
     *
371
     * If the layout name does not contain a file extension, it will use the default one `.php`.
372
     *
373
     * @param string $view the view name.
374
     * @param array $params the parameters (name-value pairs) that should be made available in the view.
375
     * These parameters will not be available in the layout.
376
     * @return string the rendering result.
377
     * @throws InvalidParamException if the view file or the layout file does not exist.
378
     */
379
    public function render($view, $params = [])
380
    {
381
        $content = $this->getView()->render($view, $params, $this);
382
        return $this->renderContent($content);
383
    }
384
385
    /**
386
     * Renders a static string by applying a layout.
387
     * @param string $content the static string being rendered
388
     * @return string the rendering result of the layout with the given static string as the `$content` variable.
389
     * If the layout is disabled, the string will be returned back.
390
     * @since 2.0.1
391
     */
392
    public function renderContent($content)
393
    {
394
        $layoutFile = $this->findLayoutFile($this->getView());
395
        if ($layoutFile !== false) {
396
            return $this->getView()->renderFile($layoutFile, ['content' => $content], $this);
0 ignored issues
show
Bug introduced by
It seems like $layoutFile defined by $this->findLayoutFile($this->getView()) on line 394 can also be of type boolean; however, yii\base\View::renderFile() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
397
        }
398
        return $content;
399
    }
400
401
    /**
402
     * Renders a view without applying layout.
403
     * This method differs from [[render()]] in that it does not apply any layout.
404
     * @param string $view the view name. Please refer to [[render()]] on how to specify a view name.
405
     * @param array $params the parameters (name-value pairs) that should be made available in the view.
406
     * @return string the rendering result.
407
     * @throws InvalidParamException if the view file does not exist.
408
     */
409
    public function renderPartial($view, $params = [])
410
    {
411
        return $this->getView()->render($view, $params, $this);
412
    }
413
414
    /**
415
     * Renders a view file.
416
     * @param string $file the view file to be rendered. This can be either a file path or a path alias.
417
     * @param array $params the parameters (name-value pairs) that should be made available in the view.
418
     * @return string the rendering result.
419
     * @throws InvalidParamException if the view file does not exist.
420
     */
421 8
    public function renderFile($file, $params = [])
422
    {
423 8
        return $this->getView()->renderFile($file, $params, $this);
424
    }
425
426
    /**
427
     * Returns the view object that can be used to render views or view files.
428
     * The [[render()]], [[renderPartial()]] and [[renderFile()]] methods will use
429
     * this view object to implement the actual view rendering.
430
     * If not set, it will default to the "view" application component.
431
     * @return View|\yii\web\View the view object that can be used to render views or view files.
432
     */
433 8
    public function getView()
434
    {
435 8
        if ($this->_view === null) {
436 8
            $this->_view = Yii::$app->getView();
437 8
        }
438 8
        return $this->_view;
439
    }
440
441
    /**
442
     * Sets the view object to be used by this controller.
443
     * @param View|\yii\web\View $view the view object that can be used to render views or view files.
444
     */
445
    public function setView($view)
446
    {
447
        $this->_view = $view;
448
    }
449
450
    /**
451
     * Returns the directory containing view files for this controller.
452
     * The default implementation returns the directory named as controller [[id]] under the [[module]]'s
453
     * [[viewPath]] directory.
454
     * @return string the directory containing the view files for this controller.
455
     */
456
    public function getViewPath()
457
    {
458
        if ($this->_viewPath === null) {
459
            $this->_viewPath = $this->module->getViewPath() . DIRECTORY_SEPARATOR . $this->id;
460
        }
461
        return $this->_viewPath;
462
    }
463
464
    /**
465
     * Sets the directory that contains the view files.
466
     * @param string $path the root directory of view files.
467
     * @throws InvalidParamException if the directory is invalid
468
     * @since 2.0.7
469
     */
470
    public function setViewPath($path)
471
    {
472
        $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...
473
    }
474
475
    /**
476
     * Finds the applicable layout file.
477
     * @param View $view the view object to render the layout file.
478
     * @return string|bool the layout file path, or false if layout is not needed.
479
     * Please refer to [[render()]] on how to specify this parameter.
480
     * @throws InvalidParamException if an invalid path alias is used to specify the layout.
481
     */
482
    public function findLayoutFile($view)
483
    {
484
        $module = $this->module;
485
        if (is_string($this->layout)) {
486
            $layout = $this->layout;
487
        } elseif ($this->layout === null) {
488
            while ($module !== null && $module->layout === null) {
489
                $module = $module->module;
490
            }
491
            if ($module !== null && is_string($module->layout)) {
492
                $layout = $module->layout;
493
            }
494
        }
495
496
        if (!isset($layout)) {
497
            return false;
498
        }
499
500
        if (strncmp($layout, '@', 1) === 0) {
501
            $file = Yii::getAlias($layout);
502
        } elseif (strncmp($layout, '/', 1) === 0) {
503
            $file = Yii::$app->getLayoutPath() . DIRECTORY_SEPARATOR . substr($layout, 1);
504
        } else {
505
            $file = $module->getLayoutPath() . DIRECTORY_SEPARATOR . $layout;
506
        }
507
508
        if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
509
            return $file;
510
        }
511
        $path = $file . '.' . $view->defaultExtension;
512
        if ($view->defaultExtension !== 'php' && !is_file($path)) {
513
            $path = $file . '.php';
514
        }
515
516
        return $path;
517
    }
518
}
519