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

View File

@ -6,7 +6,12 @@ php:
- 5.4
- 5.5
script: phpunit
before_install:
- pear install pear/PHP_CodeSniffer
script:
- phpcs --standard=PSR2 src/
- phpunit
notifications:
email:

4
README
View File

@ -58,6 +58,10 @@ SUPPORT
to the client API please see http://www.maxmind.com/en/support for
details.
CONTRIBUTING
Patches and pull requests are encouraged. All code should follow the
PSR-2 style guidelines. Please include unit tests whenever possible.
AUTHOR
Gregory Oschwald <goschwald@maxmind.com>

View File

@ -6,11 +6,13 @@ class HttpException extends \Exception
{
public $code;
public function __construct($message, $code, $uri,
Exception $previous = null)
{
public function __construct(
$message,
$code,
$uri,
Exception $previous = null
) {
$this->code = $code;
parent::__construct($message, null, $previous);
}
}

View File

@ -6,11 +6,14 @@ class WebserviceException extends HttpException
{
public $httpStatus;
public function __construct($message, $code, $httpStatus, $uri,
Exception $previous = null)
{
public function __construct(
$message,
$code,
$httpStatus,
$uri,
Exception $previous = null
) {
$this->httpStatus = $httpStatus;
parent::__construct($message, $code, $uri, $previous);
}
}

View File

@ -7,7 +7,7 @@ class City extends Country
protected $city;
protected $location;
protected $postal;
protected $subdivisions = Array();
protected $subdivisions = array();
public function __construct($raw, $languages)
{
@ -20,12 +20,33 @@ class City extends Country
$this->createSubdivisions($raw, $languages);
}
private function createSubdivisions($raw, $languages) {
if(!isset($raw['subdivisions'])) return;
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));
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);
}
}

View File

@ -4,5 +4,4 @@ namespace GeoIP2\Model;
class CityIspOrg extends City
{
}

View File

@ -6,33 +6,47 @@ class Country
{
private $continent;
private $country;
private $languages;
private $registeredCountry;
private $representedCountry;
private $traits;
private $raw;
public function __construct($raw, $languages) {
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->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->languages = $languages;
}
protected function get($field) {
return isset($this->raw[$field]) ? $this->raw[$field] : Array();
protected function get($field)
{
return isset($this->raw[$field]) ? $this->raw[$field] : array();
}
public function __get ($attr)
{
if ($attr != "instance" && isset($this->$attr)) return $this->$attr;
if ($attr != "instance" && isset($this->$attr)) {
return $this->$attr;
}
throw new \RuntimeException("Unknown attribute: $attr");
}

View File

@ -4,5 +4,4 @@ namespace GeoIP2\Model;
class Omni extends CityIspOrg
{
}

View File

@ -6,12 +6,14 @@ abstract class AbstractPlaceRecord extends AbstractRecord
{
private $languages;
public function __construct($record, $languages){
public function __construct($record, $languages)
{
$this->languages = $languages;
parent::__construct($record);
}
public function __get($attr) {
public function __get($attr)
{
if ($attr == 'name') {
return $this->name();
} else {
@ -19,10 +21,12 @@ abstract class AbstractPlaceRecord extends AbstractRecord
}
}
private function name() {
foreach($this->languages as $language) {
if (isset($this->names[$language])) return $this->names[$language];
private function name()
{
foreach ($this->languages as $language) {
if (isset($this->names[$language])) {
return $this->names[$language];
}
}
}
}

View File

@ -6,16 +6,18 @@ abstract class AbstractRecord
{
private $record;
public function __construct($record) {
public function __construct($record)
{
$this->record = $record;
}
public function __get($attr) {
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])){
if ($valid && isset($this->record[$key])) {
return $this->record[$key];
} elseif ($valid) {
return null;

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');
}

View File

@ -4,7 +4,9 @@ namespace GeoIP2\Record;
class Continent extends AbstractPlaceRecord
{
protected $validAttributes = Array('continentCode',
protected $validAttributes = array(
'continentCode',
'geonameId',
'names');
'names'
);
}

View File

@ -4,9 +4,10 @@ namespace GeoIP2\Record;
class Country extends AbstractPlaceRecord
{
protected $validAttributes = Array('confidence',
protected $validAttributes = array(
'confidence',
'geonameId',
'isoCode',
'names');
'names'
);
}

View File

@ -4,11 +4,13 @@ namespace GeoIP2\Record;
class Location extends AbstractRecord
{
protected $validAttributes = Array('accuracyRadius',
protected $validAttributes = array(
'accuracyRadius',
'latitude',
'longitude',
'metroCode',
'postalCode',
'postalConfidence',
'timeZone');
'timeZone'
);
}

View File

@ -4,5 +4,5 @@ namespace GeoIP2\Record;
class Postal extends AbstractRecord
{
protected $validAttributes = Array('code', 'confidence');
protected $validAttributes = array('code', 'confidence');
}

View File

@ -4,9 +4,11 @@ namespace GeoIP2\Record;
class RepresentedCountry extends Country
{
protected $validAttributes = Array('confidence',
protected $validAttributes = array(
'confidence',
'geonameId',
'isoCode',
'names',
'type');
'namespace',
'type'
);
}

View File

@ -4,8 +4,10 @@ namespace GeoIP2\Record;
class Subdivision extends AbstractPlaceRecord
{
protected $validAttributes = Array('confidence',
protected $validAttributes = array(
'confidence',
'geonameId',
'isoCode',
'names');
'names'
);
}

View File

@ -4,7 +4,8 @@ namespace GeoIP2\Record;
class Traits extends AbstractRecord
{
protected $validAttributes = Array('autonomousSystemNumber',
protected $validAttributes = array(
'autonomousSystemNumber',
'autonomousSystemOrganization',
'domain',
'isAnonymousProxy',
@ -12,6 +13,6 @@ class Traits extends AbstractRecord
'isp',
'ipAddress',
'organization',
'userType');
'userType'
);
}

View File

@ -23,9 +23,12 @@ class Client
private $baseUri = 'https://geoip.maxmind.com/geoip/v2.0';
private $guzzleClient;
public function __construct($userId, $licenseKey, $languages=array('en'),
$guzzleClient = null)
{
public function __construct(
$userId,
$licenseKey,
$languages = array('en'),
$guzzleClient = null
) {
$this->userId = $userId;
$this->licenseKey = $licenseKey;
$this->languages = $languages;
@ -57,7 +60,8 @@ class Client
{
$uri = implode('/', array($this->baseUri, $path, $ipAddress));
$client = $this->guzzleClient ? $this->guzzleClient : new GuzzleClient();
$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');
@ -65,13 +69,11 @@ class Client
$request->setHeader('User-Agent', $ua);
$response = null;
try{
try {
$response = $request->send();
}
catch (ClientErrorResponseException $e) {
} catch (ClientErrorResponseException $e) {
$this->handle4xx($e->getResponse(), $uri);
}
catch (ServerErrorResponseException $e) {
} catch (ServerErrorResponseException $e) {
$this->handle5xx($e->getResponse(), $uri);
}
@ -79,8 +81,7 @@ class Client
$body = $this->handleSuccess($response, $uri);
$class = "GeoIP2\\Model\\" . $class;
return new $class($body, $this->languages);
}
else {
} else {
$this->handleNon200($response, $uri);
}
}
@ -88,14 +89,19 @@ class Client
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.");
throw new GenericException(
"Received a 200 response for $uri but did not " .
"receive a HTTP body."
);
}
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());
} catch (RuntimeException $e) {
throw new GenericException(
"Received a 200 response for $uri but could not decode " .
"the response as JSON: " . $e->getMessage()
);
}
}
@ -106,45 +112,69 @@ class Client
$body = array();
if ( $response->getContentLength() > 0 ) {
if( strstr($response->getContentType(), 'json')) {
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());
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
);
}
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 the following body: " . $response->getBody(),
$status, $uri);
}
}
else {
throw new HttpException("Received a $status error for $uri with no body",
$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);
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);
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 " .
throw new HttpException(
"Received a very surprising HTTP status " .
"($status) for $uri",
$status, $uri);
$status,
$uri
);
}
}

View File

