Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds the HttpFacadeDownloader #3505

Merged
merged 2 commits into from
Jan 22, 2024

Conversation

peterfox
Copy link
Contributor

@peterfox peterfox commented Jan 10, 2024

Changes

  • Adds a new HttpFacadeDownloader implementing the Downloader interface.
  • Adds a test for the new Downloader.

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::`

@peterfox peterfox force-pushed the feature/http-facade-downloader branch from b32dcd1 to 9d51402 Compare January 10, 2024 22:40
@freekmurze
Copy link
Member

Could you document how this should be used?

@peterfox peterfox force-pushed the feature/http-facade-downloader branch from 9d51402 to b345522 Compare January 20, 2024 14:23
@peterfox
Copy link
Contributor Author

@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 freekmurze merged commit 7db2555 into spatie:main Jan 22, 2024
5 checks passed
@freekmurze
Copy link
Member

Thanks!

@peterfox peterfox deleted the feature/http-facade-downloader branch January 22, 2024 16:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants