Skip to content

Implement Coordinates by Location Name endpoint #189

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 72 additions & 1 deletion Cmfcmf/OpenWeatherMap.php
Original file line number Diff line number Diff line change
@@ -23,6 +23,8 @@
use Cmfcmf\OpenWeatherMap\CurrentWeatherGroup;
use Cmfcmf\OpenWeatherMap\Exception as OWMException;
use Cmfcmf\OpenWeatherMap\NotFoundException as OWMNotFoundException;
use Cmfcmf\OpenWeatherMap\Util\City;
use Cmfcmf\OpenWeatherMap\Util\Location;
use Cmfcmf\OpenWeatherMap\UVIndex;
use Cmfcmf\OpenWeatherMap\WeatherForecast;
use Psr\Cache\CacheItemPoolInterface;
@@ -74,6 +76,12 @@ class OpenWeatherMap
*/
private $airPollutionUrl = 'https://api.openweathermap.org/pollution/v1/';

/**
* @var string The base API URL for fetching coordinates by location name.
* @see https://openweathermap.org/api/geocoding-api#direct_name
*/
private $coordinatesByLocationNameUrl = 'http://api.openweathermap.org/geo/1.0/direct';

/**
* @var CacheItemPoolInterface|null $cache The cache to use.
*/
@@ -589,7 +597,9 @@ private function cacheOrFetchResult($url)
}
}

