43 Commits

Author SHA1 Message Date
Gregory Oschwald
7fa971aef8 Updated .gitignore 2013-10-21 11:15:22 -07:00
Gregory Oschwald
edb6940c74 Updated exception text in test 2013-10-21 11:09:27 -07:00
Gregory Oschwald
57cb77a53c Updated version in example composer.json 2013-10-21 11:04:28 -07:00
Gregory Oschwald
8aedaa5f91 Doc updates 2013-10-21 11:03:02 -07:00
Gregory Oschwald
87f6e2ad6b Require new version of MaxMind DB API 2013-10-21 11:00:02 -07:00
Gregory Oschwald
6bcd0ab21e Removed Get Satisfaction link 2013-10-21 09:10:03 -07:00
Gregory Oschwald
e03b9558a9 Tidying and doc fixes 2013-10-21 06:18:12 -07:00
Gregory Oschwald
234dcaff7c Renamed languages to locales in the code 2013-10-17 12:58:21 -07:00
Gregory Oschwald
b8188bc558 language code -> locale code 2013-10-17 10:28:31 -07:00
Gregory Oschwald
8f16ed6115 Merge branch 'leading-backslash' of github.com:BenMorel/GeoIP2-php into BenMorel-leading-backslash 2013-10-16 10:45:50 -07:00
Gregory Oschwald
8f3331002a Merge branch 'unused-imports' of github.com:BenMorel/GeoIP2-php into BenMorel-unused-imports 2013-10-16 10:43:47 -07:00
Benjamin Morel
b4b0341307 Fixed typo in exception names 2013-10-16 17:33:29 +00:00
Benjamin Morel
ee00329652 Removed unused imports 2013-10-16 17:30:18 +00:00
Benjamin Morel
e8fa9a3a24 Removed the leading backslash on imports 2013-10-16 17:27:40 +00:00
Gregory Oschwald
167433de0c Added iterface for Reader/Client.
It could use a better name.
2013-10-02 06:54:03 -07:00
Gregory Oschwald
c584dbfd6b Added more info to comment 2013-09-19 08:07:24 -07:00
Gregory Oschwald
c642a32b0c Added some comments in examples 2013-09-19 07:52:44 -07:00
Gregory Oschwald
decfda7e90 Added missing documentation on $languages param 2013-08-02 13:34:53 -07:00
Gregory Oschwald
3a560452af Added more detailed examples 2013-08-02 13:32:21 -07:00
Gregory Oschwald
8febab1fe4 Updates for v0.4.0 release 2013-07-16 12:40:34 -07:00
Gregory Oschwald
f0430b613d No reason for call_user_func_array 2013-07-16 10:34:44 -07:00
Gregory Oschwald
e3289ec416 Fix for PHP 5.3 where you can't use '$this' in a callback. 2013-07-16 10:11:06 -07:00
Gregory Oschwald
1d1dcec74c Added missing method documentation 2013-07-16 09:48:45 -07:00
Gregory Oschwald
630765f924 Make unit tests check all the methods 2013-07-16 09:44:30 -07:00
Gregory Oschwald
b55d42b5cd Documentation updates 2013-07-16 09:21:08 -07:00
Gregory Oschwald
044ca4d085 Added specific exceptions for the different types of errors. 2013-07-16 07:46:50 -07:00
Gregory Oschwald
3ba84992c8 Updated for new test path 2013-07-15 16:10:05 -07:00
Gregory Oschwald
a6c1f9378e Updated submodule 2013-07-15 16:09:31 -07:00
Gregory Oschwald
1c0817d133 Test looking up an invalid address 2013-07-15 16:05:08 -07:00
Gregory Oschwald
59a51ef34d Tests for the reader 2013-07-15 15:52:07 -07:00
Gregory Oschwald
3e0fc2a837 Basic GeoIP2 database reader 2013-07-15 15:06:51 -07:00
Gregory Oschwald
c898f76a50 Release of 0.3.0 with updated namespace 2013-07-12 07:01:27 -07:00
Gregory Oschwald
8a265a763e Remove HipChat notifications due to popular demand. 2013-07-12 07:00:48 -07:00
Gregory Oschwald
3579ce7297 Doc updates plus HipChat notification 2013-07-10 19:25:09 -07:00
Gregory Oschwald
aa88c3040f Fixed a couple of incorrect case changes 2013-07-10 15:35:09 -07:00
Gregory Oschwald
5df4bbee47 Fix composer file 2013-07-10 15:30:33 -07:00
Gregory Oschwald
e60181f13a Rename GeoIP2 => GeoIp2 for consistency 2013-07-10 15:24:40 -07:00
Gregory Oschwald
1c37dcac03 Updated change log 2013-06-10 09:44:28 -07:00
Gregory Oschwald
f4898f7f90 Added beta note with a link to our website and GetSatisfaction 2013-06-06 09:28:51 -07:00
Olaf Alders
6f85654820 s/associated the IP/associated with the IP/ 2013-05-29 16:36:25 -04:00
Olaf Alders
fc74279d11 s/block in/block/ 2013-05-29 15:55:55 -04:00
Olaf Alders
b8aa4bc429 Update versioning copy 2013-05-29 15:52:47 -04:00
Gregory Oschwald
d9a87dd5bd Updated version in Composer example 2013-05-29 07:43:44 -07:00
39 changed files with 927 additions and 375 deletions

2
.gitignore vendored
View File

@@ -1,8 +1,10 @@
_site
.gh-pages
.idea
composer.lock
composer.phar
phpunit.xml
geoip2-php.sublime-*
vendor/
*.sw?
t.php

3
.gitmodules vendored Normal file
View File

@@ -0,0 +1,3 @@
[submodule "maxmind-db"]
path = maxmind-db
url = git://github.com/maxmind/MaxMind-DB.git

View File

@@ -1,24 +1,53 @@
CHANGELOG
=========
0.5.0 (2013-10-21)
------------------
* Renamed $languages constructor parameters to $locales for both the Client
and Reader classes.
* Documentation and code clean-up (Ben Morel).
* Added the interface `GeoIp2\ProviderInterface`, which is implemented by both
`\GeoIp2\Database\Reader` and `\GeoIp2\WebService\Client`.
0.4.0 (2013-07-16)
------------------
* This is the first release with the GeoIP2 database reader. Please see the
`README.md` file and the `\GeoIp2\Database\Reader` class.
* The general exception classes were replaced with specific exception classes
representing particular types of errors, such as an authentication error.
0.3.0 (2013-07-12)
------------------
* In namespaces and class names, "GeoIP2" was renamed to "GeoIp2" to improve
consistency.
0.2.1 (2013-06-10)
------------------
* First official beta release.
* Documentation updates and corrections.
0.2.0 (2013-05-29)
------------------
* `GenericException` was renamed to `GeoIP2Exception`.
* We now support more languages. The new languages are de, es, fr, and pt-BR.
* The REST API now returns a record with data about your account. There is
a new geoip.records.MaxMind class for this data.
a new `GeoIP\Records\MaxMind` class for this data.
* The `continentCode` attribute on `Continent` was renamed to `code`.
* Documentation updates.
0.1.1 (2013-05-14)
------------------
* Updated Guzzle version requirement
* Fixed Composer example in README.md
* Updated Guzzle version requirement.
* Fixed Composer example in README.md.
0.1.0 (2013-05-13)
------------------
* Initial release
* Initial release.

154
README.md
View File

