From 1e3b2461724b0161a82d079b53446274b88c596c Mon Sep 17 00:00:00 2001 From: Ovidiu U Date: Wed, 22 Apr 2026 12:13:52 +0100 Subject: [PATCH] feat: resolve outcodes from local DB before HTTP --- app/Services/PostcodeService.php | 21 +++++++++++++++++++- tests/Unit/Services/PostcodeServiceTest.php | 22 +++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/app/Services/PostcodeService.php b/app/Services/PostcodeService.php index b093789..7c27a2b 100644 --- a/app/Services/PostcodeService.php +++ b/app/Services/PostcodeService.php @@ -2,6 +2,7 @@ namespace App\Services; +use App\Models\Outcode; use App\Models\Postcode; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Http; @@ -35,7 +36,7 @@ class PostcodeService $result = match (true) { $this->isFullPostcode($query) => $this->lookupLocalPostcode($query) ?? $this->lookupPostcode($query), - $this->isOutcode($query) => $this->lookupOutcode($query), + $this->isOutcode($query) => $this->lookupLocalOutcode($query) ?? $this->lookupOutcode($query), default => $this->lookupPlace($query), }; @@ -74,6 +75,24 @@ class PostcodeService ); } + private function lookupLocalOutcode(string $outcode): ?LocationResult + { + $normalised = strtoupper(trim($outcode)); + + $row = Outcode::find($normalised); + + if ($row === null) { + return null; + } + + return new LocationResult( + query: $outcode, + displayName: $normalised, + lat: $row->lat, + lng: $row->lng, + ); + } + private function formatPostcode(string $normalised): string { // Insert the single space before the last 3 chars ("SW1A1AA" -> "SW1A 1AA"). diff --git a/tests/Unit/Services/PostcodeServiceTest.php b/tests/Unit/Services/PostcodeServiceTest.php index 4d4025b..464ef8e 100644 --- a/tests/Unit/Services/PostcodeServiceTest.php +++ b/tests/Unit/Services/PostcodeServiceTest.php @@ -1,5 +1,6 @@ 'PE7', + 'lat' => 52.536397, + 'lng' => -0.210181, + ]); + + Http::fake(); + + $result = $this->service->resolve('PE7'); + + expect($result)->toBeInstanceOf(LocationResult::class) + ->and($result->displayName)->toBe('PE7') + ->and($result->lat)->toBe(52.536397) + ->and($result->lng)->toBe(-0.210181); + + Http::assertNothingSent(); +});