Skip to content

Commit

Permalink
Merge pull request #96 from cviebrock/feature/addFromUrl
Browse files Browse the repository at this point in the history
Feature/add from url
  • Loading branch information
freekmurze committed Nov 7, 2015
2 parents 7f5a531 + 72b4d0b commit 0f80ad1
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/Exceptions/UrlCouldNotBeOpened.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

namespace Spatie\MediaLibrary\Exceptions;

use Exception;

class UrlCouldNotBeOpened extends Exception
{
}
14 changes: 14 additions & 0 deletions src/HasMedia/HasMediaTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Spatie\MediaLibrary\Conversion\Conversion;
use Spatie\MediaLibrary\Exceptions\MediaDoesNotBelongToModel;
use Spatie\MediaLibrary\Exceptions\MediaIsNotPartOfCollection;
use Spatie\MediaLibrary\Exceptions\UrlCouldNotBeOpened;
use Spatie\MediaLibrary\FileAdder\FileAdderFactory;
use Spatie\MediaLibrary\Filesystem;
use Spatie\MediaLibrary\Media;
Expand Down Expand Up @@ -40,6 +41,19 @@ public function addMedia($file)
return app(FileAdderFactory::class)->create($this, $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);
}

throw new UrlCouldNotBeOpened;

}

/**
* Copy a file to the medialibrary.
*
Expand Down
17 changes: 17 additions & 0 deletions tests/FileAdder/IntegrationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,23 @@ public function it_can_add_an_upload_to_the_medialibrary()
$this->assertFileExists($this->getMediaDirectory($media->id.'/'.$media->file_name));
}

/**
* @test
*/
public function it_can_add_a_remote_file_to_the_medialibrary()
{
$url = $this->getTestUrl();
$filename = basename(parse_url($url, PHP_URL_PATH));

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

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

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

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

0 comments on commit 0f80ad1

Please sign in to comment.