| Conditions | 8 |
| Paths | 14 |
| Total Lines | 57 |
| Code Lines | 30 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 1 | ||
| 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 |
||
| 13 | function ip_info($ip) { |
||
| 14 | if (is_ip($ip) === false) { |
||
| 15 | $ip_address_array = dns_get_record($ip, DNS_A); |
||
| 16 | $randomKey = array_rand($ip_address_array); |
||
| 17 | $ip = $ip_address_array[$randomKey]["ip"]; |
||
| 18 | } |
||
| 19 | |||
| 20 | // List of API endpoints |
||
| 21 | $endpoints = [ |
||
| 22 | 'https://ipapi.co/{ip}/json/', |
||
| 23 | 'https://ipwhois.app/json/{ip}', |
||
| 24 | 'http://www.geoplugin.net/json.gp?ip={ip}', |
||
| 25 | 'https://api.ipbase.com/v1/json/{ip}' |
||
| 26 | ]; |
||
| 27 | |||
| 28 | // Initialize an empty result object |
||
| 29 | $result = (object) [ |
||
| 30 | 'country' => "XX" |
||
| 31 | ]; |
||
| 32 | |||
| 33 | // Loop through each endpoint |
||
| 34 | foreach ($endpoints as $endpoint) { |
||
| 35 | // Construct the full URL |
||
| 36 | $url = str_replace('{ip}', $ip, $endpoint); |
||
| 37 | |||
| 38 | $options = array( |
||
| 39 | "http"=>array( |
||
| 40 | "header"=>"User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" // i.e. An iPad |
||
| 41 | ) |
||
| 42 | ); |
||
| 43 | |||
| 44 | $context = stream_context_create($options); |
||
| 45 | $response = file_get_contents($url, false, $context); |
||
| 46 | |||
| 47 | if ($response !== false) { |
||
| 48 | $data = json_decode($response); |
||
| 49 | |||
| 50 | // Extract relevant information and update the result object |
||
| 51 | if ($endpoint == $endpoints[0]) { |
||
| 52 | // Data from ipapi.co |
||
| 53 | $result->country = $data->country_code ?? "XX"; |
||
| 54 | } elseif ($endpoint == $endpoints[1]) { |
||
| 55 | // Data from ipwhois.app |
||
| 56 | $result->country = $data->country_code ?? "XX"; |
||
| 57 | } elseif ($endpoint == $endpoints[2]) { |
||
| 58 | // Data from geoplugin.net |
||
| 59 | $result->country = $data->geoplugin_countryCode ?? "XX"; |
||
| 60 | } elseif ($endpoint == $endpoints[3]) { |
||
| 61 | // Data from ipbase.com |
||
| 62 | $result->country = $data->country_code ?? "XX"; |
||
| 63 | } |
||
| 64 | // Break out of the loop since we found a successful endpoint |
||
| 65 | break; |
||
| 66 | } |
||
| 67 | } |
||
| 68 | |||
| 69 | return $result; |
||
| 70 | } |
||
| 71 |