| Conditions | 10 |
| Paths | 5 |
| Total Lines | 43 |
| Code Lines | 22 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 2 | ||
| Bugs | 0 | Features | 0 |
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:
If many parameters/temporary variables are present:
| 1 | <?php |
||
| 17 | public function handle($request, Closure $next) |
||
| 18 | { |
||
| 19 | if (! config('recaptcha.enabled')) { |
||
| 20 | return $next($request); |
||
| 21 | } |
||
| 22 | |||
| 23 | if ($request->has('g-recaptcha-response')) { |
||
| 24 | $client = new \GuzzleHttp\Client(); |
||
| 25 | $res = $client->post(config('recaptcha.domain'), [ |
||
| 26 | 'form_params' => [ |
||
| 27 | 'secret' => config('recaptcha.secret_key'), |
||
| 28 | 'response' => $request->input('g-recaptcha-response'), |
||
| 29 | ], |
||
| 30 | ]); |
||
| 31 | |||
| 32 | if ($res->getStatusCode() === 200) { |
||
| 33 | $result = json_decode($res->getBody()); |
||
| 34 | |||
| 35 | $verified = function ($result, $request) { |
||
| 36 | if (! config('recaptcha.verify_domain')) { |
||
| 37 | return false; |
||
| 38 | } |
||
| 39 | |||
| 40 | $url = parse_url($request->url()); |
||
| 41 | |||
| 42 | if (! array_key_exists('host', $url)) { |
||
| 43 | return false; |
||
| 44 | } |
||
| 45 | |||
| 46 | return $result->hostname === $url['host']; |
||
| 47 | }; |
||
| 48 | |||
| 49 | if ($result->success && (! config('recaptcha.verify_domain') || $verified($result, $request))) { |
||
| 50 | return $next($request); |
||
| 51 | } |
||
| 52 | } |
||
| 53 | } |
||
| 54 | |||
| 55 | // Emit an event and return to the previous view with an error (only the captcha error will be shown!) |
||
| 56 | event(new FailedCaptcha($request->ip(), (! isset($result->hostname) ?: $result->hostname))); |
||
|
|
|||
| 57 | |||
| 58 | return back()->withErrors(['g-recaptcha-response' => trans('strings.captcha_invalid')])->withInput(); |
||
| 59 | } |
||
| 60 | } |
||
| 61 |
If you define a variable conditionally, it can happen that it is not defined for all execution paths.
Let’s take a look at an example:
In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.
Available Fixes
Check for existence of the variable explicitly:
Define a default value for the variable:
Add a value for the missing path: