Passed
Push — master ( 9dbdd9...d5a428 )
by Alexander
04:15
created

framework/base/Controller.php (2 issues)

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

108
        $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...
109 491
        $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

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