Move geocoder into service folder

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

View File

@@ -2,11 +2,11 @@
declare(strict_types=1);
namespace Pcm\GeocodeBundle;
namespace Pcm\GeocodeBundle\Service;
use Exception;
use Pcm\GeocodeBundle\Data\LatLon;
use Pcm\GeocodeBundle\Entity\GeocodeData;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
@@ -14,13 +14,17 @@ 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): GeocodeData
public function geocodePostcode(string $postcode): LatLon
{
$client = $this->getHttpClient();
$client = $this->setClientHeaders();
$response = $this->makeApiRequest($client, $postcode);
$data = $response->toArray();
$this->throwIfNoResponseData($data);
@@ -28,9 +32,9 @@ class Geocoder
return $this->createGeocodeDataObject($data);
}
private function getHttpClient(): HttpClientInterface
private function setClientHeaders(): HttpClientInterface
{
return HttpClient::create([
return $this->client->withOptions([
'headers' => ["User-Agent" => "Geocode"]
]);
}
@@ -55,12 +59,8 @@ class Geocoder
throw new Exception("No data was received from API response! Were the arguments valid?");
}
private function createGeocodeDataObject(array $data): GeocodeData
private function createGeocodeDataObject(array $data): LatLon
{
$geocodeData = new GeocodeData();
$geocodeData->setLatitude((float) $data[0]['lat']);
$geocodeData->setLongitude((float) $data[0]['lon']);
return $geocodeData;
return new LatLon((float) $data[0]['lat'], (float) $data[0]['lon']);
}
}