Compare commits

..

13 Commits

Author SHA1 Message Date
35a37a1eae Improve method names 2024-09-26 10:19:07 +01:00
9a7e6b01cb Change tests to accept an interface 2024-09-26 10:17:44 +01:00
35d5c324e2 Add method to get compiler to stop crying 2024-09-26 10:17:30 +01:00
dd2f8a76d6 Change geocoder to use geocode data 2024-09-26 09:59:10 +01:00
ab4bbd0574 Change file name 2024-09-26 09:58:43 +01:00
2aa5cb731e Add get geocode data method to interface 2024-09-26 09:51:21 +01:00
2f54e01fdd Update docblock 2024-09-26 09:44:48 +01:00
40fc3f59f8 Update changelog 2024-09-26 09:42:45 +01:00
d8ecb41ac3 Add test to return false on is geocoded if coords are 0 0 2024-09-26 09:41:54 +01:00
brabli
214fcc2bac Add changelog 2024-08-05 14:58:58 +01:00
brabli
070279e8d4 Update readme 2024-08-05 14:55:00 +01:00
brabli
10d1d3c318 Update docblocks 2024-08-05 14:50:26 +01:00
brabli
8b662ebfa3 Rename Mappable stuff to Geocode stuff, change dir structure 2024-08-05 14:25:03 +01:00
8 changed files with 126 additions and 68 deletions

8
CHANGELOG.md Normal file
View File

@@ -0,0 +1,8 @@
# Changelog
## [x.x.x] xxxx-xx-xx
- Coordinates set to 0, 0 will cause isGeocoded to return false
## [1.0.0] 2024-08-05
- First major version release

View File

@@ -1 +1,6 @@
Readme # PCM Geocode Bundle
Provides an interface/trait combo to add latitude and longitude fields to an entity.
Also included is a `Geocoder` service which accepts a postcode and attempts to return a `GeoCoordinates` object which contains the latitude and longitude of the postcode.

View File

@@ -1,18 +0,0 @@
<?php
declare(strict_types=1);
namespace Pcm\GeocodeBundle\Entity\Interface;
interface MappableInterface
{
public function getLatitude(): ?float;
public function getLongitude(): ?float;
public function setLatitude(float $lat): self;
public function setLongitude(float $lon): self;
public function isGeocoded(): bool;
}

View File

@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace Pcm\GeocodeBundle\Interface\Entity;
/**
* Defines latitude and longitude getters and setters
*/
interface GeocodeInterface
{
public function getLatitude(): ?float;
public function getLongitude(): ?float;
public function setLatitude(float $lat): self;
public function setLongitude(float $lon): self;
/**
* Used by {@see Pcm\GeocodeBundle\Service\Geocoder} to retrieve raw data for geocoding.
*
* @return string Data to use when geocodind an entity
*/
public function getGeocodeData(): string;
/**
* @return bool True if both latitude and longitude are set and are not (0, 0)
*/
public function isGeocoded(): bool;
}

View File

