spatie / laravel-medialibrary

Associate files with Eloquent models
https://spatie.be/docs/laravel-medialibrary
MIT License
5.78k stars 1.08k forks source link

Adds the HttpFacadeDownloader #3505

Closed peterfox closed 10 months ago

peterfox commented 10 months ago

Changes

Why

I find it difficult to write tests with the current downloader as it can't even be mocked by the container and requires a config change. I thought at a minimum this might be a small improvement as the Http facade is pretty good for mocking HTTP calls.

Usage

The downloader is used as normal.

    // config/media-library.php

    /*
     * When using the addMediaFromUrl method you may want to replace the default downloader.
     * This is particularly useful when the url of the image is behind a firewall and
     * need to add additional flags, possibly using curl.
     */
    'media_downloader' => Spatie\MediaLibrary\Downloaders\HttpFacadeDownloader::class,

This then makes it easier in tests to mock the download of files.

$url = 'http://medialibrary.spatie.be/assets/images/mountain.jpg';
$yourModel
   ->addMediaFromUrl($url)
   ->toMediaCollection();

with a test like this:

Http::fake([
    // Stub a response where the body will be the contents of the file
    'http://medialibrary.spatie.be/assets/images/mountain.jpg' => Http::response('::file::'),
]);

// Execute code for the test

// Then check that a request for the file was made
Http::assertSent(function (Request $request) {
    return $request->url() == 'http://medialibrary.spatie.be/assets/images/mountain.jpg';
});

// We may also assert that the contents of any files created
// will contain `::file::`
freekmurze commented 10 months ago

Could you document how this should be used?

peterfox commented 10 months ago

@freekmurze apologies for the slow update. I've added some docs and another test that displays it working. Let me know if you need more.

freekmurze commented 10 months ago

Thanks!