diff --git a/app/Console/Commands/ImportPostcodes.php b/app/Console/Commands/ImportPostcodes.php index 5317b62..c4fdd90 100644 --- a/app/Console/Commands/ImportPostcodes.php +++ b/app/Console/Commands/ImportPostcodes.php @@ -6,7 +6,6 @@ use Illuminate\Console\Attributes\Description; use Illuminate\Console\Attributes\Signature; use Illuminate\Console\Command; use Illuminate\Support\Facades\DB; -use RuntimeException; #[Signature('postcodes:import {--file= : Path to ONSPD CSV file}')] #[Description('Import UK postcodes (ONSPD) into the local postcodes and outcodes tables')] @@ -27,7 +26,9 @@ final class ImportPostcodes extends Command $handle = fopen($file, 'r'); if ($handle === false) { - throw new RuntimeException("Unable to open {$file}"); + $this->error("Unable to open {$file}."); + + return self::FAILURE; } $header = fgetcsv($handle); @@ -39,6 +40,17 @@ final class ImportPostcodes extends Command return self::FAILURE; } + $headerCounts = array_count_values(array_map('strtolower', $header)); + + foreach (['pcd', 'lat', 'long'] as $required) { + if (($headerCounts[$required] ?? 0) > 1) { + $this->error("Column '{$required}' appears more than once — refusing to import."); + fclose($handle); + + return self::FAILURE; + } + } + $columns = array_change_key_case(array_flip($header), CASE_LOWER); foreach (['pcd', 'lat', 'long'] as $required) { diff --git a/tests/Feature/Console/ImportPostcodesTest.php b/tests/Feature/Console/ImportPostcodesTest.php index 0e9b076..bd43cfb 100644 --- a/tests/Feature/Console/ImportPostcodesTest.php +++ b/tests/Feature/Console/ImportPostcodesTest.php @@ -5,12 +5,14 @@ use Illuminate\Foundation\Testing\RefreshDatabase; uses(RefreshDatabase::class); -function writeOnspdFixture(string $contents): string -{ - $path = tempnam(sys_get_temp_dir(), 'onspd_').'.csv'; - file_put_contents($path, $contents); +if (! function_exists('writeOnspdFixture')) { + function writeOnspdFixture(string $contents): string + { + $path = tempnam(sys_get_temp_dir(), 'onspd_').'.csv'; + file_put_contents($path, $contents); - return $path; + return $path; + } } it('imports active postcodes from an ONSPD CSV', function (): void {