Controller::bindActionParams()   F
last analyzed

Complexity

Conditions 32
Paths 580

Size

Total Lines 96
Code Lines 70

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 56
CRAP Score 34.7205

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 32
eloc 70
nc 580
nop 2
dl 0
loc 96
ccs 56
cts 65
cp 0.8615
crap 34.7205
rs 0.5833
c 1
b 0
f 0

How to fix   Long Method    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
/**
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
                if (PHP_VERSION_ID >= 80000) {
134 6
                    $isArray = ($type = $param->getType()) instanceof \ReflectionNamedType && $type->getName() === 'array';
135
                } else {
136
                    $isArray = $param->isArray();
137
                }
138 6
                if ($isArray) {
139
                    $params[$name] = (array)$params[$name];
140 6
                } elseif (is_array($params[$name])) {
141
                    $isValid = false;
142
                } elseif (
143 6
                    PHP_VERSION_ID >= 70000
144 6
                    && ($type = $param->getType()) !== null
145 6
                    && method_exists($type, 'isBuiltin')
146 6
                    && $type->isBuiltin()
147 6
                    && ($params[$name] !== null || !$type->allowsNull())
148
                ) {
149 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

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

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

260
        return $this->response->/** @scrutinizer ignore-call */ redirect(Url::to($url), $statusCode);
Loading history...
261
    }
262
263
    /**
264
     * Redirects the browser to the home page.
265
     *
266
     * You can use this method in an action by returning the [[Response]] directly:
267
     *
268
     * ```php
269
     * // stop executing this action and redirect to home page
270
     * return $this->goHome();
271
     * ```
272
     *
273
     * @return Response the current response object
274
     */
275
    public function goHome()
276
    {
277
        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

277
        return $this->response->redirect(Yii::$app->/** @scrutinizer ignore-call */ getHomeUrl());
Loading history...
278
    }
279
280
    /**
281
     * Redirects the browser to the last visited page.
282
     *
283
     * You can use this method in an action by returning the [[Response]] directly:
284
     *
285
     * ```php
286
     * // stop executing this action and redirect to last visited page
287
     * return $this->goBack();
288
     * ```
289
     *
290
     * For this function to work you have to [[User::setReturnUrl()|set the return URL]] in appropriate places before.
291
     *
292
     * @param string|array|null $defaultUrl the default return URL in case it was not set previously.
293
     * If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to.
294
     * Please refer to [[User::setReturnUrl()]] on accepted format of the URL.
295
     * @return Response the current response object
296
     * @see User::getReturnUrl()
297
     */
298
    public function goBack($defaultUrl = null)
299
    {
300
        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

300
        return $this->response->redirect(Yii::$app->/** @scrutinizer ignore-call */ getUser()->getReturnUrl($defaultUrl));
Loading history...
301
    }
302
303
    /**
304
     * Refreshes the current page.
305
     * This method is a shortcut to [[Response::refresh()]].
306
     *
307
     * You can use it in an action by returning the [[Response]] directly:
308
     *
309
     * ```php
310
     * // stop executing this action and refresh the current page
311
     * return $this->refresh();
312
     * ```
313
     *
314
     * @param string $anchor the anchor that should be appended to the redirection URL.
315
     * Defaults to empty. Make sure the anchor starts with '#' if you want to specify it.
316
     * @return Response the response object itself
317
     */
318
    public function refresh($anchor = '')
319
    {
320
        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

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