Skip to content

Commit

Permalink
sets the irght extension when downloading from url
Browse files Browse the repository at this point in the history
  • Loading branch information
QuentinGab committed Jul 29, 2024
1 parent 6a35c25 commit 2d1245b
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
12 changes: 11 additions & 1 deletion src/FileDownloaders/FileDownloader.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Elegantly\Media\FileDownloaders;

use Elegantly\Media\Helpers\File;
use Exception;
use Spatie\TemporaryDirectory\TemporaryDirectory;

Expand All @@ -15,7 +16,7 @@ public static function getTemporaryFile(string $url, ?TemporaryDirectory $tempor
],
]);

if (! $stream = @fopen($url, 'r', false, $context)) {
if (!$stream = @fopen($url, 'r', false, $context)) {
throw new Exception("Can't reach the url: {$url}");
}

Expand All @@ -30,6 +31,15 @@ public static function getTemporaryFile(string $url, ?TemporaryDirectory $tempor

fclose($stream);


if ($extension = File::extension($path)) {
$pathWithExtension = "{$path}.{$extension}";

rename($path, $pathWithExtension);

return $pathWithExtension;
}

return $path;
}
}
2 changes: 1 addition & 1 deletion src/Helpers/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public static function extension(string|HttpFile|UploadedFile $file): ?string
return $file->guessExtension() ?? $file->getExtension();
}

return SupportFile::extension($file);
return SupportFile::extension($file) ?: SupportFile::guessExtension($file);
}

public static function type(string $path): MediaType
Expand Down
19 changes: 19 additions & 0 deletions tests/Unit/FileDownloaderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,22 @@

expect(is_file($path))->toBe(false);
});

it('download a file from an url as a temporary file and sets the right extension', function () {

$temporaryDirectory = (new TemporaryDirectory)
->location(storage_path('media-tmp'))
->create();

$path = FileDownloader::getTemporaryFile(
"https://icon.horse/icon/discord.com",
$temporaryDirectory
);

expect(is_file($path))->toBe(true);
expect(str($path)->endsWith(".png"))->toBe(true);

$temporaryDirectory->delete();

expect(is_file($path))->toBe(false);
});

0 comments on commit 2d1245b

Please sign in to comment.