Updated code to follow the PSR-2 style guidelines.

This commit is contained in:
Gregory Oschwald
2013-05-09 07:29:29 -07:00
parent 95813b00a9
commit ed6166f934
22 changed files with 807 additions and 636 deletions
+11 -9
View File
@@ -4,13 +4,15 @@ namespace GeoIP2\Exception;
class HttpException extends \Exception
{
public $code;
public $code;
public function __construct($message, $code, $uri,
Exception $previous = null)
{
$this->code = $code;
parent::__construct($message, null, $previous);
}
}
public function __construct(
$message,
$code,
$uri,
Exception $previous = null
) {
$this->code = $code;
parent::__construct($message, null, $previous);
}
}
+12 -9
View File
@@ -4,13 +4,16 @@ namespace GeoIP2\Exception;
class WebserviceException extends HttpException
{
public $httpStatus;
public $httpStatus;
public function __construct($message, $code, $httpStatus, $uri,
Exception $previous = null)
{
$this->httpStatus = $httpStatus;
parent::__construct($message, $code, $uri, $previous);
}
}
public function __construct(
$message,
$code,
$httpStatus,
$uri,
Exception $previous = null
) {
$this->httpStatus = $httpStatus;
parent::__construct($message, $code, $uri, $previous);
}
}
+42 -21
View File
@@ -4,28 +4,49 @@ namespace GeoIP2\Model;
class City extends Country
{
protected $city;
protected $location;
protected $postal;
protected $subdivisions = Array();
protected $city;
protected $location;
protected $postal;
protected $subdivisions = array();
public function __construct($raw, $languages)
{
parent::__construct($raw, $languages);
public function __construct($raw, $languages)
{
parent::__construct($raw, $languages);
$this->city = new \GeoIP2\Record\City($this->get('city'), $languages);
$this->location = new \GeoIP2\Record\Location($this->get('location'));
$this->postal = new \GeoIP2\Record\Postal($this->get('postal'));
$this->city = new \GeoIP2\Record\City($this->get('city'), $languages);
$this->location = new \GeoIP2\Record\Location($this->get('location'));
$this->postal = new \GeoIP2\Record\Postal($this->get('postal'));
$this->createSubdivisions($raw, $languages);
}
private function createSubdivisions($raw, $languages) {
if(!isset($raw['subdivisions'])) return;
foreach ($raw['subdivisions'] as $sub) {
array_push($this->subdivisions,
new \GeoIP2\Record\Subdivision($sub, $languages));
$this->createSubdivisions($raw, $languages);
}
}
}
private function createSubdivisions($raw, $languages)
{
if (!isset($raw['subdivisions'])) {
return;
}
foreach ($raw['subdivisions'] as $sub) {
array_push(
$this->subdivisions,
new \GeoIP2\Record\Subdivision($sub, $languages)
);
}
}
public function __get($attr)
{
if ($attr == 'mostSpecificSubdivision') {
return $this->$attr();
} else {
return parent::__get($attr);
}
}
private function mostSpecificSubdivision()
{
return empty($this->subdivisions)?
new \GeoIP2\Record\Subdivision(array(), $this->languages):
end($this->subdivisions);
}
}
+1 -2
View File
@@ -4,5 +4,4 @@ namespace GeoIP2\Model;
class CityIspOrg extends City
{
}
}
+41 -27
View File
@@ -4,36 +4,50 @@ namespace GeoIP2\Model;
class Country
{
private $continent;
private $country;
private $registeredCountry;
private $representedCountry;
private $traits;
private $raw;
private $continent;
private $country;
private $languages;
private $registeredCountry;
private $representedCountry;
private $traits;
private $raw;
public function __construct($raw, $languages) {
$this->raw = $raw;
public function __construct($raw, $languages)
{
$this->raw = $raw;
$this->continent = new \GeoIP2\Record\Continent($this->get('continent'),
$languages);
$this->country = new \GeoIP2\Record\Country($this->get('country'),
$languages);
$this->registeredCountry =
new \GeoIP2\Record\Country($this->get('registered_country'), $languages);
$this->representedCountry =
new \GeoIP2\Record\RepresentedCountry($this->get('represented_country'),
$languages);
$this->traits = new \GeoIP2\Record\Traits($this->get('traits'));
}
$this->continent = new \GeoIP2\Record\Continent(
$this->get('continent'),
$languages
);
$this->country = new \GeoIP2\Record\Country(
$this->get('country'),
$languages
);
$this->registeredCountry = new \GeoIP2\Record\Country(
$this->get('registered_country'),
$languages
);
$this->representedCountry = new \GeoIP2\Record\RepresentedCountry(
$this->get('represented_country'),
$languages
);
$this->traits = new \GeoIP2\Record\Traits($this->get('traits'));
protected function get($field) {
return isset($this->raw[$field]) ? $this->raw[$field] : Array();
}
$this->languages = $languages;
}
public function __get ($attr)
{
if ($attr != "instance" && isset($this->$attr)) return $this->$attr;
protected function get($field)
{
return isset($this->raw[$field]) ? $this->raw[$field] : array();
}
throw new \RuntimeException("Unknown attribute: $attr");
}
public function __get ($attr)
{
if ($attr != "instance" && isset($this->$attr)) {
return $this->$attr;
}
throw new \RuntimeException("Unknown attribute: $attr");
}
}
-1
View File
@@ -4,5 +4,4 @@ namespace GeoIP2\Model;
class Omni extends CityIspOrg
{
}
+22 -18
View File
@@ -4,25 +4,29 @@ namespace GeoIP2\Record;
abstract class AbstractPlaceRecord extends AbstractRecord
{
private $languages;
private $languages;
public function __construct($record, $languages){
$this->languages = $languages;
parent::__construct($record);
}
public function __get($attr) {
if ($attr == 'name') {
return $this->name();
} else {
return parent::__get($attr);
public function __construct($record, $languages)
{
$this->languages = $languages;
parent::__construct($record);
}
}
private function name() {
foreach($this->languages as $language) {
if (isset($this->names[$language])) return $this->names[$language];
public function __get($attr)
{
if ($attr == 'name') {
return $this->name();
} else {
return parent::__get($attr);
}
}
}
}
private function name()
{
foreach ($this->languages as $language) {
if (isset($this->names[$language])) {
return $this->names[$language];
}
}
}
}
+20 -18
View File
@@ -4,23 +4,25 @@ namespace GeoIP2\Record;
abstract class AbstractRecord
{
private $record;
private $record;
public function __construct($record) {
$this->record = $record;
}
public function __get($attr) {
$valid = in_array($attr, $this->validAttributes);
// XXX - kind of ugly but greatly reduces boilerplate code
$key = strtolower(preg_replace('/([A-Z])/', '_\1', $attr));
if ($valid && isset($this->record[$key])){
return $this->record[$key];
} elseif ($valid) {
return null;
} else {
throw new \RuntimeException("Unknown attribute: $attr");
public function __construct($record)
{
$this->record = $record;
}
}
}
public function __get($attr)
{
$valid = in_array($attr, $this->validAttributes);
// XXX - kind of ugly but greatly reduces boilerplate code
$key = strtolower(preg_replace('/([A-Z])/', '_\1', $attr));
if ($valid && isset($this->record[$key])) {
return $this->record[$key];
} elseif ($valid) {
return null;
} else {
throw new \RuntimeException("Unknown attribute: $attr");
}
}
}
+2 -2
View File
@@ -4,5 +4,5 @@ namespace GeoIP2\Record;
class City extends AbstractPlaceRecord
{
protected $validAttributes = Array('confidence', 'geonameId', 'names');
}
protected $validAttributes = array('confidence', 'geonameId', 'names');
}
+6 -4
View File
@@ -4,7 +4,9 @@ namespace GeoIP2\Record;
class Continent extends AbstractPlaceRecord
{
protected $validAttributes = Array('continentCode',
'geonameId',
'names');
}
protected $validAttributes = array(
'continentCode',
'geonameId',
'names'
);
}
+7 -6
View File
@@ -4,9 +4,10 @@ namespace GeoIP2\Record;
class Country extends AbstractPlaceRecord
{
protected $validAttributes = Array('confidence',
'geonameId',
'isoCode',
'names');
}
protected $validAttributes = array(
'confidence',
'geonameId',
'isoCode',
'names'
);
}
+10 -8
View File
@@ -4,11 +4,13 @@ namespace GeoIP2\Record;
class Location extends AbstractRecord
{
protected $validAttributes = Array('accuracyRadius',
'latitude',
'longitude',
'metroCode',
'postalCode',
'postalConfidence',
'timeZone');
}
protected $validAttributes = array(
'accuracyRadius',
'latitude',
'longitude',
'metroCode',
'postalCode',
'postalConfidence',
'timeZone'
);
}
+1 -1
View File
@@ -4,5 +4,5 @@ namespace GeoIP2\Record;
class Postal extends AbstractRecord
{
protected $validAttributes = Array('code', 'confidence');
protected $validAttributes = array('code', 'confidence');
}
+8 -6
View File
@@ -4,9 +4,11 @@ namespace GeoIP2\Record;
class RepresentedCountry extends Country
{
protected $validAttributes = Array('confidence',
'geonameId',
'isoCode',
'names',
'type');
}
protected $validAttributes = array(
'confidence',
'geonameId',
'isoCode',
'namespace',
'type'
);
}
+7 -5
View File
@@ -4,8 +4,10 @@ namespace GeoIP2\Record;
class Subdivision extends AbstractPlaceRecord
{
protected $validAttributes = Array('confidence',
'geonameId',
'isoCode',
'names');
}
protected $validAttributes = array(
'confidence',
'geonameId',
'isoCode',
'names'
);
}
+12 -11
View File
@@ -4,14 +4,15 @@ namespace GeoIP2\Record;
class Traits extends AbstractRecord
{
protected $validAttributes = Array('autonomousSystemNumber',
'autonomousSystemOrganization',
'domain',
'isAnonymousProxy',
'isSatelliteProvider',
'isp',
'ipAddress',
'organization',
'userType');
}
protected $validAttributes = array(
'autonomousSystemNumber',
'autonomousSystemOrganization',
'domain',
'isAnonymousProxy',
'isSatelliteProvider',
'isp',
'ipAddress',
'organization',
'userType'
);
}
+140 -110
View File
@@ -17,134 +17,164 @@ use Guzzle\Http\Exception\ServerErrorResponseException;
class Client
{
private $userId;
private $licenseKey;
private $languages;
private $baseUri = 'https://geoip.maxmind.com/geoip/v2.0';
private $guzzleClient;
private $userId;
private $licenseKey;
private $languages;
private $baseUri = 'https://geoip.maxmind.com/geoip/v2.0';
private $guzzleClient;
public function __construct($userId, $licenseKey, $languages=array('en'),
$guzzleClient = null)
{
$this->userId = $userId;
$this->licenseKey = $licenseKey;
$this->languages = $languages;
// To enable unit testing
$this->guzzleClient = $guzzleClient;
}
public function city($ipAddress = 'me')
{
return $this->responseFor('city', 'City', $ipAddress);
}
public function country($ipAddress = 'me')
{
return $this->responseFor('country', 'Country', $ipAddress);
}
public function cityIspOrg($ipAddress = 'me')
{
return $this->responseFor('city_isp_org', 'CityIspOrg', $ipAddress);
}
public function omni($ipAddress = 'me')
{
return $this->responseFor('omni', 'Omni', $ipAddress);
}
private function responseFor($path, $class, $ipAddress)
{
$uri = implode('/', array($this->baseUri, $path, $ipAddress));
$client = $this->guzzleClient ? $this->guzzleClient : new GuzzleClient();
$request = $client->get($uri, array('Accept' => 'application/json'));
$request->setAuth($this->userId, $this->licenseKey);
$ua = $request->getHeader('User-Agent');
$ua = "GeoIP2 PHP API ($ua)";
$request->setHeader('User-Agent', $ua);
$response = null;
try{
$response = $request->send();
}
catch (ClientErrorResponseException $e) {
$this->handle4xx($e->getResponse(), $uri);
}
catch (ServerErrorResponseException $e) {
$this->handle5xx($e->getResponse(), $uri);
public function __construct(
$userId,
$licenseKey,
$languages = array('en'),
$guzzleClient = null
) {
$this->userId = $userId;
$this->licenseKey = $licenseKey;
$this->languages = $languages;
// To enable unit testing
$this->guzzleClient = $guzzleClient;
}
if ($response && $response->isSuccessful()) {
$body = $this->handleSuccess($response, $uri);
$class = "GeoIP2\\Model\\" . $class;
return new $class($body, $this->languages);
}
else {
$this->handleNon200($response, $uri);
}
}
private function handleSuccess($response, $uri)
{
if ($response->getContentLength() == 0) {
throw new GenericException("Received a 200 response for $uri but did not receive a HTTP body.");
public function city($ipAddress = 'me')
{
return $this->responseFor('city', 'City', $ipAddress);
}
try {
return $response->json();
public function country($ipAddress = 'me')
{
return $this->responseFor('country', 'Country', $ipAddress);
}
catch (RuntimeException $e) {
throw new GenericException("Received a 200 response for $uri but could not decode the response as JSON: " . $e->getMessage());
public function cityIspOrg($ipAddress = 'me')
{
return $this->responseFor('city_isp_org', 'CityIspOrg', $ipAddress);
}
}
private function handle4xx($response, $uri)
{
$status = $response->getStatusCode();
public function omni($ipAddress = 'me')
{
return $this->responseFor('omni', 'Omni', $ipAddress);
}
$body = array();
private function responseFor($path, $class, $ipAddress)
{
$uri = implode('/', array($this->baseUri, $path, $ipAddress));
if ( $response->getContentLength() > 0 ) {
if( strstr($response->getContentType(), 'json')) {
$client = $this->guzzleClient ?
$this->guzzleClient : new GuzzleClient();
$request = $client->get($uri, array('Accept' => 'application/json'));
$request->setAuth($this->userId, $this->licenseKey);
$ua = $request->getHeader('User-Agent');
$ua = "GeoIP2 PHP API ($ua)";
$request->setHeader('User-Agent', $ua);
$response = null;
try {
$body = $response->json();
if (!isset($body['code']) || !isset($body['error']) ){
throw new GenericException('Response contains JSON but it does not specify code or error keys: ' . $response->getBody());
}
$response = $request->send();
} catch (ClientErrorResponseException $e) {
$this->handle4xx($e->getResponse(), $uri);
} catch (ServerErrorResponseException $e) {
$this->handle5xx($e->getResponse(), $uri);
}
catch (RuntimeException $e){
throw new HttpException("Received a $status error for $uri but it did not include the expected JSON body: " . $e->getMessage(), $status, $uri);
if ($response && $response->isSuccessful()) {
$body = $this->handleSuccess($response, $uri);
$class = "GeoIP2\\Model\\" . $class;
return new $class($body, $this->languages);
} else {
$this->handleNon200($response, $uri);
}
}
else {
throw new HttpException("Received a $status error for $uri with the following body: " . $response->getBody(),
$status, $uri);
}
}
else {
throw new HttpException("Received a $status error for $uri with no body",
$status, $uri);
}
throw new WebserviceException($body['error'], $body['code'], $status, $uri);
}
private function handleSuccess($response, $uri)
{
if ($response->getContentLength() == 0) {
throw new GenericException(
"Received a 200 response for $uri but did not " .
"receive a HTTP body."
);
}
private function handle5xx($response, $uri)
{
$status = $response->getStatusCode();
try {
return $response->json();
} catch (RuntimeException $e) {
throw new GenericException(
"Received a 200 response for $uri but could not decode " .
"the response as JSON: " . $e->getMessage()
);
throw new HttpException("Received a server error ($status) for $uri",
$status,$uri);
}
}
}
private function handleNon200($response, $uri)
{
$status = $response->getStatusCode();
private function handle4xx($response, $uri)
{
$status = $response->getStatusCode();
throw new HttpException("Received a very surprising HTTP status " .
"($status) for $uri",
$status, $uri);
}
$body = array();
if ($response->getContentLength() > 0) {
if (strstr($response->getContentType(), 'json')) {
try {
$body = $response->json();
if (!isset($body['code']) || !isset($body['error'])) {
throw new GenericException(
'Response contains JSON but it does not specify ' .
'code or error keys: ' . $response->getBody()
);
}
} catch (RuntimeException $e) {
throw new HttpException(
"Received a $status error for $uri but it did not " .
"include the expected JSON body: " .
$e->getMessage(),
$status,
$uri
);
}
} else {
throw new HttpException(
"Received a $status error for $uri with the " .
"following body: " . $response->getBody(),
$status,
$uri
);
}
} else {
throw new HttpException(
"Received a $status error for $uri with no body",
$status,
$uri
);
}
throw new WebserviceException(
$body['error'],
$body['code'],
$status,
$uri
);
}
private function handle5xx($response, $uri)
{
$status = $response->getStatusCode();
throw new HttpException(
"Received a server error ($status) for $uri",
$status,
$uri
);
}
private function handleNon200($response, $uri)
{
$status = $response->getStatusCode();
throw new HttpException(
"Received a very surprising HTTP status " .
"($status) for $uri",
$status,
$uri
);
}
}