curl = $curl; $this->remoteAddress = $remoteAddress; $this->jsonSerializer = $jsonSerializer; $this->configHelper = $configHelper; $this->geoIpCache = $geoIpCache; } /** * @inheritDoc */ public function getGeoLocation(?string $ip): ?array { $result = null; if (! $ip) { $ip = $this->remoteAddress->getRemoteAddress(); } if ($ip) { $cacheKey = ip2long($ip) . '_gl_ipapi'; $geoipCache = $this->geoIpCache->get(); if (isset($geoipCache[$cacheKey])) { return $geoipCache[$cacheKey]; } $curlResult = $this->curlExec($ip); if ($curlResult) { $curlResultArr = $this->jsonSerializer->unserialize($curlResult); if (isset($curlResultArr['error'])) { return $result; } $result = [ 'country_code' => $curlResultArr['country_code'] ?? '', 'country_name' => $curlResultArr['country_name'] ?? '', 'region_name' => $curlResultArr['region_name'] ?? '', 'city_name' => $curlResultArr['city'] ?? '', 'latitude' => $curlResultArr['latitude'] ?? '', 'longitude' => $curlResultArr['longitude'] ?? '', 'database_name' => $this->dataName ]; } $result = (!empty($result)) ? $result : null; $geoipCache[$cacheKey] = $result; $this->geoIpCache->set($geoipCache); } return $result; } /** * @inheritDoc */ public function getCountryCode(?string $ip): ?string { $result = null; if (! $ip) { $ip = $this->remoteAddress->getRemoteAddress(); } if ($ip) { $cacheKey = ip2long($ip) . '_cc_ipapi'; $geoipCache = $this->geoIpCache->get(); if (isset($geoipCache[$cacheKey])) { return $geoipCache[$cacheKey]; } $curlResult = $this->curlExec($ip); if ($curlResult) { $curlResultArr = $this->jsonSerializer->unserialize($curlResult); if (isset($curlResultArr['error'])) { return $result; } else { $result = $curlResultArr['country_code']; } } $result = (!empty($result)) ? $result : null; $geoipCache[$cacheKey] = $result; $this->geoIpCache->set($geoipCache); } return $result; } /** * @inheritDoc */ public function getCurrentCountryState(?string $ip): ?string { $result = null; if (! $ip) { $ip = $this->remoteAddress->getRemoteAddress(); } if ($ip) { $cacheKey = ip2long($ip) . '_cc_ipapi_cstate'; $geoipCache = $this->geoIpCache->get(); if (isset($geoipCache[$cacheKey])) { return $geoipCache[$cacheKey]; } $curlResult = $this->curlExec($ip); if ($curlResult) { $curlResultArr = $this->jsonSerializer->unserialize($curlResult); if (isset($curlResultArr['error'])) { return $result; } else { $result = $curlResultArr['region_name']; } } $result = (!empty($result)) ? $result : null; $geoipCache[$cacheKey] = $result; $this->geoIpCache->set($geoipCache); } return $result; } /** * @param $ip * @return string */ private function curlExec($ip): string { $url = $this->configHelper->useIpApiHttps() ? "https://" : "http://"; $url .= $this->configHelper->getIpApiUrl($ip); $options = [ CURLOPT_HEADER => 0, CURLOPT_FRESH_CONNECT => 1, CURLOPT_RETURNTRANSFER => 1, CURLOPT_FORBID_REUSE => 1, CURLOPT_TIMEOUT => 4, ]; $this->curl->post($url, $options); return $this->curl->getBody(); } }