From fd3cd2f76f1a45a56cf114ee425bc1ebbf0e4b26 Mon Sep 17 00:00:00 2001 From: Carl Alexander Date: Tue, 29 Nov 2022 12:43:29 -0500 Subject: [PATCH] fix: don't rewrite `srcset` attribute when rewriting image urls --- ...tDeliveryNetworkImageProcessingSubscriber.php | 3 ++- ...iveryNetworkImageProcessingSubscriberTest.php | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/Subscriber/ContentDeliveryNetworkImageProcessingSubscriber.php b/src/Subscriber/ContentDeliveryNetworkImageProcessingSubscriber.php index 3dfbb76..97fec22 100644 --- a/src/Subscriber/ContentDeliveryNetworkImageProcessingSubscriber.php +++ b/src/Subscriber/ContentDeliveryNetworkImageProcessingSubscriber.php @@ -209,7 +209,8 @@ public function rewriteContentImageUrls(string $content): string return $image['height'] || $image['width']; })->mapWithKeys(function (array $image) { $src = $this->getOriginalImageUrl($image['image_src']); - $tag = str_replace($image['image_src'], esc_url($this->generateImageUrl($src, $image['height'], $image['width'], $image['cropped'])), $image['image_tag']); + + $tag = preg_replace('#(src=["|\'])[^\s]+?(["|\'])#', sprintf('$1%s$2', esc_url($this->generateImageUrl($src, $image['height'], $image['width'], $image['cropped']))), $image['image_tag']); $tag = preg_replace('#(?<=\s)(height|width)=["|\']?[\d%]+["|\']?\s?#i', '', $tag); return [ diff --git a/tests/Unit/Subscriber/ContentDeliveryNetworkImageProcessingSubscriberTest.php b/tests/Unit/Subscriber/ContentDeliveryNetworkImageProcessingSubscriberTest.php index 0b701f1..9d04db9 100644 --- a/tests/Unit/Subscriber/ContentDeliveryNetworkImageProcessingSubscriberTest.php +++ b/tests/Unit/Subscriber/ContentDeliveryNetworkImageProcessingSubscriberTest.php @@ -541,6 +541,22 @@ public function testReEnableImageDownsizeFilterIfFlagWasTrue() $this->assertTrue($imageDownsizeFilterEnabledProperty->getValue($subscriber)); } + public function testRewriteContentImageUrlsDoesntRewriteSrcsetUrls() + { + $content = ''; + $expectedContent = ''; + + $_prime_post_caches = $this->getFunctionMock($this->getNamespace(ContentDeliveryNetworkImageProcessingSubscriber::class), '_prime_post_caches'); + $_prime_post_caches->expects($this->once()) + ->with($this->identicalTo([]), $this->identicalTo(false)); + + $esc_url = $this->getFunctionMock($this->getNamespace(ContentDeliveryNetworkImageProcessingSubscriber::class), 'esc_url'); + $esc_url->expects($this->any()) + ->willReturn($this->returnArgument(0)); + + $this->assertSame($expectedContent, (new ContentDeliveryNetworkImageProcessingSubscriber($this->getImageSizes(), true, 'https://assets.com/uploads'))->rewriteContentImageUrls($content)); + } + public function testRewriteContentImageUrlsDoesntRewriteUrlIfUploadsUrlDoesntMatch() { $content = '';