@@ -1,32 +1,31 @@
# GeoIP2 PHP API #
**NOTE**: This is an alpha release. The API may change before the final
production release. The first production release will have the version
number 2.0.0.
## Beta Note ##
This is a beta release. The API may change before the first production
release, which will be numbered 2.0.0.
You may find information on the GeoIP2 beta release process on [our
website](http://www.maxmind.com/en/geoip2_beta).
## Description ##
Currently, this distribution provides an API for the [GeoIP2 web services]
(http://dev.maxmind.com/geoip/geoip2/web-services).
In the future, this distribution will also provide the same API for the
GeoIP2 downloadable databases. These databases have not yet been
released as a downloadable product.
See ``GeoIP2\WebService\Client`` for details on the web service client
API.
This distribution provides an API for the [GeoIP2 web services]
(http://dev.maxmind.com/geoip/geoip2/web-services) and the [GeoLite2
databases](http://dev.maxmind.com/geoip/geoip2/geolite2/). The commercial
GeoIP2 databases have not yet been released as a downloadable product.
## Installation ##
### Define Your Dependencies ###
We recommend installing this package with [Composer](http://getcomposer.org/).
To do this, add ```geoip2/geoip2``` to your ```composer.json``` file.
To do this, add `geoip2/geoip2` to your `composer.json` file.
```json
{
"require": {
"geoip2/geoip2": "0.1.*"
"geoip2/geoip2": "0.5.*"
}
}
```
@@ -54,10 +53,71 @@ You can autoload all dependencies by adding this to your code:
require 'vendor/autoload.php';
```
## Usage ##
### Optional C Extension ###
To use this API, you must create a new ``\GeoIP2\WebService\Client``
object with your ``$userId`` and ``$licenseKey``, then you call the method
The [MaxMind DB API](https://github.com/maxmind/MaxMind-DB-Reader-php)
includes an optional C extension that you may install to dramatically increase
the performance of lookups in GeoIP2 or GeoLite2 databases. To install, please
follow the instructions included with that API.
The extension has no effect on web-service lookups.
## Database Reader ##
### Usage ###
To use this API, you must create a new `\GeoIp2\Database\Reader` object with
the path to the database file as the first argument to the constructor. You
may then call the method corresponding to the database you are using.
If the lookup succeeds, the method call will return a model class for the
record in the database. This model in turn contains multiple container
classes for the different parts of the data such as the city in which the
IP address is located.
If the record is not found, a `\GeoIp2\Exception\AddressNotFoundException`
is returned. If the database is invalid or corrupt, a
`\MaxMind\Db\InvalidDatabaseException` will be thrown.
See the API documentation for more details.
### Example ###
```php
<?php
require_once 'vendor/autoload.php';
use GeoIp2\Database\Reader;
// This creates the Reader object, which should be reused across
// lookups.
$reader = new Reader('/usr/local/share/GeoIP/GeoIP2-City.mmdb');
// Replace "city" with the appropriate method for your database, e.g.,
// "country".
$record = $reader->city('128.101.101.101');
print($record->country->isoCode . "\n"); // 'US'
print($record->country->name . "\n"); // 'United States'
print($record->country->names['zh-CN'] . "\n"); // '美国'
print($record->mostSpecificSubdivision->name . "\n"); // 'Minnesota'
print($record->mostSpecificSubdivision->isoCode . "\n"); // 'MN'
print($record->city->name . "\n"); // 'Minneapolis'
print($record->postal->code . "\n"); // '55455'
print($record->location->latitude . "\n"); // 44.9733
print($record->location->longitude . "\n"); // -93.2323
```
## Web Service Client ##
### Usage ###
To use this API, you must create a new `\GeoIp2\WebService\Client`
object with your `$userId` and `$licenseKey`, then you call the method
corresponding to a specific end point, passing it the IP address you want to
look up.
@@ -65,41 +125,43 @@ If the request succeeds, the method call will return a model class for the end
point you called. This model in turn contains multiple record classes, each of
which represents part of the data returned by the web service.
If there is an error, a structured exception is thrown.
See the API documentation for more details.
## Example ##
### Example ###
```php
<?php
require_once 'vendor/autoload.php';
use \GeoIP2\WebService\Client;
use GeoIp2\WebService\Client;
// This creates a Client object that can be reused across requests.
// Replace "42" with your user ID and "license_key" with your license
// key.
$client = new Client(42, 'abcdef123456');
$omni = $client->omni('24.24.24.24');
echo $omni->country->isoCode;
// Replace "city" with the method corresponding to the web service that
// you are using, e.g., "country", "cityIspOrg", "omni".
$record = $client->city('128.101.101.101');
print($record->country->isoCode . "\n"); // 'US'
print($record->country->name . "\n"); // 'United States'
print($record->country->names['zh-CN'] . "\n"); // '美国'
print($record->mostSpecificSubdivision->name . "\n"); // 'Minnesota'
print($record->mostSpecificSubdivision->isoCode . "\n"); // 'MN'
print($record->city->name . "\n"); // 'Minneapolis'
print($record->postal->code . "\n"); // '55455'
print($record->location->latitude . "\n"); // 44.9733
print($record->location->longitude . "\n"); // -93.2323
```
## Exceptions ##
For details on the possible errors returned by the web service itself, see
the
[GeoIP2 web service docs](http://dev.maxmind.com/geoip2/geoip/web-service).
If the web service returns an explicit error document, this is thrown as a
```\GeoIP2\Exception\WebServiceException```. If some other sort of transport
error occurs, this is thrown as a ```\GeoIP2\Exception\HttpException```.
The difference is that the web service error includes an error message and
error code delivered by the web service. The latter is thrown when some sort
of unanticipated error occurs, such as the web service returning a 500 or an
invalid error document.
If the web service returns any status code besides 200, 4xx, or 5xx, this also
becomes a ```\GeoIP2\Exception\HttpException```.
Finally, if the web service returns a 200 but the body is invalid, the client
throws a ```\GeoIP2\Exception\GeoIP2Exception```.
## What data is returned? ##
### What data is returned? ###
While many of the end points return the same basic records, the attributes
which can be populated vary between end points. In addition, while an end
@@ -113,8 +175,8 @@ See the
[GeoIP2 web service docs](http://dev.maxmind.com/geoip/geoip2/web-services)
for details on what data each end point may return.
The only piece of data which is always returned is the ```ipAddress```
attribute in the ``GeoIP2\Record\Traits`` record.
The only piece of data which is always returned is the `ipAddress`
attribute in the `GeoIp2\Record\Traits` record.
Every record class attribute has a corresponding predicate method so you can
check to see if the attribute is set.
@@ -124,10 +186,10 @@ check to see if the attribute is set.
[GeoNames](http://www.geonames.org/) offers web services and downloadable
databases with data on geographical features around the world, including
populated places. They offer both free and paid premium data. Each
feature is unique identified by a ```geonameId```, which is an integer.
feature is unique identified by a `geonameId`, which is an integer.
Many of the records returned by the GeoIP2 web services and databases
include a ```geonameId``` property. This is the ID of a geographical feature
include a `geonameId` property. This is the ID of a geographical feature
(city, region, country, etc.) in the GeoNames database.
Some of the data that MaxMind provides is also sourced from GeoNames. We

View File

@@ -58,6 +58,6 @@ git push git@github.com:maxmind/GeoIP2-php.git
git push
cd ..
git tag $TAG
git tag -a $TAG
git push
git push --tags

View File

@@ -14,6 +14,7 @@
],
"require": {
"guzzle/guzzle": "3.*",
"maxmind-db/reader": "0.2.*",
"php": ">=5.3.1"
},
"require-dev": {
@@ -21,6 +22,6 @@
"satooshi/php-coveralls": "dev-master"
},
"autoload": {
"psr-0": { "GeoIP2": "src/" }
"psr-0": { "GeoIp2": "src/" }
}
}

1
maxmind-db Submodule

Submodule maxmind-db added at f7b9342b84

View File

@@ -3,13 +3,13 @@
<phpunit bootstrap="./tests/bootstrap.php" colors="true">
<testsuites>
<testsuite name="GeoIP2 Test Suite">
<directory suffix="Test.php">./tests/GeoIP2/Test/</directory>
<directory suffix="Test.php">./tests/GeoIp2/Test/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">./src/GeoIP2/</directory>
<directory suffix=".php">./src/GeoIp2/</directory>
</whitelist>
</filter>

View File

@@ -1,10 +0,0 @@
<?php
namespace GeoIP2\Exception;
/**
* This class represents a generic error.
*/
class GeoIP2Exception extends \Exception
{
}

View File

@@ -0,0 +1,149 @@
<?php
namespace GeoIp2\Database;
use GeoIp2\Exception\AddressNotFoundException;
use GeoIp2\ProviderInterface;
use MaxMind\Db\Reader as DbReader;
/**
* Instances of this class provide a reader for the GeoIP2 database format.
* IP addresses can be looked up using the <code>country</code>
* and <code>city</code> methods. We also provide <code>cityIspOrg</code>
* and <code>omni</code> methods to ease compatibility with the web service
* client, although we may offer the ability to specify additional databases
* to replicate these web services in the future (e.g., the ISP/Org database).
*
* **Usage**
*
* The basic API for this class is the same for every database. First, you
* create a reader object, specifying a file name. You then call the method
* corresponding to the specific database, passing it the IP address you want
* to look up.
*
* If the request succeeds, the method call will return a model class for
* the method you called. This model in turn contains multiple record classes,
* each of which represents part of the data returned by the database. If
* the database does not contain the requested information, the attributes
* on the record class will have a <code>null</code> value.
*
* If the address is not in the database, an
* {@link \GeoIp2\Exception\AddressNotFoundException} exception will be
* thrown. If an invalid IP address is passed to one of the methods, a
* SPL {@link \InvalidArgumentException} will be thrown. If the database is
* corrupt or invalid, a {@link \MaxMind\Db\Reader\InvalidDatabaseException}
* will be thrown.
*
*/
class Reader implements ProviderInterface
{
private $dbReader;
private $locales;
/**
* Constructor.
*
* @param string $filename The path to the GeoIP2 database file.
* @param array $locales List of locale codes to use in name property
* from most preferred to least preferred.
* @throws \MaxMind\Db\Reader\InvalidDatabaseException if the database
* is corrupt or invalid
*/
public function __construct(
$filename,
$locales = array('en')
) {
$this->dbReader = new DbReader($filename);
$this->locales = $locales;
}
/**
* This method returns a GeoIP2 City model.
*
* @param string $ipAddress IPv4 or IPv6 address as a string.
*
* @return \GeoIp2\Model\City
*
* @throws \GeoIp2\Exception\AddressNotFoundException if the address is
* not in the database.
* @throws \MaxMind\Db\Reader\InvalidDatabaseException if the database
* is corrupt or invalid
*/
public function city($ipAddress)
{
return $this->modelFor('City', $ipAddress);
}
/**
* This method returns a GeoIP2 Country model.
*
* @param string $ipAddress IPv4 or IPv6 address as a string.
*
* @return \GeoIp2\Model\Country
*
* @throws \GeoIp2\Exception\AddressNotFoundException if the address is
* not in the database.
* @throws \MaxMind\Db\Reader\InvalidDatabaseException if the database
* is corrupt or invalid
*/
public function country($ipAddress)
{
return $this->modelFor('Country', $ipAddress);
}
/**
* This method returns a GeoIP2 City/ISP/Org model.
*
* @param string $ipAddress IPv4 or IPv6 address as a string.
*
* @return \GeoIp2\Model\CityIspOrg
*
* @throws \GeoIp2\Exception\AddressNotFoundException if the address is
* not in the database.
* @throws \MaxMind\Db\Reader\InvalidDatabaseException if the database
* is corrupt or invalid
*/
public function cityIspOrg($ipAddress)
{
return $this->modelFor('CityIspOrg', $ipAddress);
}
/**
* This method returns a GeoIP2 Omni model.
*
* @param string $ipAddress IPv4 or IPv6 address as a string.
*
* @return \GeoIp2\Model\Omni
*
* @throws \GeoIp2\Exception\AddressNotFoundException if the address is
* not in the database.
* @throws \MaxMind\Db\Reader\InvalidDatabaseException if the database
* is corrupt or invalid
*/
public function omni($ipAddress)
{
return $this->modelFor('Omni', $ipAddress);
}
private function modelFor($class, $ipAddress)
{
$record = $this->dbReader->get($ipAddress);
if ($record === null) {
throw new AddressNotFoundException(
"The address $ipAddress is not in the database."
);
}
$record['traits']['ip_address'] = $ipAddress;
$class = "GeoIp2\\Model\\" . $class;
return new $class($record, $this->locales);
}
/**
* Closes the GeoIP2 database and returns the resources to the system.
*/
public function close()
{
$this->dbReader->close();
}
}

View File

@@ -0,0 +1,10 @@
<?php
namespace GeoIp2\Exception;
/**
* This class represents a generic error.
*/
class AddressNotFoundException extends GeoIp2Exception
{
}

View File

@@ -0,0 +1,10 @@
<?php
namespace GeoIp2\Exception;
/**
* This class represents a generic error.
*/
class AuthenticationException extends GeoIp2Exception
{
}

View File

@@ -0,0 +1,10 @@
<?php
namespace GeoIp2\Exception;
/**
* This class represents a generic error.
*/
class GeoIp2Exception extends \Exception
{
}

View File

@@ -1,12 +1,12 @@
<?php
namespace GeoIP2\Exception;
namespace GeoIp2\Exception;
/**
* This class represents an HTTP transport error.
*/
class HttpException extends GeoIP2Exception
class HttpException extends GeoIp2Exception
{
/**
* The URI queried
@@ -17,7 +17,7 @@ class HttpException extends GeoIP2Exception
$message,
$httpStatus,
$uri,
Exception $previous = null
\Exception $previous = null
) {
$this->uri = $uri;
parent::__construct($message, $httpStatus, $previous);

View File

@@ -1,12 +1,12 @@
<?php
namespace GeoIP2\Exception;
namespace GeoIp2\Exception;
/**
* This class represents an error returned by MaxMind's GeoIP2
* web service.
*/
class WebServiceException extends HttpException
class InvalidRequestException extends HttpException
{
/**
* The code returned by the MaxMind web service
@@ -18,7 +18,7 @@ class WebServiceException extends HttpException
$error,
$httpStatus,
$uri,
Exception $previous = null
\Exception $previous = null
) {
$this->error = $error;
parent::__construct($message, $httpStatus, $uri, $previous);

View File

@@ -0,0 +1,10 @@
<?php
namespace GeoIp2\Exception;
/**
* This class represents a generic error.
*/
class OutOfQueriesException extends GeoIp2Exception
{
}

View File

@@ -1,6 +1,6 @@
<?php
namespace GeoIP2\Model;
namespace GeoIp2\Model;
/**
* This class provides a model for the data returned by the GeoIP2
@@ -10,33 +10,33 @@ namespace GeoIP2\Model;
* classes is which fields in each record may be populated. See
* http://dev.maxmind.com/geoip/geoip2/web-services more details.
*
* @property \GeoIP2\Record\City $city City data for the requested IP
* @property \GeoIp2\Record\City $city City data for the requested IP
* address.
*
* @property \GeoIP2\Record\Continent $continent Continent data for the
* @property \GeoIp2\Record\Continent $continent Continent data for the
* requested IP address.
*
* @property \GeoIP2\Record\Country $country Country data for the requested
* @property \GeoIp2\Record\Country $country Country data for the requested
* IP address. This object represents the country where MaxMind believes the
* end user is located.
*
* @property \GeoIP2\Record\Location $location Location data for the
* @property \GeoIp2\Record\Location $location Location data for the
* requested IP address.
*
* @property \GeoIP2\Record\MaxMind $maxmind Data related to your MaxMind
* @property \GeoIp2\Record\MaxMind $maxmind Data related to your MaxMind
* account.
*
* @property \GeoIP2\Record\Country $registeredCountry Registered country
* @property \GeoIp2\Record\Country $registeredCountry Registered country
* data for the requested IP address. This record represents the country
* where the ISP has registered a given IP block in and may differ from the
* where the ISP has registered a given IP block and may differ from the
* user's country.
*
* @property \GeoIP2\Record\RepresentedCountry $representedCountry
* @property \GeoIp2\Record\RepresentedCountry $representedCountry
* Represented country data for the requested IP address. The represented
* country is used for things like military bases or embassies. It is only
* present when the represented country differs from the country.
*
* @property array $subdivisions An array of {@link \GeoIP2\Record\Subdivision}
* @property array $subdivisions An array of {@link \GeoIp2\Record\Subdivision}
* objects representing the country subdivisions for the requested IP
* address. The number and type of subdivisions varies by country, but a
* subdivision is typically a state, province, county, etc. Subdivisions
@@ -44,12 +44,12 @@ namespace GeoIP2\Model;
* If the response did not contain any subdivisions, this method returns
* an empty array.
*
* @property \GeoIP2\Record\Subdivision $mostSpecificSubdivision An object
* @property \GeoIp2\Record\Subdivision $mostSpecificSubdivision An object
* representing the most specific subdivision returned. If the response
* did not contain any subdivisions, this method returns an empty
* {@link \GeoIP2\Record\Subdivision} object.
* {@link \GeoIp2\Record\Subdivision} object.
*
* @property \GeoIP2\Record\Traits $traits Data for the traits of the
* @property \GeoIp2\Record\Traits $traits Data for the traits of the
* requested IP address.
*/
class City extends Country
@@ -74,18 +74,18 @@ class City extends Country
/**
* @ignore
*/
public function __construct($raw, $languages)
public function __construct($raw, $locales)
{
parent::__construct($raw, $languages);
parent::__construct($raw, $locales);
$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'), $locales);
$this->location = new \GeoIp2\Record\Location($this->get('location'));
$this->postal = new \GeoIp2\Record\Postal($this->get('postal'));
$this->createSubdivisions($raw, $languages);
$this->createSubdivisions($raw, $locales);
}
private function createSubdivisions($raw, $languages)
private function createSubdivisions($raw, $locales)
{
if (!isset($raw['subdivisions'])) {
return;
@@ -94,7 +94,7 @@ class City extends Country
foreach ($raw['subdivisions'] as $sub) {
array_push(
$this->subdivisions,
new \GeoIP2\Record\Subdivision($sub, $languages)
new \GeoIp2\Record\Subdivision($sub, $locales)
);
}
}
@@ -114,7 +114,7 @@ class City extends Country
private function mostSpecificSubdivision()
{
return empty($this->subdivisions) ?
new \GeoIP2\Record\Subdivision(array(), $this->languages):
new \GeoIp2\Record\Subdivision(array(), $this->locales) :
end($this->subdivisions);
}
}

View File

@@ -1,6 +1,6 @@
<?php
namespace GeoIP2\Model;
namespace GeoIp2\Model;
/**
* This class provides a model for the data returned by the GeoIP2
@@ -10,33 +10,33 @@ namespace GeoIP2\Model;
* classes is which fields in each record may be populated. See
* http://dev.maxmind.com/geoip/geoip2/web-services more details.
*
* @property \GeoIP2\Record\City $city City data for the requested IP
* @property \GeoIp2\Record\City $city City data for the requested IP
* address.
*
* @property \GeoIP2\Record\Continent $continent Continent data for the
* @property \GeoIp2\Record\Continent $continent Continent data for the
* requested IP address.
*
* @property \GeoIP2\Record\Country $country Country data for the requested
* @property \GeoIp2\Record\Country $country Country data for the requested
* IP address. This object represents the country where MaxMind believes the
* end user is located.
*
* @property \GeoIP2\Record\Location $location Location data for the
* @property \GeoIp2\Record\Location $location Location data for the
* requested IP address.
*
* @property \GeoIP2\Record\MaxMind $maxmind Data related to your MaxMind
* @property \GeoIp2\Record\MaxMind $maxmind Data related to your MaxMind
* account.
*
* @property \GeoIP2\Record\Country $registeredCountry Registered country
* @property \GeoIp2\Record\Country $registeredCountry Registered country
* data for the requested IP address. This record represents the country
* where the ISP has registered a given IP block in and may differ from the
* where the ISP has registered a given IP block and may differ from the
* user's country.
*
* @property \GeoIP2\Record\RepresentedCountry $representedCountry
* @property \GeoIp2\Record\RepresentedCountry $representedCountry
* Represented country data for the requested IP address. The represented
* country is used for things like military bases or embassies. It is only
* present when the represented country differs from the country.
*
* @property array $subdivisions An array of {@link \GeoIP2\Record\Subdivision}
* @property array $subdivisions An array of {@link \GeoIp2\Record\Subdivision}
* objects representing the country subdivisions for the requested IP
* address. The number and type of subdivisions varies by country, but a
* subdivision is typically a state, province, county, etc. Subdivisions
@@ -44,12 +44,12 @@ namespace GeoIP2\Model;
* If the response did not contain any subdivisions, this method returns
* an empty array.
*
* @property \GeoIP2\Record\Subdivision $mostSpecificSubdivision An object
* @property \GeoIp2\Record\Subdivision $mostSpecificSubdivision An object
* representing the most specific subdivision returned. If the response
* did not contain any subdivisions, this method returns an empty
* {@link \GeoIP2\Record\Subdivision} object.
* {@link \GeoIp2\Record\Subdivision} object.
*
* @property \GeoIP2\Record\Traits $traits Data for the traits of the
* @property \GeoIp2\Record\Traits $traits Data for the traits of the
* requested IP address.
*/
class CityIspOrg extends City

View File

@@ -1,6 +1,6 @@
<?php
namespace GeoIP2\Model;
namespace GeoIp2\Model;
/**
* This class provides a model for the data returned by the GeoIP2 Country
@@ -10,34 +10,34 @@ namespace GeoIP2\Model;
* classes is which fields in each record may be populated. See
* http://dev.maxmind.com/geoip/geoip2/web-services more details.
*
* @property \GeoIP2\Record\Continent $continent Continent data for the
* @property \GeoIp2\Record\Continent $continent Continent data for the
* requested IP address.
*
* @property \GeoIP2\Record\Country $country Country data for the requested
* @property \GeoIp2\Record\Country $country Country data for the requested
* IP address. This object represents the country where MaxMind believes the
* end user is located.
*
* @property \GeoIP2\Record\MaxMind $maxmind Data related to your MaxMind
* @property \GeoIp2\Record\MaxMind $maxmind Data related to your MaxMind
* account.
*
* @property \GeoIP2\Record\Country $registeredCountry Registered country
* @property \GeoIp2\Record\Country $registeredCountry Registered country
* data for the requested IP address. This record represents the country
* where the ISP has registered a given IP block in and may differ from the
* where the ISP has registered a given IP block and may differ from the
* user's country.
*
* @property \GeoIP2\Record\RepresentedCountry $representedCountry
* @property \GeoIp2\Record\RepresentedCountry $representedCountry
* Represented country data for the requested IP address. The represented
* country is used for things like military bases or embassies. It is only
* present when the represented country differs from the country.
*
* @property \GeoIP2\Record\Traits $traits Data for the traits of the
* @property \GeoIp2\Record\Traits $traits Data for the traits of the
* requested IP address.
*/
class Country
{
private $continent;
private $country;
private $languages;
private $locales;
private $maxmind;
private $registeredCountry;
private $representedCountry;
@@ -47,30 +47,30 @@ class Country
/**
* @ignore
*/
public function __construct($raw, $languages)
public function __construct($raw, $locales)
{
$this->raw = $raw;
$this->continent = new \GeoIP2\Record\Continent(
$this->continent = new \GeoIp2\Record\Continent(
$this->get('continent'),
$languages
$locales
);
$this->country = new \GeoIP2\Record\Country(
$this->country = new \GeoIp2\Record\Country(
$this->get('country'),
$languages
$locales
);
$this->maxmind = new \GeoIP2\Record\MaxMind($this->get('maxmind'));
$this->registeredCountry = new \GeoIP2\Record\Country(
$this->maxmind = new \GeoIp2\Record\MaxMind($this->get('maxmind'));
$this->registeredCountry = new \GeoIp2\Record\Country(
$this->get('registered_country'),
$languages
$locales
);
$this->representedCountry = new \GeoIP2\Record\RepresentedCountry(
$this->representedCountry = new \GeoIp2\Record\RepresentedCountry(
$this->get('represented_country'),
$languages
$locales
);
$this->traits = new \GeoIP2\Record\Traits($this->get('traits'));
$this->traits = new \GeoIp2\Record\Traits($this->get('traits'));
$this->languages = $languages;
$this->locales = $locales;
}
/**

View File

@@ -1,6 +1,6 @@
<?php
namespace GeoIP2\Model;
namespace GeoIp2\Model;
/**
* This class provides a model for the data returned by the GeoIP2
@@ -10,33 +10,33 @@ namespace GeoIP2\Model;
* classes is which fields in each record may be populated. See
* http://dev.maxmind.com/geoip/geoip2/web-services more details.
*
* @property \GeoIP2\Record\City $city City data for the requested IP
* @property \GeoIp2\Record\City $city City data for the requested IP
* address.
*
* @property \GeoIP2\Record\Continent $continent Continent data for the
* @property \GeoIp2\Record\Continent $continent Continent data for the
* requested IP address.
*
* @property \GeoIP2\Record\Country $country Country data for the requested
* @property \GeoIp2\Record\Country $country Country data for the requested
* IP address. This object represents the country where MaxMind believes the
* end user is located.
*
* @property \GeoIP2\Record\Location $location Location data for the
* @property \GeoIp2\Record\Location $location Location data for the
* requested IP address.
*
* @property \GeoIP2\Record\MaxMind $maxmind Data related to your MaxMind
* @property \GeoIp2\Record\MaxMind $maxmind Data related to your MaxMind
* account.
*
* @property \GeoIP2\Record\Country $registeredCountry Registered country
* @property \GeoIp2\Record\Country $registeredCountry Registered country
* data for the requested IP address. This record represents the country
* where the ISP has registered a given IP block in and may differ from the
* where the ISP has registered a given IP block and may differ from the
* user's country.
*
* @property \GeoIP2\Record\RepresentedCountry $representedCountry
* @property \GeoIp2\Record\RepresentedCountry $representedCountry
* Represented country data for the requested IP address. The represented
* country is used for things like military bases or embassies. It is only
* present when the represented country differs from the country.
*
* @property array $subdivisions An array of {@link \GeoIP2\Record\Subdivision}
* @property array $subdivisions An array of {@link \GeoIp2\Record\Subdivision}
* objects representing the country subdivisions for the requested IP
* address. The number and type of subdivisions varies by country, but a
* subdivision is typically a state, province, county, etc. Subdivisions
@@ -44,12 +44,12 @@ namespace GeoIP2\Model;
* If the response did not contain any subdivisions, this method returns
* an empty array.
*
* @property \GeoIP2\Record\Subdivision $mostSpecificSubdivision An object
* @property \GeoIp2\Record\Subdivision $mostSpecificSubdivision An object
* representing the most specific subdivision returned. If the response
* did not contain any subdivisions, this method returns an empty
* {@link \GeoIP2\Record\Subdivision} object.
* {@link \GeoIp2\Record\Subdivision} object.
*
* @property \GeoIP2\Record\Traits $traits Data for the traits of the
* @property \GeoIp2\Record\Traits $traits Data for the traits of the
* requested IP address.
*/
class Omni extends CityIspOrg

View File

@@ -0,0 +1,34 @@
<?php
namespace GeoIp2;
interface ProviderInterface
{
/**
* @param ipAddress
* IPv4 or IPv6 address to lookup.
* @return \GeoIp2\Model\Country A Country model for the requested IP address.
*/
public function country($ipAddress);
/**
* @param ipAddress
* IPv4 or IPv6 address to lookup.
* @return \GeoIp2\Model\City A City model for the requested IP address.
*/
public function city($ipAddress);
/**
* @param ipAddress
* IPv4 or IPv6 address to lookup.
* @return \GeoIp2\Model\CityIspOrg A CityIspOrg model for the requested IP address.
*/
public function cityIspOrg($ipAddress);
/**
* @param ipAddress
* IPv4 or IPv6 address to lookup.
* @return \GeoIp2\Model\Omni An Omni model for the requested IP address.
*/
public function omni($ipAddress);
}

View File

@@ -1,17 +1,17 @@
<?php
namespace GeoIP2\Record;
namespace GeoIp2\Record;
abstract class AbstractPlaceRecord extends AbstractRecord
{
private $languages;
private $locales;
/**
* @ignore
*/
public function __construct($record, $languages)
public function __construct($record, $locales)
{
$this->languages = $languages;
$this->locales = $locales;
parent::__construct($record);
}
@@ -29,9 +29,9 @@ abstract class AbstractPlaceRecord extends AbstractRecord
private function name()
{
foreach ($this->languages as $language) {
if (isset($this->names[$language])) {
return $this->names[$language];
foreach ($this->locales as $locale) {
if (isset($this->names[$locale])) {
return $this->names[$locale];
}
}
}

View File

@@ -1,6 +1,6 @@
<?php
namespace GeoIP2\Record;
namespace GeoIp2\Record;
abstract class AbstractRecord
{

View File

@@ -1,6 +1,6 @@
<?php
namespace GeoIP2\Record;
namespace GeoIp2\Record;
/**
* City-level data associated with an IP address.
@@ -14,10 +14,10 @@ namespace GeoIP2\Record;
* @property int $geonameId The GeoName ID for the city. This attribute
* is returned by all end points.
*
* @property string $name The name of the city based on the languages list
* @property string $name The name of the city based on the locales list
* passed to the constructor. This attribute is returned by all end points.
*
* @property array $names A array map where the keys are language codes
* @property array $names A array map where the keys are locale codes
* and the values are names. This attribute is returned by all end points.
*/
class City extends AbstractPlaceRecord

View File

@@ -1,6 +1,6 @@
<?php
namespace GeoIP2\Record;
namespace GeoIp2\Record;
/**
* Contains data for the continent record associated with an IP address
@@ -14,10 +14,10 @@ namespace GeoIP2\Record;
* is returned by all end points.
*
* @property string $name Returns the name of the continent based on the
* languages list passed to the constructor. This attribute is returned by
* locales list passed to the constructor. This attribute is returned by
* all end points.
*
* @property array $names An array map where the keys are language codes
* @property array $names An array map where the keys are locale codes
* and the values are names. This attribute is returned by all end points.
*/
class Continent extends AbstractPlaceRecord

View File

@@ -1,6 +1,6 @@
<?php
namespace GeoIP2\Record;
namespace GeoIp2\Record;
/**
* Contains data for the country record associated with an IP address
@@ -18,10 +18,10 @@ namespace GeoIP2\Record;
* two-character ISO 3166-1 alpha code} for the country. This attribute is
* returned by all end points.
*
* @property string $name The name of the country based on the languages list
* @property string $name The name of the country based on the locales list
* passed to the constructor. This attribute is returned by all end points.
*
* @property array $names An array map where the keys are language codes and
* @property array $names An array map where the keys are locale codes and
* the values are names. This attribute is returned by all end points.
*/
class Country extends AbstractPlaceRecord

View File

@@ -1,6 +1,6 @@
<?php
namespace GeoIP2\Record;
namespace GeoIp2\Record;
/**
* Contains data for the location record associated with an IP address

View File

@@ -1,6 +1,6 @@
<?php
namespace GeoIP2\Record;
namespace GeoIp2\Record;
/**
* Contains data about your account.

View File

@@ -1,6 +1,6 @@
<?php
namespace GeoIP2\Record;
namespace GeoIp2\Record;
/**
* Contains data for the postal record associated with an IP address

View File

@@ -1,6 +1,6 @@
<?php
namespace GeoIP2\Record;
namespace GeoIp2\Record;
/**
* Contains data for the represented country associated with an IP address
@@ -22,10 +22,10 @@ namespace GeoIP2\Record;
* two-character ISO 3166-1 alpha code} for the country. This attribute is
* returned by all end points.
*
* @property string $name The name of the country based on the languages list
* @property string $name The name of the country based on the locales list
* passed to the constructor. This attribute is returned by all end points.
*
* @property array $names An array map where the keys are language codes and
* @property array $names An array map where the keys are locale codes and
* the values are names. This attribute is returned by all end points.
*
* @property string $type A string indicating the type of entity that is

View File

@@ -1,6 +1,6 @@
<?php
namespace GeoIP2\Record;
namespace GeoIp2\Record;
/**
*
@@ -20,11 +20,11 @@ namespace GeoIP2\Record;
* http://en.wikipedia.org/wiki/ISO_3166-2 ISO 3166-2 code}. This attribute
* is returned by all end points except Country.
*
* @property string $name The name of the subdivision based on the languages
* @property string $name The name of the subdivision based on the locales
* list passed to the constructor. This attribute is returned by all end
* points except Country.
*
* @property array $names An array map where the keys are language codes and
* @property array $names An array map where the keys are locale codes and
* the values are names. This attribute is returned by all end points except
* Country.
*/

View File

@@ -1,6 +1,6 @@
<?php
namespace GeoIP2\Record;
namespace GeoIp2\Record;
/**
*
@@ -39,12 +39,12 @@ namespace GeoIP2\Record;
* to a satellite Internet provider. This attribute is returned by all
* end points.
*
* @property string $isp The name of the ISP associated the IP address.
* @property string $isp The name of the ISP associated with the IP address.
* This attribute is only available from the City/ISP/Org and Omni end
* points.
*
* @property string $organization The name of the organization associated
* the IP address. This attribute is only available from the City/ISP/Org
* with the IP address. This attribute is only available from the City/ISP/Org
* and Omni end points.
*
* @property string $userType <p>The user type associated with the IP

View File

@@ -1,16 +1,16 @@
<?php
namespace GeoIP2\WebService;
namespace GeoIp2\WebService;
use GeoIP2\Exception\GeoIP2Exception;
use GeoIP2\Exception\HttpException;
use GeoIP2\Exception\WebServiceException;
use GeoIP2\Model\City;
use GeoIP2\Model\CityIspOrg;
use GeoIP2\Model\Country;
use GeoIP2\Model\Omni;
use Guzzle\Http\Client as GuzzleClient;
use GeoIp2\Exception\AddressNotFoundException;
use GeoIp2\Exception\AuthenticationException;
use GeoIp2\Exception\GeoIp2Exception;
use GeoIp2\Exception\HttpException;
use GeoIp2\Exception\InvalidRequestException;
use GeoIp2\Exception\OutOfQueriesException;
use GeoIp2\ProviderInterface;
use Guzzle\Common\Exception\RuntimeException;
use Guzzle\Http\Client as GuzzleClient;
use Guzzle\Http\Exception\ClientErrorResponseException;
use Guzzle\Http\Exception\ServerErrorResponseException;
@@ -44,32 +44,12 @@ use Guzzle\Http\Exception\ServerErrorResponseException;
* service.
*
* If the request fails, the client class throws an exception.
*
* **Exceptions**
*
* For details on the possible errors returned by the web service itself, see
* {@link http://dev.maxmind.com/geoip2/geoip/web-services the GeoIP2 web
* service docs}.
*
* If the web service returns an explicit error document, this is thrown as a
* {@link \GeoIP2\Exception\WebServiceException}. If some other sort of
* transport error occurs, this is thrown as a {@link
* \GeoIP2\Exception\HttpException}. The difference is that the web service
* error includes an error message and error code delivered by the web
* service. The latter is thrown when some sort of unanticipated error occurs,
* such as the web service returning a 500 or an invalid error document.
*
* If the web service returns any status code besides 200, 4xx, or 5xx, this
* also becomes a {@link \GeoIP2\Exception\HttpException}.
*
* Finally, if the web service returns a 200 but the body is invalid, the
* client throws a {@link \GeoIP2\Exception\GeoIP2Exception}.
*/
class Client
class Client implements ProviderInterface
{
private $userId;
private $licenseKey;
private $languages;
private $locales;
private $host;
private $guzzleClient;
@@ -78,7 +58,7 @@ class Client
*
* @param int $userId Your MaxMind user ID
* @param string $licenseKey Your MaxMind license key
* @param array $languages List of language codes to use in name property
* @param array $locales List of locale codes to use in name property
* from most preferred to least preferred.
* @param string $host Optional host parameter
* @param object $guzzleClient Optional Guzzle client to use (to facilitate
@@ -87,13 +67,13 @@ class Client
public function __construct(
$userId,
$licenseKey,
$languages = array('en'),
$locales = array('en'),
$host = 'geoip.maxmind.com',
$guzzleClient = null
) {
$this->userId = $userId;
$this->licenseKey = $licenseKey;
$this->languages = $languages;
$this->locales = $locales;
$this->host = $host;
// To enable unit testing
$this->guzzleClient = $guzzleClient;
@@ -106,14 +86,25 @@ class Client
* address is provided, the address that the web service is called
* from will be used.
*
* @return \GeoIP2\Model\City
* @return \GeoIp2\Model\City
*
* @throws \GeoIP2\Exception\GeoIP2Exception if there was a generic
* error processing your request.
* @throws \GeoIP2\Exception\HttpException if there was an HTTP transport
* error.
* @throws \GeoIP2\Exception\WebServiceException if an error was returned
* by MaxMind's GeoIP2 web service.
* @throws \GeoIp2\Exception\AddressNotFoundException if the address you
* provided is not in our database (e.g., a private address).
* @throws \GeoIp2\Exception\AuthenticationException if there is a problem
* with the user ID or license key that you provided.
* @throws \GeoIp2\Exception\OutOfQueriesException if your account is out
* of queries.
* @throws \GeoIp2\Exception\InvalidRequestException} if your request was
* received by the web service but is invalid for some other reason.
* This may indicate an issue with this API. Please report the error to
* MaxMind.
* @throws \GeoIp2\Exception\HttpException if an unexpected HTTP error
* code or message was returned. This could indicate a problem with the
* connection between your server and the web service or that the web
* service returned an invalid document or 500 error code.
* @throws \GeoIp2\Exception\GeoIp2Exception This serves as the parent
* class to the above exceptions. It will be thrown directly if a 200
* status code is returned but the body is invalid.
*/
public function city($ipAddress = 'me')
{
@@ -127,14 +118,25 @@ class Client
* address is provided, the address that the web service is called
* from will be used.
*
* @return \GeoIP2\Model\Country
* @return \GeoIp2\Model\Country
*
* @throws \GeoIP2\Exception\GeoIP2Exception if there was a generic
* error processing your request.
* @throws \GeoIP2\Exception\HttpException if there was an HTTP transport
* error.
* @throws \GeoIP2\Exception\WebServiceException if an error was returned
* by MaxMind's GeoIP2 web service.
* @throws \GeoIp2\Exception\AddressNotFoundException if the address you
* provided is not in our database (e.g., a private address).
* @throws \GeoIp2\Exception\AuthenticationException if there is a problem
* with the user ID or license key that you provided.
* @throws \GeoIp2\Exception\OutOfQueriesException if your account is out
* of queries.
* @throws \GeoIp2\Exception\InvalidRequestException} if your request was
* received by the web service but is invalid for some other reason.
* This may indicate an issue with this API. Please report the error to
* MaxMind.
* @throws \GeoIp2\Exception\HttpException if an unexpected HTTP error
* code or message was returned. This could indicate a problem with the
* connection between your server and the web service or that the web
* service returned an invalid document or 500 error code.
* @throws \GeoIp2\Exception\GeoIp2Exception This serves as the parent
* class to the above exceptions. It will be thrown directly if a 200
* status code is returned but the body is invalid.
*/
public function country($ipAddress = 'me')
{
@@ -148,14 +150,25 @@ class Client
* address is provided, the address that the web service is called
* from will be used.
*
* @return \GeoIP2\Model\CityIspOrg
* @return \GeoIp2\Model\CityIspOrg
*
* @throws \GeoIP2\Exception\GeoIP2Exception if there was a generic
* error processing your request.
* @throws \GeoIP2\Exception\HttpException if there was an HTTP transport
* error.
* @throws \GeoIP2\Exception\WebServiceException if an error was returned
* by MaxMind's GeoIP2 web service.
* @throws \GeoIp2\Exception\AddressNotFoundException if the address you
* provided is not in our database (e.g., a private address).
* @throws \GeoIp2\Exception\AuthenticationException if there is a problem
* with the user ID or license key that you provided.
* @throws \GeoIp2\Exception\OutOfQueriesException if your account is out
* of queries.
* @throws \GeoIp2\Exception\InvalidRequestException} if your request was
* received by the web service but is invalid for some other reason.
* This may indicate an issue with this API. Please report the error to
* MaxMind.
* @throws \GeoIp2\Exception\HttpException if an unexpected HTTP error
* code or message was returned. This could indicate a problem with the
* connection between your server and the web service or that the web
* service returned an invalid document or 500 error code.
* @throws \GeoIp2\Exception\GeoIp2Exception This serves as the parent
* class to the above exceptions. It will be thrown directly if a 200
* status code is returned but the body is invalid.
*/
public function cityIspOrg($ipAddress = 'me')
{
@@ -169,14 +182,25 @@ class Client
* address is provided, the address that the web service is called
* from will be used.
*
* @return \GeoIP2\Model\Omni
* @return \GeoIp2\Model\Omni
*
* @throws \GeoIP2\Exception\GeoIP2Exception if there was a generic
* error processing your request.
* @throws \GeoIP2\Exception\HttpException if there was an HTTP transport
* error.
* @throws \GeoIP2\Exception\WebServiceException if an error was returned
* by MaxMind's GeoIP2 web service.
* @throws \GeoIp2\Exception\AddressNotFoundException if the address you
* provided is not in our database (e.g., a private address).
* @throws \GeoIp2\Exception\AuthenticationException if there is a problem
* with the user ID or license key that you provided.
* @throws \GeoIp2\Exception\OutOfQueriesException if your account is out
* of queries.
* @throws \GeoIp2\Exception\InvalidRequestException} if your request was
* received by the web service but is invalid for some other reason.
* This may indicate an issue with this API. Please report the error to
* MaxMind.
* @throws \GeoIp2\Exception\HttpException if an unexpected HTTP error
* code or message was returned. This could indicate a problem with the
* connection between your server and the web service or that the web
* service returned an invalid document or 500 error code.
* @throws \GeoIp2\Exception\GeoIp2Exception This serves as the parent
* class to the above exceptions. It will be thrown directly if a 200
* status code is returned but the body is invalid.
*/
public function omni($ipAddress = 'me')
{
@@ -191,11 +215,8 @@ class Client
$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);
$this->setUserAgent($request);
$response = null;
try {
$response = $request->send();
} catch (ClientErrorResponseException $e) {
@@ -206,8 +227,8 @@ class Client
if ($response && $response->isSuccessful()) {
$body = $this->handleSuccess($response, $uri);
$class = "GeoIP2\\Model\\" . $class;
return new $class($body, $this->languages);
$class = "GeoIp2\\Model\\" . $class;
return new $class($body, $this->locales);
} else {
$this->handleNon200($response, $uri);
}
@@ -216,7 +237,7 @@ class Client
private function handleSuccess($response, $uri)
{
if ($response->getContentLength() == 0) {
throw new GeoIP2Exception(
throw new GeoIp2Exception(
"Received a 200 response for $uri but did not " .
"receive a HTTP body."
);
@@ -225,7 +246,7 @@ class Client
try {
return $response->json();
} catch (RuntimeException $e) {
throw new GeoIP2Exception(
throw new GeoIp2Exception(
"Received a 200 response for $uri but could not decode " .
"the response as JSON: " . $e->getMessage()
);
@@ -237,14 +258,12 @@ class Client
{
$status = $response->getStatusCode();
$body = array();
if ($response->getContentLength() > 0) {
if (strstr($response->getContentType(), 'json')) {
try {
$body = $response->json();
if (!isset($body['code']) || !isset($body['error'])) {
throw new GeoIP2Exception(
throw new GeoIp2Exception(
'Response contains JSON but it does not specify ' .
'code or error keys: ' . $response->getBody()
);
@@ -273,8 +292,7 @@ class Client
$uri
);
}
throw new WebServiceException(
$this->handleWebServiceError(
$body['error'],
$body['code'],
$status,
@@ -282,6 +300,28 @@ class Client
);
}
private function handleWebServiceError($message, $code, $status, $uri)
{
switch ($code) {
case 'IP_ADDRESS_NOT_FOUND':
case 'IP_ADDRESS_RESERVED':
throw new AddressNotFoundException($message);
case 'AUTHORIZATION_INVALID':
case 'LICENSE_KEY_REQUIRED':
case 'USER_ID_REQUIRED':
throw new AuthenticationException($message);
case 'OUT_OF_QUERIES':
throw new OutOfQueriesException($message);
default:
throw new InvalidRequestException(
$message,
$code,
$status,
$uri
);
}
}
private function handle5xx($response, $uri)
{
$status = $response->getStatusCode();
@@ -305,6 +345,13 @@ class Client
);
}
private function setUserAgent($request)
{
$userAgent = $request->getHeader('User-Agent');
$userAgent = "GeoIP2 PHP API ($userAgent)";
$request->setHeader('User-Agent', $userAgent);
}
private function baseUri()
{
return 'https://' . $this->host . '/geoip/v2.0';

View File

@@ -0,0 +1,80 @@
<?php
namespace GeoIp2\Test\WebService;
use GeoIp2\Database\Reader;
class ReaderTest extends \PHPUnit_Framework_TestCase
{
public function testDefaultLocale()
{
$reader = new Reader('maxmind-db/test-data/GeoIP2-City-Test.mmdb');
// Needed for PHP 5.3
$that = $this;
$this->checkAllMethods(
function ($method) use (&$that, &$reader) {
$record = $reader->$method('81.2.69.160');
$that->assertEquals('United Kingdom', $record->country->name);
}
);
$reader->close();
}
public function testLocaleList()
{
$reader = new Reader(
'maxmind-db/test-data/GeoIP2-City-Test.mmdb',
array('xx', 'ru', 'pt-BR', 'es', 'en')
);
$that = $this;
$this->checkAllMethods(
function ($method) use (&$that, &$reader) {
$record = $reader->$method('81.2.69.160');
$that->assertEquals('Великобритания', $record->country->name);
}
);
$reader->close();
}
public function testHasIpAddress()
{
$reader = new Reader('maxmind-db/test-data/GeoIP2-City-Test.mmdb');
$that = $this;
$this->checkAllMethods(
function ($method) use (&$that, &$reader) {
$record = $reader->$method('81.2.69.160');
$that->assertEquals('81.2.69.160', $record->traits->ipAddress);
}
);
$reader->close();
}
/**
* @expectedException GeoIp2\Exception\AddressNotFoundException
* @expectedExceptionMessage The address 10.10.10.10 is not in the database.
*/
public function testUnknownAddress()
{
$reader = new Reader('maxmind-db/test-data/GeoIP2-City-Test.mmdb');
$reader->city('10.10.10.10');
$reader->close();
}
/**
* @expectedException InvalidArgumentException
* @expectedExceptionMessage is not a valid IP address
*/
public function testInvalidAddress()
{
$reader = new Reader('maxmind-db/test-data/GeoIP2-City-Test.mmdb');
$reader->city('invalid');
$reader->close();
}
public function checkAllMethods($testCb)
{
foreach (array('city', 'cityIspOrg', 'country', 'omni') as $method) {
$testCb($method);
}
}
}

View File

@@ -1,8 +1,8 @@
<?php
namespace GeoIP2\Test\Model;
namespace GeoIp2\Test\Model;
use GeoIP2\Model\Country;
use GeoIp2\Model\Country;
class CountryTest extends \PHPUnit_Framework_TestCase
{
@@ -38,28 +38,28 @@ class CountryTest extends \PHPUnit_Framework_TestCase
public function testObjects()
{
$this->assertInstanceOf(
'GeoIP2\Model\Country',
'GeoIp2\Model\Country',
$this->model,
'minimal GeoIP2::Model::Country object'
'minimal GeoIp2::Model::Country object'
);
$this->assertInstanceOf(
'GeoIP2\Record\Continent',
'GeoIp2\Record\Continent',
$this->model->continent
);
$this->assertInstanceOf(
'GeoIP2\Record\Country',
'GeoIp2\Record\Country',
$this->model->country
);
$this->assertInstanceOf(
'GeoIP2\Record\Country',
'GeoIp2\Record\Country',
$this->model->registeredCountry
);
$this->assertInstanceOf(
'GeoIP2\Record\RepresentedCountry',
'GeoIp2\Record\RepresentedCountry',
$this->model->representedCountry
);
$this->assertInstanceOf(
'GeoIP2\Record\Traits',
'GeoIp2\Record\Traits',
$this->model->traits
);
}

View File

@@ -1,8 +1,8 @@
<?php
namespace GeoIP2\Test\Model;
namespace GeoIp2\Test\Model;
use GeoIP2\Model\Country;
use GeoIp2\Model\Country;
class NameTest extends \PHPUnit_Framework_TestCase
{
@@ -46,7 +46,8 @@ class NameTest extends \PHPUnit_Framework_TestCase
);
}
public function testTwoFallbacks() {
public function testTwoFallbacks()
{
$model = new Country($this->raw, array('ru', 'ja'));
$this->assertEquals(

View File

@@ -1,8 +1,8 @@
<?php
namespace GeoIP2\Test\Model;
namespace GeoIp2\Test\Model;
use GeoIP2\Model\Omni;
use GeoIp2\Model\Omni;
class OmniTest extends \PHPUnit_Framework_TestCase
{
@@ -72,60 +72,60 @@ class OmniTest extends \PHPUnit_Framework_TestCase
$model = new Omni($raw, array('en'));
$this->assertInstanceOf(
'GeoIP2\Model\Omni',
'GeoIp2\Model\Omni',
$model,
'GeoIP2\Model\Omni object'
'GeoIp2\Model\Omni object'
);
$this->assertInstanceOf(
'GeoIP2\Record\City',
'GeoIp2\Record\City',
$model->city,
'$model->city'
);
$this->assertInstanceOf(
'GeoIP2\Record\Continent',
'GeoIp2\Record\Continent',
$model->continent,
'$model->continent'
);
$this->assertInstanceOf(
'GeoIP2\Record\Country',
'GeoIp2\Record\Country',
$model->country,
'$model->country'
);
$this->assertInstanceOf(
'GeoIP2\Record\Location',
'GeoIp2\Record\Location',
$model->location,
'$model->location'
);
$this->assertInstanceOf(
'GeoIP2\Record\Country',
'GeoIp2\Record\Country',
$model->registeredCountry,
'$model->registeredCountry'
);
$this->assertInstanceOf(
'GeoIP2\Record\RepresentedCountry',
'GeoIp2\Record\RepresentedCountry',
$model->representedCountry,
'$model->representedCountry'
);
$subdivisions = $model->subdivisions;
foreach ($subdivisions as $subdiv) {
$this->assertInstanceOf('GeoIP2\Record\Subdivision', $subdiv);
$this->assertInstanceOf('GeoIp2\Record\Subdivision', $subdiv);
}
$this->assertInstanceOf(
'GeoIP2\Record\Subdivision',
'GeoIp2\Record\Subdivision',
$model->mostSpecificSubdivision,
'$model->mostSpecificSubdivision'
);
$this->assertInstanceOf(
'GeoIP2\Record\Traits',
'GeoIp2\Record\Traits',
$model->traits,
'$model->traits'
);
@@ -150,43 +150,43 @@ class OmniTest extends \PHPUnit_Framework_TestCase
$model = new Omni($raw, array('en'));
$this->assertInstanceOf(
'GeoIP2\Model\Omni',
'GeoIp2\Model\Omni',
$model,
'GeoIP2\Model\Omni object with no data except traits.ipAddress'
'GeoIp2\Model\Omni object with no data except traits.ipAddress'
);
$this->assertInstanceOf(
'GeoIP2\Record\City',
'GeoIp2\Record\City',
$model->city,
'$model->city'
);
$this->assertInstanceOf(
'GeoIP2\Record\Continent',
'GeoIp2\Record\Continent',
$model->continent,
'$model->continent'
);
$this->assertInstanceOf(
'GeoIP2\Record\Country',
'GeoIp2\Record\Country',
$model->country,
'$model->country'
);
$this->assertInstanceOf(
'GeoIP2\Record\Location',
'GeoIp2\Record\Location',
$model->location,
'$model->location'
);
$this->assertInstanceOf(
'GeoIP2\Record\Country',
'GeoIp2\Record\Country',
$model->registeredCountry,
'$model->registeredCountry'
);
$this->assertInstanceOf(
'GeoIP2\Record\RepresentedCountry',
'GeoIp2\Record\RepresentedCountry',
$model->representedCountry,
'$model->representedCountry'
);
@@ -198,13 +198,13 @@ class OmniTest extends \PHPUnit_Framework_TestCase
);
$this->assertInstanceOf(
'GeoIP2\Record\Subdivision',
'GeoIp2\Record\Subdivision',
$model->mostSpecificSubdivision,
'$model->mostSpecificSubdivision'
);
$this->assertInstanceOf(
'GeoIP2\Record\Traits',
'GeoIp2\Record\Traits',
$model->traits,
'$model->traits'
);
@@ -234,7 +234,7 @@ class OmniTest extends \PHPUnit_Framework_TestCase
$model = new Omni($raw, array('en'));
$this->assertInstanceOf(
'GeoIP2\Model\Omni',
'GeoIp2\Model\Omni',
$model,
'no exception when Omni model gets raw data with unknown keys'
);

View File

@@ -1,8 +1,8 @@
<?php
namespace GeoIP2\Test\WebService;
namespace GeoIp2\Test\WebService;
use GeoIP2\WebService\Client;
use GeoIp2\WebService\Client;
use Guzzle\Http\Client as GuzzleClient;
use Guzzle\Http\Message\Response;
use Guzzle\Plugin\Mock\MockPlugin;
@@ -82,6 +82,54 @@ class ClientTest extends \PHPUnit_Framework_TestCase
null,
'text/plain'
),
'1.2.3.13' => $this->response(
'error',
404,
array(
'code' => 'IP_ADDRESS_NOT_FOUND',
'error' => 'The address "1.2.3.13" is not in our database.'
)
),
'1.2.3.14' => $this->response(
'error',
400,
array(
'code' => 'IP_ADDRESS_RESERVED',
'error' => 'The address "1.2.3.14" is a private address.'
)
),
'1.2.3.15' => $this->response(
'error',
401,
array(
'code' => 'AUTHORIZATION_INVALID',
'error' => 'A user ID and license key are required to use this service'
)
),
'1.2.3.16' => $this->response(
'error',
401,
array(
'code' => 'LICENSE_KEY_REQUIRED',
'error' => 'A license key is required to use this service'
)
),
'1.2.3.17' => $this->response(
'error',
401,
array(
'code' => 'USER_ID_REQUIRED',
'error' => 'A user ID is required to use this service'
)
),
'1.2.3.18' => $this->response(
'error',
402,
array(
'code' => 'OUT_OF_QUERIES',
'error' => 'The license key you have provided is out of queries.'
)
),
);
return $responses[$ip];
}
@@ -91,7 +139,7 @@ class ClientTest extends \PHPUnit_Framework_TestCase
$country = $this->client($this->getResponse('1.2.3.4'))
->country('1.2.3.4');
$this->assertInstanceOf('GeoIP2\Model\Country', $country);
$this->assertInstanceOf('GeoIp2\Model\Country', $country);
$this->assertEquals(
42,
@@ -155,7 +203,7 @@ class ClientTest extends \PHPUnit_Framework_TestCase
$omni = $this->client($this->getResponse('1.2.3.4'))
->omni('1.2.3.4');
$this->assertInstanceOf('GeoIP2\Model\Omni', $omni);
$this->assertInstanceOf('GeoIp2\Model\Omni', $omni);
$this->assertEquals(
42,
@@ -169,7 +217,7 @@ class ClientTest extends \PHPUnit_Framework_TestCase
$city = $this->client($this->getResponse('1.2.3.4'))
->city('1.2.3.4');
$this->assertInstanceOf('GeoIP2\Model\City', $city);
$this->assertInstanceOf('GeoIp2\Model\City', $city);
}
public function testMe()
@@ -177,14 +225,14 @@ class ClientTest extends \PHPUnit_Framework_TestCase
$client = $this->client($this->getResponse('me'));
$this->assertInstanceOf(
'GeoIP2\Model\CityIspOrg',
'GeoIp2\Model\CityIspOrg',
$client->cityIspOrg('me'),
'can set ip parameter to me'
);
}
/**
* @expectedException GeoIP2\Exception\GeoIP2Exception
* @expectedException GeoIp2\Exception\GeoIp2Exception
* @expectedExceptionMessage Received a 200 response for https://geoip.maxmind.com/geoip/v2.0/country/1.2.3.5 but did not receive a HTTP body.
*/
public function testNoBodyException()
@@ -195,7 +243,7 @@ class ClientTest extends \PHPUnit_Framework_TestCase
}
/**
* @expectedException GeoIP2\Exception\GeoIP2Exception
* @expectedException GeoIp2\Exception\GeoIp2Exception
* @expectedExceptionMessage Received a 200 response for https://geoip.maxmind.com/geoip/v2.0/country/2.2.3.5 but could not decode the response as JSON:
*/
public function testBadBodyException()
@@ -207,7 +255,7 @@ class ClientTest extends \PHPUnit_Framework_TestCase
/**
* @expectedException GeoIP2\Exception\WebServiceException
* @expectedException GeoIp2\Exception\InvalidRequestException
* @expectedExceptionCode 400
* @expectedExceptionMessage The value "1.2.3" is not a valid ip address
*/
@@ -216,11 +264,10 @@ class ClientTest extends \PHPUnit_Framework_TestCase
$client = $this->client($this->getResponse('1.2.3.6'));
$client->country('1.2.3.6');
}
/**
* @expectedException GeoIP2\Exception\HttpException
* @expectedException GeoIp2\Exception\HttpException
* @expectedExceptionCode 400
* @expectedExceptionMessage with no body
*/
@@ -232,7 +279,7 @@ class ClientTest extends \PHPUnit_Framework_TestCase
}
/**
* @expectedException GeoIP2\Exception\GeoIP2Exception
* @expectedException GeoIp2\Exception\GeoIp2Exception
* @expectedExceptionMessage Response contains JSON but it does not specify code or error keys
*/
public function testWeirdErrorBodyIPException()
@@ -244,7 +291,7 @@ class ClientTest extends \PHPUnit_Framework_TestCase
}
/**
* @expectedException GeoIP2\Exception\HttpException
* @expectedException GeoIp2\Exception\HttpException
* @expectedExceptionCode 400
* @expectedExceptionMessage did not include the expected JSON body
*/
@@ -257,7 +304,7 @@ class ClientTest extends \PHPUnit_Framework_TestCase
}
/**
* @expectedException GeoIP2\Exception\HttpException
* @expectedException GeoIp2\Exception\HttpException
* @expectedExceptionCode 500
* @expectedExceptionMessage Received a server error (500)
*/
@@ -270,7 +317,7 @@ class ClientTest extends \PHPUnit_Framework_TestCase
}
/**
* @expectedException GeoIP2\Exception\HttpException
* @expectedException GeoIp2\Exception\HttpException
* @expectedExceptionCode 300
* @expectedExceptionMessage Received a very surprising HTTP status (300)
*/
@@ -283,7 +330,7 @@ class ClientTest extends \PHPUnit_Framework_TestCase
}
/**
* @expectedException GeoIP2\Exception\HttpException
* @expectedException GeoIp2\Exception\HttpException
* @expectedExceptionCode 406
* @expectedExceptionMessage Received a 406 error for https://geoip.maxmind.com/geoip/v2.0/country/1.2.3.12 with the following body: Cannot satisfy your Accept-Charset requirements
*/
@@ -293,6 +340,72 @@ class ClientTest extends \PHPUnit_Framework_TestCase
$client->country('1.2.3.12');
}
/**
* @expectedException GeoIp2\Exception\AddressNotFoundException
* @expectedExceptionMessage The address "1.2.3.13" is not in our database.
*/
public function testAddressNotFoundException()
{
$client = $this->client($this->getResponse('1.2.3.13'));
$client->country('1.2.3.13');
}
/**
* @expectedException GeoIp2\Exception\AddressNotFoundException
* @expectedExceptionMessage The address "1.2.3.14" is a private address.
*/
public function testAddressReservedException()
{
$client = $this->client($this->getResponse('1.2.3.14'));
$client->country('1.2.3.14');
}
/**
* @expectedException GeoIp2\Exception\AuthenticationException
* @expectedExceptionMessage A user ID and license key are required to use this service
*/
public function testAuthorizationException()
{
$client = $this->client($this->getResponse('1.2.3.15'));
$client->country('1.2.3.15');
}
/**
* @expectedException GeoIp2\Exception\AuthenticationException
* @expectedExceptionMessage A license key is required to use this service
*/
public function testMissingLicenseKeyException()
{
$client = $this->client($this->getResponse('1.2.3.16'));
$client->country('1.2.3.16');
}
/**
* @expectedException GeoIp2\Exception\AuthenticationException
* @expectedExceptionMessage A user ID is required to use this service
*/
public function testMissingUserIdException()
{
$client = $this->client($this->getResponse('1.2.3.17'));
$client->country('1.2.3.17');
}
/**
* @expectedException GeoIp2\Exception\OutOfQueriesException
* @expectedExceptionMessage The license key you have provided is out of queries.
*/
public function testOutOfQueriesException()
{
$client = $this->client($this->getResponse('1.2.3.18'));
$client->country('1.2.3.18');
}
public function testParams()
{
$plugin = new MockPlugin();
@@ -337,7 +450,7 @@ class ClientTest extends \PHPUnit_Framework_TestCase
}
private function client($response, $languages = array('en'))
private function client($response, $locales = array('en'))
{
$plugin = new MockPlugin();
$plugin->addResponse($response);
@@ -347,7 +460,7 @@ class ClientTest extends \PHPUnit_Framework_TestCase
$client = new Client(
42,
'abcdef123456',
$languages,
$locales,
'geoip.maxmind.com',
$guzzleClient
);

View File

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