$response = $this->httpClient->sendRequest($this->httpRequestFactory->createRequest("GET", $url));
$response = $this->httpClient->sendRequest(
$this->httpRequestFactory->createRequest("GET", $url)
);
$result = $response->getBody()->getContents();
if ($response->getStatusCode() !== 200) {
if (false !== strpos($result, 'not found') && $response->getStatusCode() === 404) {
@@ -668,6 +678,67 @@ private function buildUVIndexUrl($mode, $lat, $lon, $cnt = null, \DateTime $star
return sprintf($this->uvIndexUrl . '%s?%s', $requestMode, http_build_query($params));
}

public function getCoordinatesByLocationName(
$city,
$stateCode = null,
$countryCode = null,
$limit = null
) {
$url = $this->buildCoordinatesByLocationNameUrl($city, $stateCode, $countryCode, $limit);
$response = $this->cacheOrFetchResult($url);
$data = $this->parseJson($response);
$cities = [];
foreach ($data as $datum) {
$cities[] = new City(
-1,
$datum->name,
$datum->lat,
$datum->lon,
$datum->country,
null,
null,
$datum->state,
(array)$datum->local_names
);
Comment on lines +692 to +702
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you create a new City class specifically for this API call? I don't like how the newly added fields are only used by this API, and how this API never sets some of the fields. Maybe call it Location?

}

return $cities;
}

private function buildCoordinatesByLocationNameUrl(
string $city,
string $stateCode = null,
string $countryCode = null,
int $limit = null
): string
{
$params = array(
'appid' => $this->apiKey,
'q' => $city,
);

if ($stateCode !== null) {
$params['q'] = sprintf('%s,%s', $params['q'], $stateCode);
if ($countryCode !== null) {
$params['q'] = sprintf('%s,%s', $params['q'], $countryCode);
}
} else {
if ($countryCode !== null) {
$params['q'] = sprintf('%s,,%s', $params['q'], $countryCode);
}
}

if ($limit !== null) {
$params['limit'] = $limit;
}

return sprintf(
'%s?%s',
$this->coordinatesByLocationNameUrl,
http_build_query($params)
);
}

/**
* Builds the query string for the url.
*
27 changes: 25 additions & 2 deletions Cmfcmf/OpenWeatherMap/Util/City.php
Original file line number Diff line number Diff line change
@@ -38,6 +38,16 @@ class City extends Location
*/
public $country;

/**
* @var string|null The state in which the city is located.
*/
public $state;

/**
* @var array<string,string> An array of internationalised versions of the city's name.
*/
public $localNames = [];

/**
* @var int The city's population
*/
@@ -58,16 +68,29 @@ class City extends Location
* @param string $country The abbreviation of the country the city is located in
* @param int $population The city's population.
* @param int $timezoneOffset The shift in seconds from UTC.
* @param string $state The state in which the city is located.
* @param array $localNames An array of internationalised versions of the city's name.
*
* @internal
*/
public function __construct($id, $name = null, $lat = null, $lon = null, $country = null, $population = null, $timezoneOffset = null)
{
public function __construct(
$id,
$name = null,
$lat = null,
$lon = null,
$country = null,
$population = null,
$timezoneOffset = null,
$state = null,
$localNames = []
) {
$this->id = (int)$id;
$this->name = isset($name) ? (string)$name : null;
$this->country = isset($country) ? (string)$country : null;
$this->population = isset($population) ? (int)$population : null;
$this->timezone = isset($timezoneOffset) ? new \DateTimeZone(self::timezoneOffsetInSecondsToHours((int)$timezoneOffset)) : null;
$this->state = $state ?? null;
$this->localNames = $localNames ?? [];

parent::__construct($lat, $lon);
}
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -21,6 +21,7 @@
"ext-json": "*",
"ext-libxml": "*",
"ext-simplexml": "*",
"mjelamanov/psr18-guzzle": "^1.2",
"psr/cache": "^1 || ^2 || ^3",
"psr/http-client": "^1.0",
"psr/http-factory": "^1.0"
3,197 changes: 1,457 additions & 1,740 deletions composer.lock

Large diffs are not rendered by default.

157 changes: 157 additions & 0 deletions tests/OpenWeatherMapTest.php
Original file line number Diff line number Diff line change
@@ -19,12 +19,24 @@
namespace Cmfcmf\OpenWeatherMap\Tests;

use Cmfcmf\OpenWeatherMap;
use Cmfcmf\OpenWeatherMap\CurrentWeather;
use Cmfcmf\OpenWeatherMap\Exception;
use Cmfcmf\OpenWeatherMap\Tests\MyTestCase;
use Cmfcmf\OpenWeatherMap\Tests\TestHttpClient;
use Cache\Adapter\PHPArray\ArrayCachePool;
use Cmfcmf\OpenWeatherMap\Util\City;
use Cmfcmf\OpenWeatherMap\Util\Location;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Http\Factory\Guzzle\RequestFactory;
use Http\Adapter\Guzzle6\Client as GuzzleAdapter;
use Http\Factory\Guzzle\StreamFactory;
use Mjelamanov\GuzzlePsr18\Client;
use Psr\Http\Message\ResponseInterface;
use Psr\SimpleCache\CacheInterface;

class OpenWeatherMapTest extends MyTestCase
@@ -144,6 +156,151 @@ public function testGetForecastUVIndex()
$this->assertContainsOnlyInstancesOf('\Cmfcmf\OpenWeatherMap\UVIndex', $result);
}

public function coordinatesByLocationNameUrlDataProvider(): array
{
return [
[
'Bundaberg',
sprintf(
'http://api.openweathermap.org/geo/1.0/direct?appid=%s&q=%s',
'2f8796eefe67558dc205b09dd336d022',
'Bundaberg'
)
],
[
'Bundaberg',
sprintf(
'http://api.openweathermap.org/geo/1.0/direct?appid=%s&q=%s%%2C%s',
'2f8796eefe67558dc205b09dd336d022',
'Bundaberg',
'Queensland'
),
'Queensland'
],
[
'Bundaberg',
sprintf(
'http://api.openweathermap.org/geo/1.0/direct?appid=%s&q=%s%%2C%s%%2C%s',
'2f8796eefe67558dc205b09dd336d022',
'Bundaberg',
'Queensland',
'AU'
),
'Queensland',
'AU',
],
[
'Bundaberg',
sprintf(
'http://api.openweathermap.org/geo/1.0/direct?appid=%s&q=%s%%2C%%2C%s&limit=%d',
'2f8796eefe67558dc205b09dd336d022',
'Bundaberg',
'AU',
20
),
null,
'AU',
20,
],
[
'Bundaberg',
sprintf(
'http://api.openweathermap.org/geo/1.0/direct?appid=%s&q=%s&limit=%d',
'2f8796eefe67558dc205b09dd336d022',
'Bundaberg',
20
),
null,
null,
20,
],
];
}

/**
* @dataProvider coordinatesByLocationNameUrlDataProvider
*/
public function testCorrectlyBuildsCoordinatesByLocationNameUrl(
$city,
$generatedUrl,
$stateCode = null,
$countryCode = null,
$limit = null
) {
$requestFactory = $this->createMock(RequestFactory::class);
$requestFactory
->expects($this->once())
->method('createRequest')
->with('GET', $generatedUrl);

$response = $this->createMock(ResponseInterface::class);
$response
->method('getBody')
->willReturn((new StreamFactory())->createStream('{}'));
$response
->method('getStatusCode')
->willReturn(200);
$httpClient = $this->createMock(Client::class);
$httpClient
->expects($this->once())
->method('sendRequest')
->willReturn($response);

$this->owm = new OpenWeatherMap(
$this->apiKey,
$httpClient,
$requestFactory
);
$data = $this->owm->getCoordinatesByLocationName($city, $stateCode, $countryCode, $limit);
}

public function testRetrieveCoordinatesByLocationName()
{
$result = <<<EOF
[{"name":"Bundaberg","local_names":{"ar":"بوندابيرج"},"zh":"班达伯格","en":"Bundaberg","ja":"バンダバーグ","ru":"Бундаберг","uk":"Бундаберг","lat":-24.8653253,"lon":152.3516785,"country":"AU","state":"Queensland"}]
EOF;

$expected = [
new City (
-1,
'Bundaberg',
-24.8653253,
152.3516785,
"AU",
null,
null,
"Queensland",
[
"ar" => "بوندابيرج",
"en" => "Bundaberg",
"ja" => "バンダバーグ",
"ru" => "Бундаберг",
"uk" => "Бундаберг",
"zh" => "班达伯格",
]
),
];

$mock = new MockHandler([
new Response(200, [], $result),
]);

$handlerStack = HandlerStack::create($mock);
$httpClient = new Client(
new GuzzleClient(['handler' => $handlerStack])
);
Comment on lines +288 to +291
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you use TestHttpClient from the tests folder instead of introducing a new dependency?


$this->owm = new OpenWeatherMap(
$this->apiKey,
$httpClient,
$this->createMock(RequestFactory::class)
);
$owm = $this->openWeather;
$data = $owm->getCoordinatesByLocationName('Bundaberg');

$this->assertEquals($expected, $data);
}

public function testGetHistoryUVIndex()
{
$owm = $this->openWeather;