Skip to content
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

Implement Coordinates by Location Name endpoint #189

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
Expand Up @@ -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;
Expand Down Expand Up @@ -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.
*/
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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.
*
Expand Down
27 changes: 25 additions & 2 deletions Cmfcmf/OpenWeatherMap/Util/City.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand All @@ -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);
}
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
Loading