Skip to content

Commit

Permalink
Add version to responsive image url (#3731)
Browse files Browse the repository at this point in the history
* Add version to responsive image url

* Add tests to ensure responsive image urls can be versioned
  • Loading branch information
jorenvh authored Dec 30, 2024
1 parent a352432 commit 1c49502
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/ResponsiveImages/ResponsiveImage.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,13 @@ public function url(): string

$urlGenerator = UrlGeneratorFactory::createForMedia($this->media, $conversionName);

return $urlGenerator->getResponsiveImagesDirectoryUrl().rawurlencode($this->fileName);
$url = $urlGenerator->getResponsiveImagesDirectoryUrl().rawurlencode($this->fileName);

if (config('media-library.version_urls') === true) {
$url = "{$url}?v={$this->media->updated_at->timestamp}";
}

return $url;
}

public function generatedFor(): string
Expand Down
31 changes: 31 additions & 0 deletions tests/ResponsiveImages/ResponsiveImageTest.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<?php

use Carbon\Carbon;

beforeEach(function () {
$this->fileName = 'test';
$this->fileNameWithUnderscore = 'test_';
Expand Down Expand Up @@ -48,6 +50,35 @@
expect($media->getSrcset('thumb'))->toContain('data:image/svg+xml;base64,');
});

test('a media instance can generate the contents of scrset with versioned urls', function () {
config()->set('media-library.version_urls', true);

$this->travelTo(Carbon::create(2023, 3, 24, 14));

$this->freezeTime(function (Carbon $time) {
$this->testModelWithResponsiveImages
->addMedia($this->getTestJpg())
->withResponsiveImages()
->toMediaCollection();

$media = $this->testModelWithResponsiveImages->getFirstMedia();

$timestamp = $time->timestamp;

$this->assertStringContainsString(
"/media/1/responsive-images/{$this->fileName}___media_library_original_340_280.jpg?v={$timestamp} 340w, /media/1/responsive-images/{$this->fileName}___media_library_original_284_234.jpg?v={$timestamp} 284w, /media/1/responsive-images/{$this->fileName}___media_library_original_237_195.jpg?v={$timestamp} 237w",
$media->getSrcset()
);
expect($media->getSrcset())->toContain('data:image/svg+xml;base64');

$this->assertStringContainsString(
"/media/1/responsive-images/{$this->fileName}___thumb_50_41.jpg?v={$timestamp} 50w",
$media->getSrcset('thumb')
);
expect($media->getSrcset('thumb'))->toContain('data:image/svg+xml;base64,');
});
});

test('a responsive image can return some properties', function () {
$this->testModel
->addMedia($this->getTestJpg())
Expand Down

0 comments on commit 1c49502

Please sign in to comment.