Total Complexity | 43 |
Total Lines | 296 |
Duplicated Lines | 0 % |
Changes | 2 | ||
Bugs | 0 | Features | 0 |
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.
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 |
||
26 | class Controller extends \yii\base\Controller |
||
27 | { |
||
28 | /** |
||
29 | * @var bool whether to enable CSRF validation for the actions in this controller. |
||
30 | * CSRF validation is enabled only when both this property and [[\yii\web\Request::enableCsrfValidation]] are true. |
||
31 | */ |
||
32 | public $enableCsrfValidation = true; |
||
33 | /** |
||
34 | * @var array the parameters bound to the current action. |
||
35 | */ |
||
36 | public $actionParams = []; |
||
37 | |||
38 | |||
39 | /** |
||
40 | * Renders a view in response to an AJAX request. |
||
41 | * |
||
42 | * This method is similar to [[renderPartial()]] except that it will inject into |
||
43 | * the rendering result with JS/CSS scripts and files which are registered with the view. |
||
44 | * For this reason, you should use this method instead of [[renderPartial()]] to render |
||
45 | * a view to respond to an AJAX request. |
||
46 | * |
||
47 | * @param string $view the view name. Please refer to [[render()]] on how to specify a view name. |
||
48 | * @param array $params the parameters (name-value pairs) that should be made available in the view. |
||
49 | * @return string the rendering result. |
||
50 | */ |
||
51 | public function renderAjax($view, $params = []) |
||
52 | { |
||
53 | return $this->getView()->renderAjax($view, $params, $this); |
||
|
|||
54 | } |
||
55 | |||
56 | /** |
||
57 | * Send data formatted as JSON. |
||
58 | * |
||
59 | * This method is a shortcut for sending data formatted as JSON. It will return |
||
60 | * the [[Application::getResponse()|response]] application component after configuring |
||
61 | * the [[Response::$format|format]] and setting the [[Response::$data|data]] that should |
||
62 | * be formatted. A common usage will be: |
||
63 | * |
||
64 | * ```php |
||
65 | * return $this->asJson($data); |
||
66 | * ``` |
||
67 | * |
||
68 | * @param mixed $data the data that should be formatted. |
||
69 | * @return Response a response that is configured to send `$data` formatted as JSON. |
||
70 | * @since 2.0.11 |
||
71 | * @see Response::$format |
||
72 | * @see Response::FORMAT_JSON |
||
73 | * @see JsonResponseFormatter |
||
74 | */ |
||
75 | public function asJson($data) |
||
80 | } |
||
81 | |||
82 | /** |
||
83 | * Send data formatted as XML. |
||
84 | * |
||
85 | * This method is a shortcut for sending data formatted as XML. It will return |
||
86 | * the [[Application::getResponse()|response]] application component after configuring |
||
87 | * the [[Response::$format|format]] and setting the [[Response::$data|data]] that should |
||
88 | * be formatted. A common usage will be: |
||
89 | * |
||
90 | * ```php |
||
91 | * return $this->asXml($data); |
||
92 | * ``` |
||
93 | * |
||
94 | * @param mixed $data the data that should be formatted. |
||
95 | * @return Response a response that is configured to send `$data` formatted as XML. |
||
96 | * @since 2.0.11 |
||
97 | * @see Response::$format |
||
98 | * @see Response::FORMAT_XML |
||
99 | * @see XmlResponseFormatter |
||
100 | */ |
||
101 | public function asXml($data) |
||
106 | } |
||
107 | |||
108 | /** |
||
109 | * Binds the parameters to the action. |
||
110 | * This method is invoked by [[\yii\base\Action]] when it begins to run with the given parameters. |
||
111 | * This method will check the parameter names that the action requires and return |
||
112 | * the provided parameters according to the requirement. If there is any missing parameter, |
||
113 | * an exception will be thrown. |
||
114 | * @param \yii\base\Action $action the action to be bound with parameters |
||
115 | * @param array $params the parameters to be bound to the action |
||
116 | * @return array the valid parameters that the action can run with. |
||
117 | * @throws BadRequestHttpException if there are missing or invalid parameters. |
||
118 | */ |
||
119 | public function bindActionParams($action, $params) |
||
120 | { |
||
121 | if ($action instanceof InlineAction) { |
||
122 | $method = new \ReflectionMethod($this, $action->actionMethod); |
||
123 | } else { |
||
124 | $method = new \ReflectionMethod($action, 'run'); |
||
125 | } |
||
126 | |||
127 | $args = []; |
||
128 | $missing = []; |
||
129 | $actionParams = []; |
||
130 | $requestedParams = []; |
||
131 | foreach ($method->getParameters() as $param) { |
||
132 | $name = $param->getName(); |
||
133 | if (array_key_exists($name, $params)) { |
||
134 | $isValid = true; |
||
135 | if (PHP_VERSION_ID >= 80000) { |
||
136 | $isArray = ($type = $param->getType()) instanceof \ReflectionNamedType && $type->getName() === 'array'; |
||
137 | } else { |
||
138 | $isArray = $param->isArray(); |
||
139 | } |
||
140 | if ($isArray) { |
||
141 | $params[$name] = (array)$params[$name]; |
||
142 | } elseif (is_array($params[$name])) { |
||
143 | $isValid = false; |
||
144 | } elseif ( |
||
145 | PHP_VERSION_ID >= 70000 |
||
146 | && ($type = $param->getType()) !== null |
||
147 | && $type->isBuiltin() |
||
148 | && ($params[$name] !== null || !$type->allowsNull()) |
||
149 | ) { |
||
150 | $typeName = PHP_VERSION_ID >= 70100 ? $type->getName() : (string)$type; |
||
151 | |||
152 | if ($params[$name] === '' && $type->allowsNull()) { |
||
153 | if ($typeName !== 'string') { // for old string behavior compatibility |
||
154 | $params[$name] = null; |
||
155 | } |
||
156 | } else { |
||
157 | switch ($typeName) { |
||
158 | case 'int': |
||
159 | $params[$name] = filter_var($params[$name], FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE); |
||
160 | break; |
||
161 | case 'float': |
||
162 | $params[$name] = filter_var($params[$name], FILTER_VALIDATE_FLOAT, FILTER_NULL_ON_FAILURE); |
||
163 | break; |
||
164 | case 'bool': |
||
165 | $params[$name] = filter_var($params[$name], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); |
||
166 | break; |
||
167 | } |
||
168 | if ($params[$name] === null) { |
||
169 | $isValid = false; |
||
170 | } |
||
171 | } |
||
172 | } |
||
173 | if (!$isValid) { |
||
174 | throw new BadRequestHttpException( |
||
175 | Yii::t('yii', 'Invalid data received for parameter "{param}".', ['param' => $name]) |
||
176 | ); |
||
177 | } |
||
178 | $args[] = $actionParams[$name] = $params[$name]; |
||
179 | unset($params[$name]); |
||
180 | } elseif ( |
||
181 | PHP_VERSION_ID >= 70100 |
||
182 | && ($type = $param->getType()) !== null |
||
183 | && $type instanceof \ReflectionNamedType |
||
184 | && !$type->isBuiltin() |
||
185 | ) { |
||
186 | try { |
||
187 | $this->bindInjectedParams($type, $name, $args, $requestedParams); |
||
188 | } catch (HttpException $e) { |
||
189 | throw $e; |
||
190 | } catch (Exception $e) { |
||
191 | throw new ServerErrorHttpException($e->getMessage(), 0, $e); |
||
192 | } |
||
193 | } elseif ($param->isDefaultValueAvailable()) { |
||
194 | $args[] = $actionParams[$name] = $param->getDefaultValue(); |
||
195 | } else { |
||
196 | $missing[] = $name; |
||
197 | } |
||
198 | } |
||
199 | |||
200 | if (!empty($missing)) { |
||
201 | throw new BadRequestHttpException( |
||
202 | Yii::t('yii', 'Missing required parameters: {params}', ['params' => implode(', ', $missing)]) |
||
203 | ); |
||
204 | } |
||
205 | |||
206 | $this->actionParams = $actionParams; |
||
207 | |||
208 | // We use a different array here, specifically one that doesn't contain service instances but descriptions instead. |
||
209 | if (Yii::$app->requestedParams === null) { |
||
210 | Yii::$app->requestedParams = array_merge($actionParams, $requestedParams); |
||
211 | } |
||
212 | |||
213 | return $args; |
||
214 | } |
||
215 | |||
216 | /** |
||
217 | * {@inheritdoc} |
||
218 | */ |
||
219 | public function beforeAction($action) |
||
220 | { |
||
221 | if (parent::beforeAction($action)) { |
||
222 | if ($this->enableCsrfValidation && Yii::$app->getErrorHandler()->exception === null && !$this->request->validateCsrfToken()) { |
||
223 | throw new BadRequestHttpException(Yii::t('yii', 'Unable to verify your data submission.')); |
||
224 | } |
||
225 | |||
226 | return true; |
||
227 | } |
||
228 | |||
229 | return false; |
||
230 | } |
||
231 | |||
232 | /** |
||
233 | * Redirects the browser to the specified URL. |
||
234 | * This method is a shortcut to [[Response::redirect()]]. |
||
235 | * |
||
236 | * You can use it in an action by returning the [[Response]] directly: |
||
237 | * |
||
238 | * ```php |
||
239 | * // stop executing this action and redirect to login page |
||
240 | * return $this->redirect(['login']); |
||
241 | * ``` |
||
242 | * |
||
243 | * @param string|array $url the URL to be redirected to. This can be in one of the following formats: |
||
244 | * |
||
245 | * - a string representing a URL (e.g. "http://example.com") |
||
246 | * - a string representing a URL alias (e.g. "@example.com") |
||
247 | * - an array in the format of `[$route, ...name-value pairs...]` (e.g. `['site/index', 'ref' => 1]`) |
||
248 | * [[Url::to()]] will be used to convert the array into a URL. |
||
249 | * |
||
250 | * Any relative URL that starts with a single forward slash "/" will be converted |
||
251 | * into an absolute one by prepending it with the host info of the current request. |
||
252 | * |
||
253 | * @param int $statusCode the HTTP status code. Defaults to 302. |
||
254 | * See <https://tools.ietf.org/html/rfc2616#section-10> |
||
255 | * for details about HTTP status code |
||
256 | * @return Response the current response object |
||
257 | */ |
||
258 | public function redirect($url, $statusCode = 302) |
||
259 | { |
||
260 | // calling Url::to() here because Response::redirect() modifies route before calling Url::to() |
||
261 | return $this->response->redirect(Url::to($url), $statusCode); |
||
262 | } |
||
263 | |||
264 | /** |
||
265 | * Redirects the browser to the home page. |
||
266 | * |
||
267 | * You can use this method in an action by returning the [[Response]] directly: |
||
268 | * |
||
269 | * ```php |
||
270 | * // stop executing this action and redirect to home page |
||
271 | * return $this->goHome(); |
||
272 | * ``` |
||
273 | * |
||
274 | * @return Response the current response object |
||
275 | */ |
||
276 | public function goHome() |
||
279 | } |
||
280 | |||
281 | /** |
||
282 | * Redirects the browser to the last visited page. |
||
283 | * |
||
284 | * You can use this method in an action by returning the [[Response]] directly: |
||
285 | * |
||
286 | * ```php |
||
287 | * // stop executing this action and redirect to last visited page |
||
288 | * return $this->goBack(); |
||
289 | * ``` |
||
290 | * |
||
291 | * For this function to work you have to [[User::setReturnUrl()|set the return URL]] in appropriate places before. |
||
292 | * |
||
293 | * @param string|array $defaultUrl the default return URL in case it was not set previously. |
||
294 | * If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to. |
||
295 | * Please refer to [[User::setReturnUrl()]] on accepted format of the URL. |
||
296 | * @return Response the current response object |
||
297 | * @see User::getReturnUrl() |
||
298 | */ |
||
299 | public function goBack($defaultUrl = null) |
||
300 | { |
||
301 | return $this->response->redirect(Yii::$app->getUser()->getReturnUrl($defaultUrl)); |
||
302 | } |
||
303 | |||
304 | /** |
||
305 | * Refreshes the current page. |
||
306 | * This method is a shortcut to [[Response::refresh()]]. |
||
307 | * |
||
308 | * You can use it in an action by returning the [[Response]] directly: |
||
309 | * |
||
310 | * ```php |
||
311 | * // stop executing this action and refresh the current page |
||
312 | * return $this->refresh(); |
||
313 | * ``` |
||
314 | * |
||
315 | * @param string $anchor the anchor that should be appended to the redirection URL. |
||
316 | * Defaults to empty. Make sure the anchor starts with '#' if you want to specify it. |
||
317 | * @return Response the response object itself |
||
318 | */ |
||
319 | public function refresh($anchor = '') |
||
322 | } |
||
323 | } |
||
324 |