Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Observer/ResponseBefore.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ public function execute(\Magento\Framework\Event\Observer $observer)
}

$response = $observer->getEvent()->getData('response');
$response->setBody(preg_replace(
$response->setBody(preg_replace_callback(
'/<head.*?>/',
"<head>
fn() => "<head>
<!-- SamJUK_FetchPriority:preload -->
{$this->getPreloadsHTML()}
<!-- / SamJUK_FetchPriority::preload -->",
Expand Down
27 changes: 27 additions & 0 deletions Test/Unit/Observer/ResponseBeforeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,33 @@ public function testModifiesResponseInFrontendAreaWithLinks(): void
$this->subject->execute($this->observerMock);
}

/**
* Test that hrefs containing "$" + digits (e.g. "/img$1.jpg") are not corrupted.
* preg_replace() treats $0-$99 in its replacement argument as backreferences
* regardless of source; preg_replace_callback() does not have this problem.
*/
public function testDoesNotCorruptHrefsContainingDollarDigitSequences(): void
{
$linkMock = $this->createMock(LinkInterface::class);
$linkMock->method('getAttrs')->willReturn(['rel' => 'preload', 'href' => '/img$1.jpg']);

$this->appStateMock->method('getAreaCode')->willReturn(Area::AREA_FRONTEND);
$this->linkStoreMock->method('get')->willReturn([$linkMock]);

$this->secureHtmlRendererMock->method('renderTag')
->willReturn('<link rel="preload" href="/img$1.jpg">');

$this->responseMock->method('getBody')->willReturn(self::SAMPLE_RESPONSE_HTML);

$this->responseMock->expects($this->once())
->method('setBody')
->with($this->callback(function ($body) {
return str_contains($body, '/img$1.jpg');
}));

$this->subject->execute($this->observerMock);
}

/**
* Test that only the first <head> tag is replaced.
*/
Expand Down
Loading