@@ -6,10 +6,14 @@ namespace Pcm\GeocodeBundle\Service;
use Pcm\GeocodeBundle\Exception\ApiErrorException; use Pcm\GeocodeBundle\Exception\ApiErrorException;
use Pcm\GeocodeBundle\Exception\NoResultsFoundException; use Pcm\GeocodeBundle\Exception\NoResultsFoundException;
use Pcm\GeocodeBundle\Interface\Entity\GeocodeInterface;
use Pcm\GeocodeBundle\Model\GeoCoordinates; use Pcm\GeocodeBundle\Model\GeoCoordinates;
use Symfony\Contracts\HttpClient\HttpClientInterface; use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface; use Symfony\Contracts\HttpClient\ResponseInterface;
/**
* Find the geo-coordinates of a postcode
*/
final class Geocoder final class Geocoder
{ {
private const string API_URL = "https://nominatim.openstreetmap.org/search"; private const string API_URL = "https://nominatim.openstreetmap.org/search";
@@ -17,23 +21,28 @@ final class Geocoder
public function __construct(private HttpClientInterface $client) {} public function __construct(private HttpClientInterface $client) {}
/** /**
* Convert a postcode into latitude and longitude. Returns null if conversion failed. * Find and return the geo-coordinates of an entity
* *
* @param string $postcode * @param GeocodeInterface $entity
* @return null|GeoCoordinates *
* @return GeoCoordinates
*
* @throws NoResultsFoundException when no results were found for the provided postcode
* @throws ApiErrorException when the API response contains an error
*/ */
public function geocodePostcode(string $postcode): ?GeoCoordinates public function geocode(GeocodeInterface $entity): GeoCoordinates
{ {
$geocodeData = $entity->getGeocodeData();
$client = $this->createClient(); $client = $this->createClient();
$response = $this->makeApiRequest($client, $postcode); $response = $this->makeApiRequest($client, $geocodeData);
$data = $this->getDataFromResponse($response); $data = $this->getDataFromResponse($response);
if (array_key_exists('error', $data)) { if (array_key_exists('error', $data)) {
throw new ApiErrorException($postcode, $data['error']['message']); throw new ApiErrorException($geocodeData, $data['error']['message']);
} }
if (empty($data)) { if (empty($data)) {
throw new NoResultsFoundException($postcode, "No results found."); throw new NoResultsFoundException($geocodeData, "No results found.");
} }
return $this->createGeoCoordinates($data); return $this->createGeoCoordinates($data);
@@ -46,7 +55,7 @@ final class Geocoder
]); ]);
} }
private function makeApiRequest(HttpClientInterface $client, string $postcode): ResponseInterface private function makeApiRequest(HttpClientInterface $client, string $geocodeData): ResponseInterface
{ {
return $client->request( return $client->request(
method: 'GET', method: 'GET',
@@ -54,7 +63,7 @@ final class Geocoder
options: [ options: [
'query' => [ 'query' => [
'format' => 'json', 'format' => 'json',
'postalcode' => $postcode 'q' => $geocodeData
] ]
] ]
); );

View File

@@ -2,18 +2,16 @@
declare(strict_types=1); declare(strict_types=1);
namespace Pcm\GeocodeBundle\Entity\Trait; namespace Pcm\GeocodeBundle\Trait\Entity;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
/** /**
* Allows an entity to be mapped via latitude and longitude coordinates * Implementation of {@see Pcm\GeocodeBundle\Interface\Entity\GeocodeInterface}
*
* Use MappableInterface
* *
* @package Pcm\GeocodeBundle * @package Pcm\GeocodeBundle
*/ */
trait MappableTrait trait GeocodeTrait
{ {
#[ORM\Column(type: 'decimal', precision: 10, scale: 6, nullable: true)] #[ORM\Column(type: 'decimal', precision: 10, scale: 6, nullable: true)]
private ?float $latitude = null; private ?float $latitude = null;
@@ -45,13 +43,9 @@ trait MappableTrait
return $this; return $this;
} }
/**
* Returns true if both latitude and longitude have been set
*
* @return bool
*/
public function isGeocoded(): bool public function isGeocoded(): bool
{ {
return null !== $this->getLatitude() && null !== $this->getLongitude(); return null !== $this->getLatitude() && null !== $this->getLongitude() && (0.0 !== $this->getLatitude() && 0.0 !== $this->getLongitude());
} }
} }

View File

@@ -4,8 +4,8 @@ declare(strict_types=1);
namespace Pcm\GeocodeBundle\Tests; namespace Pcm\GeocodeBundle\Tests;
use Pcm\GeocodeBundle\Entity\Interface\MappableInterface; use Pcm\GeocodeBundle\Interface\Entity\GeocodeInterface;
use Pcm\GeocodeBundle\Entity\Trait\MappableTrait; use Pcm\GeocodeBundle\Trait\Entity\GeocodeTrait;
use Pcm\GeocodeBundle\Exception\ApiErrorException; use Pcm\GeocodeBundle\Exception\ApiErrorException;
use Pcm\GeocodeBundle\Exception\NoResultsFoundException; use Pcm\GeocodeBundle\Exception\NoResultsFoundException;
use Pcm\GeocodeBundle\Model\GeoCoordinates; use Pcm\GeocodeBundle\Model\GeoCoordinates;
@@ -16,7 +16,7 @@ use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
/** /**
* We sleep 1 second after API calls to prevent breaking the API T&Cs. * We sleep 1 second after API calls to prevent breaking the API T&Cs.
*/ */
final class GeocodeTest extends KernelTestCase final class GeocoderTest extends KernelTestCase
{ {
// Buckingham Palace // Buckingham Palace
private const string POSTCODE = 'SW1A 1AA'; private const string POSTCODE = 'SW1A 1AA';
@@ -30,38 +30,36 @@ final class GeocodeTest extends KernelTestCase
$this->geocoder = $kernel->getContainer()->get('pcm_geocode.geocoder'); $this->geocoder = $kernel->getContainer()->get('pcm_geocode.geocoder');
} }
public function testGeocodeInstance(): void public function testGeocodeThrowsOnEmptyInput(): void
{
$this->assertInstanceOf(Geocoder::class, $this->geocoder);
}
public function testGeocodePostcodeThrowsOnEmptyInput(): void
{ {
sleep(1); sleep(1);
$this->expectException(ApiErrorException::class); $this->expectException(ApiErrorException::class);
$entity = $this->createEntity('');
$this->expectExceptionMessageMatches("/Nothing to search for.$/"); $this->expectExceptionMessageMatches("/Nothing to search for.$/");
$this->geocoder->geocodePostcode(''); $this->geocoder->geocode($entity);
} }
public function testGeocodePostcodeThrowsOnInvalidPostcode(): void public function testGeocodeThrowsOnInvalidPostcode(): void
{ {
sleep(1); sleep(1);
$this->expectException(NoResultsFoundException::class); $this->expectException(NoResultsFoundException::class);
$this->expectExceptionMessageMatches("/No results found.$/"); $this->expectExceptionMessageMatches("/No results found.$/");
$this->geocoder->geocodePostcode('ZZZZZZZZZZZZ'); $entity = $this->createEntity('Invalid Postcode');
$this->geocoder->geocode($entity);
} }
public function testGeocodePostcodeReturnsGeoCoordinates(): GeoCoordinates public function testGeocodeReturnsGeoCoordinates(): GeoCoordinates
{ {
sleep(1); sleep(1);
$geoCoords = $this->geocoder->geocodePostcode(self::POSTCODE); $entity = $this->createEntity(self::POSTCODE);
$geoCoords = $this->geocoder->geocode($entity);
$this->assertNotNull($geoCoords); $this->assertNotNull($geoCoords);
return $geoCoords; return $geoCoords;
} }
/** /**
* @depends testGeocodePostcodeReturnsGeoCoordinates * @depends testGeocodeReturnsGeoCoordinates
*/ */
public function testCoordinatesAreSet(GeoCoordinates $geoCoordinates): void public function testCoordinatesAreSet(GeoCoordinates $geoCoordinates): void
{ {
@@ -69,12 +67,30 @@ final class GeocodeTest extends KernelTestCase
$this->assertIsFloat($geoCoordinates->longitude); $this->assertIsFloat($geoCoordinates->longitude);
} }
private function getMappableEntity(): MappableInterface private function getGeocodableEntity(): GeocodeInterface
{ {
return new class implements MappableInterface return new class implements GeocodeInterface
{ {
use MappableTrait; use GeocodeTrait;
}; };
} }
private function createEntity(string $data): GeocodeInterface
{
$entity = new class implements GeocodeInterface {
use GeocodeTrait;
public string $data;
public function getGeocodeData(): string
{
return $this->data;
}
};
$entity->data = $data;
return $entity;
}
} }

