Completed
Push — 2.1 ( c952e8...98ed49 )
by Carsten
10:00
created

Controller::findLayoutFile()   C

Complexity

Conditions 13
Paths 40

Size

Total Lines 36
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 182

Importance

Changes 0
Metric Value
dl 0
loc 36
rs 5.1234
c 0
b 0
f 0
ccs 0
cts 27
cp 0
cc 13
eloc 23
nc 40
nop 1
crap 182

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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