Skip to content

Commit

Permalink
Adds the HttpFacadeDownloader
Browse files Browse the repository at this point in the history
  • Loading branch information
peterfox committed Jan 10, 2024
1 parent d6f077b commit 9d51402
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/Downloaders/HttpFacadeDownloader.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace Spatie\MediaLibrary\Downloaders;

use Illuminate\Support\Facades\Http;
use Spatie\MediaLibrary\MediaCollections\Exceptions\UnreachableUrl;

class HttpFacadeDownloader implements Downloader
{
public function getTempFile(string $url): string
{
$temporaryFile = tempnam(sys_get_temp_dir(), 'media-library');

Http::withUserAgent('Spatie MediaLibrary')
->throw(fn () => throw new UnreachableUrl($url))
->sink($temporaryFile)
->get($url);

return $temporaryFile;
}
}
28 changes: 28 additions & 0 deletions tests/Downloader/HttpFacadeDownloaderTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

it('can save a url to a temp location', function () {
$url = '';

\Illuminate\Support\Facades\Http::shouldReceive('withUserAgent')
->with('Spatie MediaLibrary')
->once()
->andReturnSelf()
->getMock()
->shouldReceive('throw')
->once()
->andReturnSelf()
->getMock()
->shouldReceive('sink')
->once()
->andReturnSelf()
->getMock()
->shouldReceive('get')
->with($url)
->once();

$downloader = new \Spatie\MediaLibrary\Downloaders\HttpFacadeDownloader();

$result = $downloader->getTempFile($url);

expect($result)->toBeString();
});

0 comments on commit 9d51402

Please sign in to comment.