mirror of
https://github.com/shlinkio/shlink.git
synced 2024-12-22 15:13:59 -06:00
Created service to resolve IP locations
This commit is contained in:
parent
06fa33877b
commit
d3c2f4ed2a
10
module/Common/src/Exception/WrongIpException.php
Normal file
10
module/Common/src/Exception/WrongIpException.php
Normal file
@ -0,0 +1,10 @@
|
||||
<?php
|
||||
namespace Shlinkio\Shlink\Common\Exception;
|
||||
|
||||
class WrongIpException extends RuntimeException
|
||||
{
|
||||
public static function fromIpAddress($ipAddress, \Exception $prev = null)
|
||||
{
|
||||
return new self(sprintf('Provided IP "%s" is invalid', $ipAddress), 0, $prev);
|
||||
}
|
||||
}
|
42
module/Common/src/Service/IpLocationResolver.php
Normal file
42
module/Common/src/Service/IpLocationResolver.php
Normal file
@ -0,0 +1,42 @@
|
||||
<?php
|
||||
namespace Shlinkio\Shlink\Common\Service;
|
||||
|
||||
use Acelaya\ZsmAnnotatedServices\Annotation\Inject;
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\Exception\GuzzleException;
|
||||
use Shlinkio\Shlink\Common\Exception\WrongIpException;
|
||||
|
||||
class IpLocationResolver implements IpLocationResolverInterface
|
||||
{
|
||||
const SERVICE_PATTERN = 'http://freegeoip.net/json/%s';
|
||||
|
||||
/**
|
||||
* @var Client
|
||||
*/
|
||||
private $httpClient;
|
||||
|
||||
/**
|
||||
* IpLocationResolver constructor.
|
||||
* @param Client $httpClient
|
||||
*
|
||||
* @Inject({"httpClient"})
|
||||
*/
|
||||
public function __construct(Client $httpClient)
|
||||
{
|
||||
$this->httpClient = $httpClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $ipAddress
|
||||
* @return array
|
||||
*/
|
||||
public function resolveIpLocation($ipAddress)
|
||||
{
|
||||
try {
|
||||
$response = $this->httpClient->get(sprintf(self::SERVICE_PATTERN, $ipAddress));
|
||||
return json_decode($response->getBody(), true);
|
||||
} catch (GuzzleException $e) {
|
||||
throw WrongIpException::fromIpAddress($ipAddress, $e);
|
||||
}
|
||||
}
|
||||
}
|
11
module/Common/src/Service/IpLocationResolverInterface.php
Normal file
11
module/Common/src/Service/IpLocationResolverInterface.php
Normal file
@ -0,0 +1,11 @@
|
||||
<?php
|
||||
namespace Shlinkio\Shlink\Common\Service;
|
||||
|
||||
interface IpLocationResolverInterface
|
||||
{
|
||||
/**
|
||||
* @param $ipAddress
|
||||
* @return array
|
||||
*/
|
||||
public function resolveIpLocation($ipAddress);
|
||||
}
|
Loading…
Reference in New Issue
Block a user