View File

@@ -4,15 +4,15 @@ declare(strict_types=1);
namespace Pcm\GeocodeBundle\Tests; namespace Pcm\GeocodeBundle\Tests;
use Pcm\GeocodeBundle\Entity\Interface\MappableInterface; use Pcm\GeocodeBundle\Interface\Entity\GeocodeInterface;
use Pcm\GeocodeBundle\Entity\Trait\MappableTrait; use Pcm\GeocodeBundle\Trait\Entity\GeocodeTrait;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
final class MappableTraitTest extends TestCase final class GeocodeTraitTest extends TestCase
{ {
private const float COORD = 123.456; private const float COORD = 123.456;
private MappableInterface $obj; private GeocodeInterface $obj;
protected function setUp(): void protected function setUp(): void
{ {
@@ -21,7 +21,7 @@ final class MappableTraitTest extends TestCase
public function testSetLatitude(): void public function testSetLatitude(): void
{ {
$this->assertInstanceOf(MappableInterface::class, $this->obj->setLatitude(self::COORD)); $this->assertInstanceOf(GeocodeInterface::class, $this->obj->setLatitude(self::COORD));
} }
public function testGetLatitudeReturnsNull(): void public function testGetLatitudeReturnsNull(): void
@@ -37,7 +37,7 @@ final class MappableTraitTest extends TestCase
public function testSetLongitude(): void public function testSetLongitude(): void
{ {
$this->assertInstanceOf(MappableInterface::class, $this->obj->setLongitude(self::COORD)); $this->assertInstanceOf(GeocodeInterface::class, $this->obj->setLongitude(self::COORD));
} }
public function testGetLongitudeReturnsNull(): void public function testGetLongitudeReturnsNull(): void
@@ -75,18 +75,30 @@ final class MappableTraitTest extends TestCase
$this->assertTrue($this->obj->isGeocoded()); $this->assertTrue($this->obj->isGeocoded());
} }
public function testIsGeocodeReturnsTrueIfLatAndLonAreBothZero(): void public function testIsGeocodedReturnsFalseIfLatAndLonAreBothZero(): void
{ {
$this->obj->setLatitude(0.000); $this->obj->setLatitude(0.000);
$this->obj->setLongitude(0.000); $this->obj->setLongitude(0.000);
$this->assertTrue($this->obj->isGeocoded()); $this->assertFalse($this->obj->isGeocoded());
} }
private function getTraitObject(): MappableInterface public function testIsGeocodedReturnsFalseIfLatAndLonAreBothZeroInts(): void
{ {
return new class implements MappableInterface $this->obj->setLatitude(0);
$this->obj->setLongitude(0);
$this->assertFalse($this->obj->isGeocoded());
}
private function getTraitObject(): GeocodeInterface
{
return new class implements GeocodeInterface
{ {
use MappableTrait; use GeocodeTrait;
public function getGeocodeData(): string
{
return '';
}
}; };
} }
} }