@ -30,38 +30,66 @@ class CountryTest extends \PHPUnit_Framework_TestCase
private $model;
public function setUp () {
public function setUp ()
{
$this->model = new Country($this->raw, ['en']);
}
public function testObjects () {
$this->assertInstanceOf('GeoIP2\Model\Country', $this->model,
'minimal GeoIP2::Model::Country object');
$this->assertInstanceOf('GeoIP2\Record\Continent', $this->model->continent);
$this->assertInstanceOf('GeoIP2\Record\Country', $this->model->country);
$this->assertInstanceOf('GeoIP2\Record\Country', $this->model->registeredCountry);
$this->assertInstanceOf('GeoIP2\Record\RepresentedCountry',
$this->model->representedCountry);
$this->assertInstanceOf('GeoIP2\Record\Traits', $this->model->traits);
public function testObjects ()
{
$this->assertInstanceOf(
'GeoIP2\Model\Country',
$this->model,
'minimal GeoIP2::Model::Country object'
);
$this->assertInstanceOf(
'GeoIP2\Record\Continent',
$this->model->continent
);
$this->assertInstanceOf(
'GeoIP2\Record\Country',
$this->model->country
);
$this->assertInstanceOf(
'GeoIP2\Record\Country',
$this->model->registeredCountry
);
$this->assertInstanceOf(
'GeoIP2\Record\RepresentedCountry',
$this->model->representedCountry
);
$this->assertInstanceOf(
'GeoIP2\Record\Traits',
$this->model->traits
);
}
public function testValues() {
public function testValues()
{
$this->assertEquals(42, $this->model->continent->geonameId,
'continent geoname_id is 42');
$this->assertEquals(
42,
$this->model->continent->geonameId,
'continent geoname_id is 42'
);
$this->assertEquals('NA', $this->model->continent->continentCode,
'continent continent_code is NA');
$this->assertEquals(
'NA',
$this->model->continent->continentCode,
'continent continent_code is NA'
);
$this->assertEquals(array( 'en' => 'North America' ),
$this->assertEquals(
array( 'en' => 'North America' ),
$this->model->continent->names,
'continent names');
'continent names'
);
$this->assertEquals(
'North America',
$this->model->continent->name,
'continent name is North America');
'continent name is North America'
);
$this->assertEquals(
1,
@ -78,7 +106,7 @@ class CountryTest extends \PHPUnit_Framework_TestCase
$this->assertEquals(
array( 'en' => 'United States of America' ),
$this->model->country->names,
'country names'
'country name'
);
$this->assertEquals(
@ -93,11 +121,14 @@ class CountryTest extends \PHPUnit_Framework_TestCase
'country confidence is undef'
);
$this->assertEquals(2, $this->model->registeredCountry->geonameId,
$this->assertEquals(
2,
$this->model->registeredCountry->geonameId,
'registered_country geoname_id is 2'
);
$this->assertEquals('CA',
$this->assertEquals(
'CA',
$this->model->registeredCountry->isoCode,
'registered_country iso_code is CA'
);
@ -115,8 +146,9 @@ class CountryTest extends \PHPUnit_Framework_TestCase
);
foreach (array( 'isAnonymousProxy', 'isSatelliteProvider' ) as $meth) {
$this->assertEquals(0, $this->model->traits->$meth,
$this->assertEquals(
0,
$this->model->traits->$meth,
"traits $meth returns 0 by default"
);
}

View File

@ -28,7 +28,8 @@ class ClientTest extends \PHPUnit_Framework_TestCase
);
private function getResponse($ip) {
private function getResponse($ip)
{
$responses = array(
'1.2.3.4' => $this->response(
'country',
@ -43,7 +44,8 @@ class ClientTest extends \PHPUnit_Framework_TestCase
'1.2.3.5' => $this->response('country', 200),
'2.2.3.5' => $this->response('country', 200, 'bad body'),
'1.2.3.6'=> $this->response(
'error', 400,
'error',
400,
array(
'code' => 'IP_ADDRESS_INVALID',
'error' => 'The value "1.2.3" is not a valid ip address'
@ -83,44 +85,71 @@ class ClientTest extends \PHPUnit_Framework_TestCase
return $responses[$ip];
}
public function testCountry() {
$country = $this->client($this->getResponse('1.2.3.4'))->country('1.2.3.4' );
public function testCountry()
{
$country = $this->client($this->getResponse('1.2.3.4'))
->country('1.2.3.4');
$this->assertInstanceOf('GeoIP2\Model\Country', $country);
$this->assertEquals(42, $country->continent->geonameId,
'continent geoname_id is 42');
$this->assertEquals(
42,
$country->continent->geonameId,
'continent geoname_id is 42'
);
$this->assertEquals('NA', $country->continent->continentCode,
'continent continent_code is NA');
$this->assertEquals(
'NA',
$country->continent->continentCode,
'continent continent_code is NA'
);
$this->assertEquals(array('en' => 'North America'),
$country->continent->names, 'continent names');
$this->assertEquals(
array('en' => 'North America'),
$country->continent->names,
'continent names'
);
$this->assertEquals('North America', $country->continent->name,
'continent name is North America');
$this->assertEquals(
'North America',
$country->continent->name,
'continent name is North America'
);
$this->assertEquals(1, $country->country->geonameId,
'country geoname_id is 1');
$this->assertEquals(
1,
$country->country->geonameId,
'country geoname_id is 1'
);
$this->assertEquals('US', $country->country->isoCode,
'country iso_code is US');
$this->assertEquals(
'US',
$country->country->isoCode,
'country iso_code is US'
);
$this->assertEquals(array( 'en' => 'United States of America' ),
$country->country->names, 'country names');
$this->assertEquals(
array( 'en' => 'United States of America' ),
$country->country->names,
'country names'
);
$this->assertEquals('United States of America',
$this->assertEquals(
'United States of America',
$country->country->name,
'country name is United States of America');
'country name is United States of America'
);
}
public function testMe()
{
$client = $this->client($this->getResponse('me'));
$this->assertInstanceOf('GeoIP2\Model\CityIspOrg',
$client->cityIspOrg('me' ),
'can set ip parameter to me');
$this->assertInstanceOf(
'GeoIP2\Model\CityIspOrg',
$client->cityIspOrg('me'),
'can set ip parameter to me'
);
}
/**
@ -169,7 +198,6 @@ class ClientTest extends \PHPUnit_Framework_TestCase
$client = $this->client($this->getResponse('1.2.3.7'));
$client->country('1.2.3.7');
}
/**
@ -231,67 +259,86 @@ class ClientTest extends \PHPUnit_Framework_TestCase
public function test406Exception()
{
$client = $this->client($this->getResponse('1.2.3.12'));
$client->country('1.2.3.12');
}
public function testParams() {
public function testParams()
{
$plugin = new MockPlugin();
$plugin->addResponse($this->getResponse('1.2.3.4'));
$guzzleClient = new GuzzleClient();
$guzzleClient->addSubscriber($plugin);
$client = new Client(42, 'abcdef123456', array('en'),
$guzzleClient);
$client = new Client(
42,
'abcdef123456',
array('en'),
$guzzleClient
);
$client->country('1.2.3.4');
$request = $plugin->getReceivedRequests()[0];
$this->assertEquals('https://geoip.maxmind.com/geoip/v2.0/country/1.2.3.4',
$this->assertEquals(
'https://geoip.maxmind.com/geoip/v2.0/country/1.2.3.4',
$request->getUrl(),
'got expected URI for Country request');
$this->assertEquals('GET', $request->getMethod(), 'request is a GET');
'got expected URI for Country request'
);
$this->assertEquals(
'GET',
$request->getMethod(),
'request is a GET'
);
$this->assertEquals('application/json', $request->getHeader('Accept'),
'request sets Accept header to application/json');
$this->assertEquals(
'application/json',
$request->getHeader('Accept'),
'request sets Accept header to application/json'
);
$this->assertStringMatchesFormat('GeoIP2 PHP API (Guzzle%s)',
$this->assertStringMatchesFormat(
'GeoIP2 PHP API (Guzzle%s)',
$request->getHeader('User-Agent') . '',
'request sets Accept header to application/json');
'request sets Accept header to application/json'
);
}
private function client($response, $languages=array('en')) {
private function client($response, $languages = array('en'))
{
$plugin = new MockPlugin();
$plugin->addResponse($response);
$guzzleClient = new GuzzleClient();
$guzzleClient->addSubscriber($plugin);
$client = new Client(42, 'abcdef123456', $languages,
$guzzleClient);
$client = new Client(
42,
'abcdef123456',
$languages,
$guzzleClient
);
return $client;
}
private function response($endpoint, $status, $body=null,
$bad=null, $contentType=null)
{
$headers = Array();
if( $contentType) {
private function response(
$endpoint,
$status,
$body = null,
$bad = null,
$contentType = null
) {
$headers = array();
if ($contentType) {
$headers['Content-Type'] = $contentType;
}
elseif ( $status == 200 || ( $status >= 400 && $status < 500 ) ) {
} elseif ($status == 200 || ( $status >= 400 && $status < 500 )) {
$headers['Content-Type'] = 'application/vnd.maxmind.com-'
. $endpoint . '+json; charset=UTF-8; version=1.0;';
}
if ($bad) {
$body = '{ invalid: }';
}
elseif (is_array($body)) {
} elseif (is_array($body)) {
$body = json_encode($body);
}
@ -302,6 +349,6 @@ class ClientTest extends \PHPUnit_Framework_TestCase
public function testTest()
{
$this->assertEquals(1,1);
$this->assertEquals(1, 1);
}
}

View File

@ -5,4 +5,3 @@ if (!$loader = @include __DIR__.'/../vendor/autoload.php') {
}
$loader->add('GeoIP2\Test', __DIR__);