diff --git a/src/HasMedia/HasMediaTrait.php b/src/HasMedia/HasMediaTrait.php index 306bcd51e..dcb6ac897 100644 --- a/src/HasMedia/HasMediaTrait.php +++ b/src/HasMedia/HasMediaTrait.php @@ -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); } /** diff --git a/tests/FileAdder/IntegrationTest.php b/tests/FileAdder/IntegrationTest.php index 1ef0de27b..c48477810 100644 --- a/tests/FileAdder/IntegrationTest.php +++ b/tests/FileAdder/IntegrationTest.php @@ -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; @@ -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(); } /** diff --git a/tests/TestCase.php b/tests/TestCase.php index 7caede05b..5d664d85e 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -131,9 +131,4 @@ public function getTestJpg() { return $this->getTestFilesDirectory('test.jpg'); } - - public function getTestUrl() - { - return 'http://medialibrary.spatie.be/assets/images/mountain.jpg'; - } }