Skip to content

Commit

Permalink
add file from remote url
Browse files Browse the repository at this point in the history
  • Loading branch information
freekmurze committed Nov 7, 2015
1 parent 0f80ad1 commit 0498de5
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 18 deletions.
16 changes: 10 additions & 6 deletions src/HasMedia/HasMediaTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,19 @@ public function addMedia($file)

public function addMediaFromUrl($url)
{
if ($stream = @fopen($url, 'r')) {
$tmpFile = tempnam(sys_get_temp_dir(), 'media-library');
file_put_contents($tmpFile, $stream);

return app(FileAdderFactory::class)->create($this, $tmpFile);
if (!$stream = @fopen($url, 'r')) {
throw new UrlCouldNotBeOpened();
}

throw new UrlCouldNotBeOpened;
$tmpFile = tempnam(sys_get_temp_dir(), 'media-library');
file_put_contents($tmpFile, $stream);

$filename = basename(parse_url($url, PHP_URL_PATH));

return app(FileAdderFactory::class)
->create($this, $tmpFile)
->usingName(pathinfo($filename, PATHINFO_FILENAME))
->usingFileName($filename);
}

/**
Expand Down
27 changes: 20 additions & 7 deletions tests/FileAdder/IntegrationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Spatie\MediaLibrary\Test\FileAdder;

use Spatie\MediaLibrary\Exceptions\UrlCouldNotBeOpened;
use Spatie\MediaLibrary\Test\TestCase;
use Symfony\Component\HttpFoundation\File\UploadedFile;

Expand Down Expand Up @@ -137,16 +138,28 @@ public function it_can_add_an_upload_to_the_medialibrary()
*/
public function it_can_add_a_remote_file_to_the_medialibrary()
{
$url = $this->getTestUrl();
$filename = basename(parse_url($url, PHP_URL_PATH));
$url = 'http://medialibrary.spatie.be/assets/images/mountain.jpg';

$media = $this->testModel->addMediaFromUrl($url)
->usingName('test')
->usingFileName($filename)
$media = $this->testModel
->addMediaFromUrl($url)
->toMediaLibrary();

$this->assertEquals('test', $media->name);
$this->assertFileExists($this->getMediaDirectory($media->id.'/'.$filename));
$this->assertEquals('mountain', $media->name);
$this->assertFileExists($this->getMediaDirectory("{$media->id}/mountain.jpg"));
}

/**
* @test
*/
public function it_wil_thrown_an_exception_when_a_remote_file_could_not_be_added()
{
$url = 'http://medialibrary.spatie.be/assets/images/thisonedoesnotexist.jpg';

$this->setExpectedException(UrlCouldNotBeOpened::class);

$this->testModel
->addMediaFromUrl($url)
->toMediaLibrary();
}

/**
Expand Down
5 changes: 0 additions & 5 deletions tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,9 +131,4 @@ public function getTestJpg()
{
return $this->getTestFilesDirectory('test.jpg');
}

public function getTestUrl()
{
return 'http://medialibrary.spatie.be/assets/images/mountain.jpg';
}
}

0 comments on commit 0498de5

Please sign in to comment.