Skip to content

Commit c2373a6

Browse files
committed
Merge pull request geocoder-php#507 from mtmail/OpenCage-more-exception-cases
Handle invalid API key, over quota respones for OpenCage provider
2 parents 772bb06 + 70ab9f5 commit c2373a6

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

src/Geocoder/Provider/OpenCage.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
namespace Geocoder\Provider;
1111

1212
use Geocoder\Exception\InvalidCredentials;
13+
use Geocoder\Exception\QuotaExceeded;
1314
use Geocoder\Exception\NoResult;
1415
use Geocoder\Exception\UnsupportedOperation;
1516
use Ivory\HttpAdapter\HttpAdapterInterface;
@@ -106,6 +107,18 @@ private function executeQuery($query)
106107

107108
$json = json_decode($content, true);
108109

110+
// https://geocoder.opencagedata.com/api#codes
111+
if (isset($json['status'])) {
112+
switch ($json['status']['code']) {
113+
case 400:
114+
throw new InvalidArgument('Invalid request (a required parameter is missing).');
115+
case 402:
116+
throw new QuotaExceeded('Valid request but quota exceeded.');
117+
case 403:
118+
throw new InvalidCredentials('Invalid or missing api key.');
119+
}
120+
}
121+
109122
if (!isset($json['total_results']) || $json['total_results'] == 0) {
110123
throw new NoResult(sprintf('Could not find results for query "%s".', $query));
111124
}

tests/Geocoder/Tests/Provider/OpenCageTest.php

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,47 @@ public function testGeocodeWithLocale()
253253
$this->assertEquals('GB', $result->getCountry()->getCode());
254254
}
255255

256+
257+
/**
258+
* @expectedException \Geocoder\Exception\QuotaExceeded
259+
* @expectedExceptionMessage Valid request but quota exceeded.
260+
*/
261+
public function testGeocodeQuotaExceeded()
262+
{
263+
$provider = new OpenCage(
264+
$this->getMockAdapterReturns(
265+
'{
266+
"status": {
267+
"code": 402,
268+
"message": "quota exceeded"
269+
}
270+
}'
271+
),
272+
'api_key'
273+
);
274+
$provider->geocode('New York');
275+
}
276+
277+
/**
278+
* @expectedException \Geocoder\Exception\InvalidCredentials
279+
* @expectedExceptionMessage Invalid or missing api key.
280+
*/
281+
public function testGeocodeInvalidApiKey()
282+
{
283+
$provider = new OpenCage(
284+
$this->getMockAdapterReturns(
285+
'{
286+
"status": {
287+
"code": 403,
288+
"message": "invalid API key"
289+
}
290+
}'
291+
),
292+
'api_key'
293+
);
294+
$provider->geocode('New York');
295+
}
296+
256297
/**
257298
* @expectedException \Geocoder\Exception\UnsupportedOperation
258299
* @expectedExceptionMessage The OpenCage provider does not support IP addresses, only street addresses.

0 commit comments

Comments
 (0)