Passed
Push — master ( 391997...f2ea9b )
by Alexander
09:24
created

Controller::goBack()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * @link https://www.yiiframework.com/
5
 * @copyright Copyright (c) 2008 Yii Software LLC
6
 * @license https://www.yiiframework.com/license/
7
 */
8
9
namespace yii\web;
10
11
use Yii;
12
use yii\base\Exception;
13
use yii\base\InlineAction;
14
use yii\helpers\Url;
15
16
/**
17
 * Controller is the base class of web controllers.
18
 *
19
 * For more details and usage information on Controller, see the [guide article on controllers](guide:structure-controllers).
20
 *
21
 * @author Qiang Xue <[email protected]>
22
 * @since 2.0
23
 */
24
class Controller extends \yii\base\Controller
25
{
26
    /**
27
     * @var bool whether to enable CSRF validation for the actions in this controller.
28
     * CSRF validation is enabled only when both this property and [[\yii\web\Request::enableCsrfValidation]] are true.
29
     */
30
    public $enableCsrfValidation = true;
31
    /**
32
     * @var array the parameters bound to the current action.
33
     */
34
    public $actionParams = [];
35
36
37
    /**
38
     * Renders a view in response to an AJAX request.
39
     *
40
     * This method is similar to [[renderPartial()]] except that it will inject into
41
     * the rendering result with JS/CSS scripts and files which are registered with the view.
42
     * For this reason, you should use this method instead of [[renderPartial()]] to render
43
     * a view to respond to an AJAX request.
44
     *
45
     * @param string $view the view name. Please refer to [[render()]] on how to specify a view name.
46
     * @param array $params the parameters (name-value pairs) that should be made available in the view.
47
     * @return string the rendering result.
48
     */
49
    public function renderAjax($view, $params = [])
50
    {
51
        return $this->getView()->renderAjax($view, $params, $this);
0 ignored issues
show
Bug introduced by
The method renderAjax() does not exist on yii\base\View. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

51
        return $this->getView()->/** @scrutinizer ignore-call */ renderAjax($view, $params, $this);
Loading history...
52
    }
53
54
    /**
55
     * Send data formatted as JSON.
56
     *
57
     * This method is a shortcut for sending data formatted as JSON. It will return
58
     * the [[Application::getResponse()|response]] application component after configuring
59
     * the [[Response::$format|format]] and setting the [[Response::$data|data]] that should
60
     * be formatted. A common usage will be:
61
     *
62
     * ```php
63
     * return $this->asJson($data);
64
     * ```
65
     *
66
     * @param mixed $data the data that should be formatted.
67
     * @return Response a response that is configured to send `$data` formatted as JSON.
68
     * @since 2.0.11
69
     * @see Response::$format
70
     * @see Response::FORMAT_JSON
71
     * @see JsonResponseFormatter
72
     */
73 1
    public function asJson($data)
74
    {
75 1
        $this->response->format = Response::FORMAT_JSON;
0 ignored issues
show
Bug Best Practice introduced by
The property format does not exist on yii\base\Response. Since you implemented __set, consider adding a @property annotation.
Loading history...
76 1
        $this->response->data = $data;
0 ignored issues
show
Bug Best Practice introduced by
The property data does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
77 1
        return $this->response;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->response returns the type array|string which is incompatible with the documented return type yii\web\Response.
Loading history...
78
    }
79
80
    /**
81
     * Send data formatted as XML.
82
     *
83
     * This method is a shortcut for sending data formatted as XML. It will return
84
     * the [[Application::getResponse()|response]] application component after configuring
85
     * the [[Response::$format|format]] and setting the [[Response::$data|data]] that should
86
     * be formatted. A common usage will be:
87
     *
88
     * ```php
89
     * return $this->asXml($data);
90
     * ```
91
     *
92
     * @param mixed $data the data that should be formatted.
93
     * @return Response a response that is configured to send `$data` formatted as XML.
94
     * @since 2.0.11
95
     * @see Response::$format
96
     * @see Response::FORMAT_XML
97
     * @see XmlResponseFormatter
98
     */
99 1
    public function asXml($data)
100
    {
101 1
        $this->response->format = Response::FORMAT_XML;
0 ignored issues
show
Bug Best Practice introduced by
The property format does not exist on yii\base\Response. Since you implemented __set, consider adding a @property annotation.
Loading history...
102 1
        $this->response->data = $data;
0 ignored issues
show
Bug Best Practice introduced by
The property data does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
103 1
        return $this->response;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->response returns the type array|string which is incompatible with the documented return type yii\web\Response.
Loading history...
104
    }
105
106
    /**
107
     * Binds the parameters to the action.
108
     * This method is invoked by [[\yii\base\Action]] when it begins to run with the given parameters.
109
     * This method will check the parameter names that the action requires and return
110
     * the provided parameters according to the requirement. If there is any missing parameter,
111
     * an exception will be thrown.
112
     * @param \yii\base\Action $action the action to be bound with parameters
113
     * @param array $params the parameters to be bound to the action
114
     * @return array the valid parameters that the action can run with.
115
     * @throws BadRequestHttpException if there are missing or invalid parameters.
116
     */
117 91
    public function bindActionParams($action, $params)
118
    {
119 91
        if ($action instanceof InlineAction) {
120 77
            $method = new \ReflectionMethod($this, $action->actionMethod);
121
        } else {
122 14
            $method = new \ReflectionMethod($action, 'run');
123
        }
124
125 91
        $args = [];
126 91
        $missing = [];
127 91
        $actionParams = [];
128 91
        $requestedParams = [];
129 91
        foreach ($method->getParameters() as $param) {
130 9
            $name = $param->getName();
131 9
            if (array_key_exists($name, $params)) {
132 6
                $isValid = true;                
133 6
                $isArray = ($type = $param->getType()) instanceof \ReflectionNamedType && $type->getName() === 'array';
134
                
135 6
                if ($isArray) {
136
                    $params[$name] = (array)$params[$name];
137 6
                } elseif (is_array($params[$name])) {
138
                    $isValid = false;
139
                } elseif (
140 6
                    PHP_VERSION_ID >= 70000
141 6
                    && ($type = $param->getType()) !== null
142 6
                    && method_exists($type, 'isBuiltin')
143 6
                    && $type->isBuiltin()
144 6
                    && ($params[$name] !== null || !$type->allowsNull())
145
                ) {
146 1
                    $typeName = PHP_VERSION_ID >= 70100 ? $type->getName() : (string)$type;
0 ignored issues
show
Bug introduced by
The method getName() does not exist on ReflectionType. It seems like you code against a sub-type of ReflectionType such as ReflectionNamedType. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

146
                    $typeName = PHP_VERSION_ID >= 70100 ? $type->/** @scrutinizer ignore-call */ getName() : (string)$type;
Loading history...
147
148 1
                    if ($params[$name] === '' && $type->allowsNull()) {
149 1
                        if ($typeName !== 'string') { // for old string behavior compatibility
150 1
                            $params[$name] = null;
151
                        }
152
                    } else {
153
                        switch ($typeName) {
154 1
                            case 'int':
155 1
                                $params[$name] = filter_var($params[$name], FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
156 1
                                break;
157 1
                            case 'float':
158
                                $params[$name] = filter_var($params[$name], FILTER_VALIDATE_FLOAT, FILTER_NULL_ON_FAILURE);
159
                                break;
160 1
                            case 'bool':
161 1
                                $params[$name] = filter_var($params[$name], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
162 1
                                break;
163
                        }
164 1
                        if ($params[$name] === null) {
165 1
                            $isValid = false;
166
                        }
167
                    }
168
                }
169 6
                if (!$isValid) {
170 1
                    throw new BadRequestHttpException(
171 1
                        Yii::t('yii', 'Invalid data received for parameter "{param}".', ['param' => $name])
172 1
                    );
173
                }
174 6
                $args[] = $actionParams[$name] = $params[$name];
175 6
                unset($params[$name]);
176
            } elseif (
177 7
                PHP_VERSION_ID >= 70100
178 7
                && ($type = $param->getType()) !== null
179 7
                && $type instanceof \ReflectionNamedType
180 7
                && !$type->isBuiltin()
181
            ) {
182
                try {
183 6
                    $this->bindInjectedParams($type, $name, $args, $requestedParams);
184 3
                } catch (HttpException $e) {
185 1
                    throw $e;
186 2
                } catch (Exception $e) {
187 5
                    throw new ServerErrorHttpException($e->getMessage(), 0, $e);
188
                }
189 1
            } elseif ($param->isDefaultValueAvailable()) {
190 1
                $args[] = $actionParams[$name] = $param->getDefaultValue();
191
            } else {
192
                $missing[] = $name;
193
            }
194
        }
195
196 88
        if (!empty($missing)) {
197
            throw new BadRequestHttpException(
198
                Yii::t('yii', 'Missing required parameters: {params}', ['params' => implode(', ', $missing)])
199
            );
200
        }
201
202 88
        $this->actionParams = $actionParams;
203
204
        // We use a different array here, specifically one that doesn't contain service instances but descriptions instead.
205 88
        if (Yii::$app->requestedParams === null) {
206 88
            Yii::$app->requestedParams = array_merge($actionParams, $requestedParams);
207
        }
208
209 88
        return $args;
210
    }
211
212
    /**
213
     * {@inheritdoc}
214
     */
215 83
    public function beforeAction($action)
216
    {
217 83
        if (parent::beforeAction($action)) {
218 77
            if ($this->enableCsrfValidation && Yii::$app->getErrorHandler()->exception === null && !$this->request->validateCsrfToken()) {
0 ignored issues
show
Bug introduced by
The method validateCsrfToken() does not exist on yii\base\Request. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

218
            if ($this->enableCsrfValidation && Yii::$app->getErrorHandler()->exception === null && !$this->request->/** @scrutinizer ignore-call */ validateCsrfToken()) {
Loading history...
219
                throw new BadRequestHttpException(Yii::t('yii', 'Unable to verify your data submission.'));
220
            }
221
222 77
            return true;
223
        }
224
225
        return false;
226
    }
227
228
    /**
229
     * Redirects the browser to the specified URL.
230
     * This method is a shortcut to [[Response::redirect()]].
231
     *
232
     * You can use it in an action by returning the [[Response]] directly:
233
     *
234
     * ```php
235
     * // stop executing this action and redirect to login page
236
     * return $this->redirect(['login']);
237
     * ```
238
     *
239
     * @param string|array $url the URL to be redirected to. This can be in one of the following formats:
240
     *
241
     * - a string representing a URL (e.g. "https://example.com")
242
     * - a string representing a URL alias (e.g. "@example.com")
243
     * - an array in the format of `[$route, ...name-value pairs...]` (e.g. `['site/index', 'ref' => 1]`)
244
     *   [[Url::to()]] will be used to convert the array into a URL.
245
     *
246
     * Any relative URL that starts with a single forward slash "/" will be converted
247
     * into an absolute one by prepending it with the host info of the current request.
248
     *
249
     * @param int $statusCode the HTTP status code. Defaults to 302.
250
     * See <https://tools.ietf.org/html/rfc2616#section-10>
251
     * for details about HTTP status code
252
     * @return Response the current response object
253
     */
254 1
    public function redirect($url, $statusCode = 302)
255
    {
256
        // calling Url::to() here because Response::redirect() modifies route before calling Url::to()
257 1
        return $this->response->redirect(Url::to($url), $statusCode);
0 ignored issues
show
Bug introduced by
The method redirect() does not exist on yii\base\Response. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

257
        return $this->response->/** @scrutinizer ignore-call */ redirect(Url::to($url), $statusCode);
Loading history...
258
    }
259
260
    /**
261
     * Redirects the browser to the home page.
262
     *
263
     * You can use this method in an action by returning the [[Response]] directly:
264
     *
265
     * ```php
266
     * // stop executing this action and redirect to home page
267
     * return $this->goHome();
268
     * ```
269
     *
270
     * @return Response the current response object
271
     */
272
    public function goHome()
273
    {
274
        return $this->response->redirect(Yii::$app->getHomeUrl());
0 ignored issues
show
Bug introduced by
The method getHomeUrl() does not exist on yii\console\Application. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

274
        return $this->response->redirect(Yii::$app->/** @scrutinizer ignore-call */ getHomeUrl());
Loading history...
275
    }
276
277
    /**
278
     * Redirects the browser to the last visited page.
279
     *
280
     * You can use this method in an action by returning the [[Response]] directly:
281
     *
282
     * ```php
283
     * // stop executing this action and redirect to last visited page
284
     * return $this->goBack();
285
     * ```
286
     *
287
     * For this function to work you have to [[User::setReturnUrl()|set the return URL]] in appropriate places before.
288
     *
289
     * @param string|array|null $defaultUrl the default return URL in case it was not set previously.
290
     * If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to.
291
     * Please refer to [[User::setReturnUrl()]] on accepted format of the URL.
292
     * @return Response the current response object
293
     * @see User::getReturnUrl()
294
     */
295
    public function goBack($defaultUrl = null)
296
    {
297
        return $this->response->redirect(Yii::$app->getUser()->getReturnUrl($defaultUrl));
0 ignored issues
show
Bug introduced by
The method getUser() does not exist on yii\console\Application. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

297
        return $this->response->redirect(Yii::$app->/** @scrutinizer ignore-call */ getUser()->getReturnUrl($defaultUrl));
Loading history...
298
    }
299
300
    /**
301
     * Refreshes the current page.
302
     * This method is a shortcut to [[Response::refresh()]].
303
     *
304
     * You can use it in an action by returning the [[Response]] directly:
305
     *
306
     * ```php
307
     * // stop executing this action and refresh the current page
308
     * return $this->refresh();
309
     * ```
310
     *
311
     * @param string $anchor the anchor that should be appended to the redirection URL.
312
     * Defaults to empty. Make sure the anchor starts with '#' if you want to specify it.
313
     * @return Response the response object itself
314
     */
315
    public function refresh($anchor = '')
316
    {
317
        return $this->response->redirect($this->request->getUrl() . $anchor);
0 ignored issues
show
Bug introduced by
The method getUrl() does not exist on yii\base\Request. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

317
        return $this->response->redirect($this->request->/** @scrutinizer ignore-call */ getUrl() . $anchor);
Loading history...
318
    }
319
}
320