Move geocoder into service folder

This commit is contained in:
Brabli
2022-07-20 21:49:26 +01:00
parent 827d528c64
commit 59bdb63c09

66
src/Service/Geocoder.php Normal file
View File

@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace Pcm\GeocodeBundle\Service;
use Exception;
use Pcm\GeocodeBundle\Data\LatLon;
use Pcm\GeocodeBundle\Entity\GeocodeData;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
class Geocoder
{
private const API_URL = "https://nominatim.openstreetmap.org/search";
public function __construct(private HttpClientInterface $client) {}
/**
* Returns a LatLon object
*
* @param string $postcode
* @return GeocodeData
*/
public function geocodePostcode(string $postcode): LatLon
{
$client = $this->setClientHeaders();
$response = $this->makeApiRequest($client, $postcode);
$data = $response->toArray();
$this->throwIfNoResponseData($data);
return $this->createGeocodeDataObject($data);
}
private function setClientHeaders(): HttpClientInterface
{
return $this->client->withOptions([
'headers' => ["User-Agent" => "Geocode"]
]);
}
private function makeApiRequest(HttpClientInterface $client, string $postcode): ResponseInterface
{
return $client->request(
method: 'GET',
url: self::API_URL,
options: [
'query' => [
'format' => 'json',
'postalcode' => $postcode
]
]
);
}
private function throwIfNoResponseData(array $data): void
{
if (empty($data))
throw new Exception("No data was received from API response! Were the arguments valid?");
}
private function createGeocodeDataObject(array $data): LatLon
{
return new LatLon((float) $data[0]['lat'], (float) $data[0]['lon']);
}
}