feat: add PostcodeService and price validation with DB constraints
- Add PostcodeService to resolve UK postcodes, outcodes, and place names to coordinates via postcodes.io API with 30-day caching - Add LocationResult value object for resolved location data - Add per-fuel-type price validation (80p-1050p range) to FuelPriceService with warning logs for out-of-range prices - Change price_pence column from unsignedSmallInteger to unsignedMediumInteger in station_prices tables - Add CHECK constraints (5000-50000 range) on price_pence columns as database-level guard - Improve error handling in PollFuelPrices command with file/line/trace output - Add tests for PostcodeService covering full postcodes, outcodes, place names, caching, and error handling - Add test for price validation range checks Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -31,6 +31,8 @@ class PollFuelPrices extends Command
|
|||||||
PricesUpdatedEvent::dispatch($inserted, $fullRefresh);
|
PricesUpdatedEvent::dispatch($inserted, $fullRefresh);
|
||||||
} catch (Throwable $e) {
|
} catch (Throwable $e) {
|
||||||
$this->error("Poll failed: {$e->getMessage()}");
|
$this->error("Poll failed: {$e->getMessage()}");
|
||||||
|
$this->error("In {$e->getFile()}:{$e->getLine()}");
|
||||||
|
$this->line($e->getTraceAsString());
|
||||||
|
|
||||||
return self::FAILURE;
|
return self::FAILURE;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,6 +17,22 @@ class FuelPriceService
|
|||||||
{
|
{
|
||||||
private const string TOKEN_CACHE_KEY = 'fuel_finder_access_token';
|
private const string TOKEN_CACHE_KEY = 'fuel_finder_access_token';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Per-fuel-type valid price range in pence (as returned by the API).
|
||||||
|
* Based on UK all-time records + 30–75% headroom for future spikes.
|
||||||
|
* All-time records: petrol 191.6p, diesel 199.2p (Jul 2022).
|
||||||
|
*
|
||||||
|
* @var array<string, array{min: int, max: int}>
|
||||||
|
*/
|
||||||
|
private const array PRICE_LIMITS_PENCE = [
|
||||||
|
'e10' => ['min' => 80, 'max' => 750],
|
||||||
|
'e5' => ['min' => 80, 'max' => 840],
|
||||||
|
'b7_standard' => ['min' => 80, 'max' => 840],
|
||||||
|
'b7_premium' => ['min' => 80, 'max' => 960],
|
||||||
|
'b10' => ['min' => 80, 'max' => 840],
|
||||||
|
'hvo' => ['min' => 80, 'max' => 1050],
|
||||||
|
];
|
||||||
|
|
||||||
public function __construct(
|
public function __construct(
|
||||||
private readonly StationTaggingService $taggingService,
|
private readonly StationTaggingService $taggingService,
|
||||||
private readonly ApiLogger $apiLogger,
|
private readonly ApiLogger $apiLogger,
|
||||||
@@ -56,6 +72,18 @@ class FuelPriceService
|
|||||||
->withToken($token)
|
->withToken($token)
|
||||||
->get($baseUrl, $params));
|
->get($baseUrl, $params));
|
||||||
|
|
||||||
|
if ($response->notFound()) {
|
||||||
|
break; // No more batches
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $response->successful()) {
|
||||||
|
Log::error('FuelPriceService: price batch returned error', [
|
||||||
|
'batch' => $batch,
|
||||||
|
'status' => $response->status(),
|
||||||
|
]);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
$stations = $response->json() ?? [];
|
$stations = $response->json() ?? [];
|
||||||
} catch (Throwable $e) {
|
} catch (Throwable $e) {
|
||||||
Log::error('FuelPriceService: price batch fetch failed', [
|
Log::error('FuelPriceService: price batch fetch failed', [
|
||||||
@@ -94,6 +122,18 @@ class FuelPriceService
|
|||||||
->withToken($token)
|
->withToken($token)
|
||||||
->get($baseUrl, $params));
|
->get($baseUrl, $params));
|
||||||
|
|
||||||
|
if ($response->notFound()) {
|
||||||
|
break; // No more batches
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $response->successful()) {
|
||||||
|
Log::error('FuelPriceService: station batch returned error', [
|
||||||
|
'batch' => $batch,
|
||||||
|
'status' => $response->status(),
|
||||||
|
]);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
$stations = $response->json() ?? [];
|
$stations = $response->json() ?? [];
|
||||||
} catch (Throwable $e) {
|
} catch (Throwable $e) {
|
||||||
Log::error('FuelPriceService: station batch fetch failed', [
|
Log::error('FuelPriceService: station batch fetch failed', [
|
||||||
@@ -152,6 +192,17 @@ class FuelPriceService
|
|||||||
Station::upsert($rows, ['node_id'], array_keys($rows[0] ?? []));
|
Station::upsert($rows, ['node_id'], array_keys($rows[0] ?? []));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function isValidPrice(FuelType $fuelType, float $pricePence): bool
|
||||||
|
{
|
||||||
|
$limits = self::PRICE_LIMITS_PENCE[$fuelType->value] ?? null;
|
||||||
|
|
||||||
|
if ($limits === null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $pricePence >= $limits['min'] && $pricePence <= $limits['max'];
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Process one batch of API price data.
|
* Process one batch of API price data.
|
||||||
*
|
*
|
||||||
@@ -185,7 +236,20 @@ class FuelPriceService
|
|||||||
continue; // Skip unknown fuel types
|
continue; // Skip unknown fuel types
|
||||||
}
|
}
|
||||||
|
|
||||||
$pricePence = (int) round($priceData['price'] * 100);
|
$rawPrice = (float) $priceData['price'];
|
||||||
|
|
||||||
|
if (! $this->isValidPrice($fuelType, $rawPrice)) {
|
||||||
|
Log::warning('FuelPriceService: price out of valid range — skipped', [
|
||||||
|
'station_id' => $stationId,
|
||||||
|
'fuel_type' => $fuelType->value,
|
||||||
|
'price' => $rawPrice,
|
||||||
|
'limits' => self::PRICE_LIMITS_PENCE[$fuelType->value],
|
||||||
|
]);
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$pricePence = (int) round($rawPrice * 100);
|
||||||
$effectiveAt = Carbon::parse($priceData['price_change_effective_timestamp']);
|
$effectiveAt = Carbon::parse($priceData['price_change_effective_timestamp']);
|
||||||
$reportedAt = Carbon::parse($priceData['price_last_updated']);
|
$reportedAt = Carbon::parse($priceData['price_last_updated']);
|
||||||
$currentPricePence = $currentPrices[$stationId][$fuelType->value]->price_pence ?? null;
|
$currentPricePence = $currentPrices[$stationId][$fuelType->value]->price_pence ?? null;
|
||||||
|
|||||||
13
app/Services/LocationResult.php
Normal file
13
app/Services/LocationResult.php
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
readonly class LocationResult
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
public string $query,
|
||||||
|
public string $displayName,
|
||||||
|
public float $lat,
|
||||||
|
public float $lng,
|
||||||
|
) {}
|
||||||
|
}
|
||||||
154
app/Services/PostcodeService.php
Normal file
154
app/Services/PostcodeService.php
Normal file
@@ -0,0 +1,154 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
use Illuminate\Support\Facades\Cache;
|
||||||
|
use Illuminate\Support\Facades\Http;
|
||||||
|
use Illuminate\Support\Facades\Log;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
class PostcodeService
|
||||||
|
{
|
||||||
|
private const string BASE_URL = 'https://api.postcodes.io';
|
||||||
|
|
||||||
|
private const int CACHE_TTL = 60 * 60 * 24 * 30; // 30 days
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
private readonly ApiLogger $apiLogger,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve a UK location query (full postcode, outcode, or place name) to coordinates.
|
||||||
|
* Returns null if the location cannot be resolved.
|
||||||
|
*/
|
||||||
|
public function resolve(string $query): ?LocationResult
|
||||||
|
{
|
||||||
|
$query = trim($query);
|
||||||
|
$cacheKey = 'postcode:'.strtolower(preg_replace('/\s+/', '', $query));
|
||||||
|
|
||||||
|
$cached = Cache::get($cacheKey);
|
||||||
|
|
||||||
|
if ($cached !== null) {
|
||||||
|
return $cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
$result = match (true) {
|
||||||
|
$this->isFullPostcode($query) => $this->lookupPostcode($query),
|
||||||
|
$this->isOutcode($query) => $this->lookupOutcode($query),
|
||||||
|
default => $this->lookupPlace($query),
|
||||||
|
};
|
||||||
|
|
||||||
|
if ($result !== null) {
|
||||||
|
Cache::put($cacheKey, $result, self::CACHE_TTL);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function isFullPostcode(string $query): bool
|
||||||
|
{
|
||||||
|
return (bool) preg_match('/^[A-Z]{1,2}[0-9][0-9A-Z]?\s*[0-9][A-Z]{2}$/i', $query);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function isOutcode(string $query): bool
|
||||||
|
{
|
||||||
|
return (bool) preg_match('/^[A-Z]{1,2}[0-9][0-9A-Z]?$/i', $query);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function lookupPostcode(string $postcode): ?LocationResult
|
||||||
|
{
|
||||||
|
$normalised = strtoupper(preg_replace('/\s+/', '', $postcode));
|
||||||
|
$url = self::BASE_URL.'/postcodes/'.$normalised;
|
||||||
|
|
||||||
|
try {
|
||||||
|
$response = $this->apiLogger->send('postcodes_io', 'GET', $url, fn () => Http::timeout(10)->get($url));
|
||||||
|
|
||||||
|
if (! $response->successful()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$data = $response->json('result');
|
||||||
|
|
||||||
|
return new LocationResult(
|
||||||
|
query: $postcode,
|
||||||
|
displayName: $data['postcode'],
|
||||||
|
lat: $data['latitude'],
|
||||||
|
lng: $data['longitude'],
|
||||||
|
);
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
Log::error('PostcodeService: postcode lookup failed', [
|
||||||
|
'postcode' => $postcode,
|
||||||
|
'error' => $e->getMessage(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function lookupOutcode(string $outcode): ?LocationResult
|
||||||
|
{
|
||||||
|
$normalised = strtoupper(trim($outcode));
|
||||||
|
$url = self::BASE_URL.'/outcodes/'.$normalised;
|
||||||
|
|
||||||
|
try {
|
||||||
|
$response = $this->apiLogger->send('postcodes_io', 'GET', $url, fn () => Http::timeout(10)->get($url));
|
||||||
|
|
||||||
|
if (! $response->successful()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$data = $response->json('result');
|
||||||
|
|
||||||
|
return new LocationResult(
|
||||||
|
query: $outcode,
|
||||||
|
displayName: $data['outcode'],
|
||||||
|
lat: $data['latitude'],
|
||||||
|
lng: $data['longitude'],
|
||||||
|
);
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
Log::error('PostcodeService: outcode lookup failed', [
|
||||||
|
'outcode' => $outcode,
|
||||||
|
'error' => $e->getMessage(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function lookupPlace(string $place): ?LocationResult
|
||||||
|
{
|
||||||
|
$url = self::BASE_URL.'/places';
|
||||||
|
$logUrl = $url.'?q='.urlencode($place).'&limit=1';
|
||||||
|
|
||||||
|
try {
|
||||||
|
$response = $this->apiLogger->send('postcodes_io', 'GET', $logUrl, fn () => Http::timeout(10)
|
||||||
|
->get($url, ['q' => $place, 'limit' => 1]));
|
||||||
|
|
||||||
|
if (! $response->successful()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$results = $response->json('result');
|
||||||
|
|
||||||
|
if (empty($results)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$data = $results[0];
|
||||||
|
|
||||||
|
return new LocationResult(
|
||||||
|
query: $place,
|
||||||
|
displayName: $data['name_1'],
|
||||||
|
lat: $data['latitude'],
|
||||||
|
lng: $data['longitude'],
|
||||||
|
);
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
Log::error('PostcodeService: place lookup failed', [
|
||||||
|
'place' => $place,
|
||||||
|
'error' => $e->getMessage(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Run the migrations.
|
||||||
|
*/
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('station_prices', function (Blueprint $table): void {
|
||||||
|
$table->unsignedMediumInteger('price_pence')
|
||||||
|
->comment('Price in pence × 100, e.g. 15990 = 159.90p')
|
||||||
|
->change();
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::table('station_prices_current', function (Blueprint $table): void {
|
||||||
|
$table->unsignedMediumInteger('price_pence')
|
||||||
|
->comment('Price in pence × 100, e.g. 15990 = 159.90p')
|
||||||
|
->change();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reverse the migrations.
|
||||||
|
*/
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('station_prices', function (Blueprint $table): void {
|
||||||
|
$table->unsignedSmallInteger('price_pence')
|
||||||
|
->comment('Price in pence × 100')
|
||||||
|
->change();
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::table('station_prices_current', function (Blueprint $table): void {
|
||||||
|
$table->unsignedSmallInteger('price_pence')
|
||||||
|
->comment('Price in pence × 100, e.g. 15990 = 159.90p')
|
||||||
|
->change();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add database-level CHECK constraint on price_pence (MySQL only).
|
||||||
|
*
|
||||||
|
* Range: 5 000–50 000 = 50p–500p per litre.
|
||||||
|
* This is a broad last-resort guard; the application layer enforces
|
||||||
|
* tighter per-fuel-type limits before any insert reaches the DB.
|
||||||
|
*/
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
if (DB::getDriverName() !== 'mysql') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
DB::statement('ALTER TABLE station_prices ADD CONSTRAINT chk_price_pence_range CHECK (price_pence BETWEEN 5000 AND 50000)');
|
||||||
|
DB::statement('ALTER TABLE station_prices_current ADD CONSTRAINT chk_current_price_pence_range CHECK (price_pence BETWEEN 5000 AND 50000)');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
if (DB::getDriverName() !== 'mysql') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
DB::statement('ALTER TABLE station_prices DROP CHECK chk_price_pence_range');
|
||||||
|
DB::statement('ALTER TABLE station_prices_current DROP CHECK chk_current_price_pence_range');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -252,6 +252,51 @@ it('skips unknown fuel types without error', function (): void {
|
|||||||
->and(StationPrice::count())->toBe(0);
|
->and(StationPrice::count())->toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('skips prices outside valid range and logs a warning', function (): void {
|
||||||
|
Cache::put('fuel_finder_access_token', 'tok', 3540);
|
||||||
|
|
||||||
|
Station::factory()->create(['node_id' => 'sta1']);
|
||||||
|
|
||||||
|
Http::fake([
|
||||||
|
'*/pfs/fuel-prices*' => Http::sequence()
|
||||||
|
->push([
|
||||||
|
[
|
||||||
|
'node_id' => 'sta1',
|
||||||
|
'fuel_prices' => [
|
||||||
|
// Way too high — clearly bad data
|
||||||
|
[
|
||||||
|
'fuel_type' => 'E10',
|
||||||
|
'price' => 900.0,
|
||||||
|
'price_last_updated' => '2026-04-04T10:00:00.000Z',
|
||||||
|
'price_change_effective_timestamp' => '2026-04-04T10:00:00.000Z',
|
||||||
|
],
|
||||||
|
// Too low — below minimum
|
||||||
|
[
|
||||||
|
'fuel_type' => 'E5',
|
||||||
|
'price' => 10.0,
|
||||||
|
'price_last_updated' => '2026-04-04T10:00:00.000Z',
|
||||||
|
'price_change_effective_timestamp' => '2026-04-04T10:00:00.000Z',
|
||||||
|
],
|
||||||
|
// Valid — should be inserted
|
||||||
|
[
|
||||||
|
'fuel_type' => 'B7_STANDARD',
|
||||||
|
'price' => 155.9,
|
||||||
|
'price_last_updated' => '2026-04-04T10:00:00.000Z',
|
||||||
|
'price_change_effective_timestamp' => '2026-04-04T10:00:00.000Z',
|
||||||
|
],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
])
|
||||||
|
->push([]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$inserted = $this->service->pollPrices();
|
||||||
|
|
||||||
|
expect($inserted)->toBe(1)
|
||||||
|
->and(StationPrice::count())->toBe(1)
|
||||||
|
->and(StationPrice::first()->price_pence)->toBe(15590);
|
||||||
|
});
|
||||||
|
|
||||||
it('stops pagination when an empty batch is returned', function (): void {
|
it('stops pagination when an empty batch is returned', function (): void {
|
||||||
Cache::put('fuel_finder_access_token', 'tok', 3540);
|
Cache::put('fuel_finder_access_token', 'tok', 3540);
|
||||||
|
|
||||||
|
|||||||
173
tests/Unit/Services/PostcodeServiceTest.php
Normal file
173
tests/Unit/Services/PostcodeServiceTest.php
Normal file
@@ -0,0 +1,173 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Services\ApiLogger;
|
||||||
|
use App\Services\LocationResult;
|
||||||
|
use App\Services\PostcodeService;
|
||||||
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
|
use Illuminate\Support\Facades\Cache;
|
||||||
|
use Illuminate\Support\Facades\Http;
|
||||||
|
|
||||||
|
uses(RefreshDatabase::class);
|
||||||
|
|
||||||
|
beforeEach(function (): void {
|
||||||
|
$this->service = new PostcodeService(new ApiLogger);
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Full postcode ---
|
||||||
|
|
||||||
|
it('resolves a full postcode to coordinates', function (): void {
|
||||||
|
Http::fake([
|
||||||
|
'*/postcodes/SW1A1AA' => Http::response([
|
||||||
|
'status' => 200,
|
||||||
|
'result' => [
|
||||||
|
'postcode' => 'SW1A 1AA',
|
||||||
|
'latitude' => 51.501009,
|
||||||
|
'longitude' => -0.141588,
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$result = $this->service->resolve('SW1A 1AA');
|
||||||
|
|
||||||
|
expect($result)->toBeInstanceOf(LocationResult::class)
|
||||||
|
->and($result->displayName)->toBe('SW1A 1AA')
|
||||||
|
->and($result->lat)->toBe(51.501009)
|
||||||
|
->and($result->lng)->toBe(-0.141588);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('normalises postcode spacing before lookup', function (): void {
|
||||||
|
Http::fake([
|
||||||
|
'*/postcodes/SW1A1AA' => Http::response([
|
||||||
|
'status' => 200,
|
||||||
|
'result' => [
|
||||||
|
'postcode' => 'SW1A 1AA',
|
||||||
|
'latitude' => 51.501009,
|
||||||
|
'longitude' => -0.141588,
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$result = $this->service->resolve('sw1a1aa');
|
||||||
|
|
||||||
|
expect($result)->not->toBeNull()
|
||||||
|
->and($result->displayName)->toBe('SW1A 1AA');
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Outcode ---
|
||||||
|
|
||||||
|
it('resolves an outcode to coordinates', function (): void {
|
||||||
|
Http::fake([
|
||||||
|
'*/outcodes/PE7' => Http::response([
|
||||||
|
'status' => 200,
|
||||||
|
'result' => [
|
||||||
|
'outcode' => 'PE7',
|
||||||
|
'latitude' => 52.536397,
|
||||||
|
'longitude' => -0.210181,
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$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);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resolves a lowercase outcode', function (): void {
|
||||||
|
Http::fake([
|
||||||
|
'*/outcodes/M1' => Http::response([
|
||||||
|
'status' => 200,
|
||||||
|
'result' => [
|
||||||
|
'outcode' => 'M1',
|
||||||
|
'latitude' => 53.480957,
|
||||||
|
'longitude' => -2.237428,
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$result = $this->service->resolve('m1');
|
||||||
|
|
||||||
|
expect($result)->not->toBeNull()
|
||||||
|
->and($result->displayName)->toBe('M1');
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Place name ---
|
||||||
|
|
||||||
|
it('resolves a city name to coordinates', function (): void {
|
||||||
|
Http::fake([
|
||||||
|
'*/places*' => Http::response([
|
||||||
|
'status' => 200,
|
||||||
|
'result' => [
|
||||||
|
[
|
||||||
|
'name_1' => 'Manchester',
|
||||||
|
'latitude' => 53.480957,
|
||||||
|
'longitude' => -2.237428,
|
||||||
|
],
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$result = $this->service->resolve('Manchester');
|
||||||
|
|
||||||
|
expect($result)->toBeInstanceOf(LocationResult::class)
|
||||||
|
->and($result->displayName)->toBe('Manchester')
|
||||||
|
->and($result->lat)->toBe(53.480957)
|
||||||
|
->and($result->lng)->toBe(-2.237428);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns null when place name yields no results', function (): void {
|
||||||
|
Http::fake([
|
||||||
|
'*/places*' => Http::response([
|
||||||
|
'status' => 200,
|
||||||
|
'result' => [],
|
||||||
|
]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$result = $this->service->resolve('Narnia');
|
||||||
|
|
||||||
|
expect($result)->toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Caching ---
|
||||||
|
|
||||||
|
it('caches a successful resolution for 30 days', function (): void {
|
||||||
|
Http::fake([
|
||||||
|
'*/outcodes/PE7' => Http::response([
|
||||||
|
'status' => 200,
|
||||||
|
'result' => [
|
||||||
|
'outcode' => 'PE7',
|
||||||
|
'latitude' => 52.536397,
|
||||||
|
'longitude' => -0.210181,
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->service->resolve('PE7');
|
||||||
|
$this->service->resolve('PE7');
|
||||||
|
|
||||||
|
Http::assertSentCount(1);
|
||||||
|
expect(Cache::get('postcode:pe7'))->toBeInstanceOf(LocationResult::class);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not cache failed lookups', function (): void {
|
||||||
|
Http::fake([
|
||||||
|
'*/postcodes/ZZ99ZZ' => Http::response(['status' => 404], 404),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$result = $this->service->resolve('ZZ9 9ZZ');
|
||||||
|
|
||||||
|
expect($result)->toBeNull()
|
||||||
|
->and(Cache::get('postcode:zz99zz'))->toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns null and does not throw on API failure', function (): void {
|
||||||
|
Http::fake([
|
||||||
|
'*/outcodes/PE7' => Http::response([], 500),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$result = $this->service->resolve('PE7');
|
||||||
|
|
||||||
|
expect($result)->toBeNull();
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user