Move geocoder into service folder
This commit is contained in:
@@ -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']);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user