Skip to content

Commit

Permalink
Error handling in importer for invalid ZIP
Browse files Browse the repository at this point in the history
  • Loading branch information
korridor committed Apr 22, 2024
1 parent 26af704 commit 2605d73
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
8 changes: 7 additions & 1 deletion app/Service/Import/Importers/TogglDataImporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Exception;
use Spatie\TemporaryDirectory\TemporaryDirectory;
use ValueError;
use ZipArchive;

class TogglDataImporter extends DefaultImporter
Expand All @@ -20,7 +21,10 @@ public function importData(string $data): void
$zip = new ZipArchive();
$temporaryDirectory = TemporaryDirectory::make();
file_put_contents($temporaryDirectory->path('import.zip'), $data);
$zip->open($temporaryDirectory->path('import.zip'), ZipArchive::RDONLY);
$res = $zip->open($temporaryDirectory->path('import.zip'), ZipArchive::RDONLY);
if ($res !== true) {
throw new ImportException('Invalid ZIP, error code: '.$res);
}
$temporaryDirectory = TemporaryDirectory::make();
$zip->extractTo($temporaryDirectory->path());
$zip->close();
Expand Down Expand Up @@ -107,6 +111,8 @@ public function importData(string $data): void
], [], (string) $task->id);
}
}
} catch (ValueError $exception) {

} catch (ImportException $exception) {
throw $exception;
} catch (Exception $exception) {
Expand Down
22 changes: 21 additions & 1 deletion tests/Unit/Service/Import/Importer/TogglDataImporterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
namespace Tests\Unit\Service\Import\Importer;

use App\Models\Organization;
use App\Service\Import\Importers\ImportException;
use App\Service\Import\Importers\TogglDataImporter;
use Exception;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Spatie\TemporaryDirectory\TemporaryDirectory;
Expand All @@ -27,6 +29,25 @@ private function createTestZip(string $folder): string
return $zipPath;
}

public function test_import_throws_exception_if_data_is_not_zip(): void
{
// Arrange
$organization = Organization::factory()->create();
$importer = new TogglDataImporter();
$importer->init($organization);

// Act
try {
$importer->importData('not a zip');
} catch (Exception $e) {
$this->assertInstanceOf(ImportException::class, $e);
$this->assertSame('Invalid ZIP, error code: 19', $e->getMessage());

return;
}
$this->fail();
}

public function test_import_of_test_file_succeeds(): void
{
// Arrange
Expand All @@ -48,7 +69,6 @@ public function test_import_of_test_file_succeeds(): void
$this->assertSame(1, $report->usersCreated);
$this->assertSame(2, $report->projectsCreated);
$this->assertSame(1, $report->clientsCreated);

}

public function test_import_of_test_file_twice_succeeds(): void
Expand Down

0 comments on commit 2605d73

Please sign in to comment.