From a6c8c4cc0c54821ff2aa906ff1e925b123fa5cbe Mon Sep 17 00:00:00 2001 From: brabli <67018167+Brabli@users.noreply.github.com> Date: Mon, 5 Aug 2024 13:07:04 +0100 Subject: [PATCH] Throw exceptions when something goes wrong instead of returning null --- src/Service/Geocoder.php | 11 ++++++----- tests/Service/GeocodeTest.php | 16 ++++++++++++++-- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/src/Service/Geocoder.php b/src/Service/Geocoder.php index e06c93e..37b306c 100644 --- a/src/Service/Geocoder.php +++ b/src/Service/Geocoder.php @@ -4,6 +4,8 @@ declare(strict_types=1); namespace Pcm\GeocodeBundle\Service; +use Pcm\GeocodeBundle\Exception\ApiErrorException; +use Pcm\GeocodeBundle\Exception\NoResultsFoundException; use Pcm\GeocodeBundle\Model\GeoCoordinates; use Symfony\Contracts\HttpClient\HttpClientInterface; use Symfony\Contracts\HttpClient\ResponseInterface; @@ -26,13 +28,12 @@ final class Geocoder $response = $this->makeApiRequest($client, $postcode); $data = $this->getDataFromResponse($response); - // @todo remove check, I don't think it's needed - if (empty($data)) { - return null; + if (array_key_exists('error', $data)) { + throw new ApiErrorException($postcode, $data['error']['message']); } - if (array_key_exists('error', $data)) { - return null; + if (empty($data)) { + throw new NoResultsFoundException($postcode, "No results found."); } return $this->createGeoCoordinates($data); diff --git a/tests/Service/GeocodeTest.php b/tests/Service/GeocodeTest.php index beb3241..3d8b310 100644 --- a/tests/Service/GeocodeTest.php +++ b/tests/Service/GeocodeTest.php @@ -6,6 +6,8 @@ namespace Pcm\GeocodeBundle\Tests; use Pcm\GeocodeBundle\Entity\Interface\MappableInterface; use Pcm\GeocodeBundle\Entity\Trait\MappableTrait; +use Pcm\GeocodeBundle\Exception\ApiErrorException; +use Pcm\GeocodeBundle\Exception\NoResultsFoundException; use Pcm\GeocodeBundle\Model\GeoCoordinates; use Pcm\GeocodeBundle\Service\Geocoder; use Pcm\GeocodeBundle\Tests\AppKernel; @@ -33,10 +35,20 @@ final class GeocodeTest extends KernelTestCase $this->assertInstanceOf(Geocoder::class, $this->geocoder); } - public function testGeocodePostcodeReturnsNullOnInvalidInput(): void + public function testGeocodePostcodeThrowsOnEmptyInput(): void { sleep(1); - $this->assertNull($this->geocoder->geocodePostcode('')); + $this->expectException(ApiErrorException::class); + $this->expectExceptionMessageMatches("/Nothing to search for.$/"); + $this->geocoder->geocodePostcode(''); + } + + public function testGeocodePostcodeThrowsOnInvalidPostcode(): void + { + sleep(1); + $this->expectException(NoResultsFoundException::class); + $this->expectExceptionMessageMatches("/No results found.$/"); + $this->geocoder->geocodePostcode('ZZZZZZZZZZZZ'); } public function testGeocodePostcodeReturnsGeoCoordinates(): GeoCoordinates