From 646520ad682d98b5211c6e26092259cfbe130b5c Mon Sep 17 00:00:00 2001 From: Tim MacDonald Date: Fri, 4 Oct 2024 03:34:32 +1000 Subject: [PATCH] Ensure headers are only attached to illuminate responses (#53019) --- .../AddLinkHeadersForPreloadedAssets.php | 3 ++- tests/Http/Middleware/VitePreloadingTest.php | 26 +++++++++++++++++-- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/src/Illuminate/Http/Middleware/AddLinkHeadersForPreloadedAssets.php b/src/Illuminate/Http/Middleware/AddLinkHeadersForPreloadedAssets.php index 93ca06e958b5..36ffb7b3e480 100644 --- a/src/Illuminate/Http/Middleware/AddLinkHeadersForPreloadedAssets.php +++ b/src/Illuminate/Http/Middleware/AddLinkHeadersForPreloadedAssets.php @@ -2,6 +2,7 @@ namespace Illuminate\Http\Middleware; +use Illuminate\Http\Response; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Vite; @@ -17,7 +18,7 @@ class AddLinkHeadersForPreloadedAssets public function handle($request, $next) { return tap($next($request), function ($response) { - if (Vite::preloadedAssets() !== []) { + if ($response instanceof Response && Vite::preloadedAssets() !== []) { $response->header('Link', Collection::make(Vite::preloadedAssets()) ->map(fn ($attributes, $url) => "<{$url}>; ".implode('; ', $attributes)) ->join(', ')); diff --git a/tests/Http/Middleware/VitePreloadingTest.php b/tests/Http/Middleware/VitePreloadingTest.php index 641280cc8d9e..63b64b99519e 100644 --- a/tests/Http/Middleware/VitePreloadingTest.php +++ b/tests/Http/Middleware/VitePreloadingTest.php @@ -9,6 +9,7 @@ use Illuminate\Http\Response; use Illuminate\Support\Facades\Facade; use PHPUnit\Framework\TestCase; +use Symfony\Component\HttpFoundation\Response as SymfonyResponse; class VitePreloadingTest extends TestCase { @@ -20,7 +21,7 @@ protected function tearDown(): void public function testItDoesNotSetLinkTagWhenNoTagsHaveBeenPreloaded() { - $app = new Container(); + $app = new Container; $app->instance(Vite::class, new class extends Vite { protected $preloadedAssets = []; @@ -36,7 +37,7 @@ public function testItDoesNotSetLinkTagWhenNoTagsHaveBeenPreloaded() public function testItAddsPreloadLinkHeader() { - $app = new Container(); + $app = new Container; $app->instance(Vite::class, new class extends Vite { protected $preloadedAssets = [ @@ -57,4 +58,25 @@ public function testItAddsPreloadLinkHeader() '; rel="modulepreload"; foo="bar"' ); } + + public function testItDoesNotAttachHeadersToNonIlluminateResponses() + { + $app = new Container; + $app->instance(Vite::class, new class extends Vite + { + protected $preloadedAssets = [ + 'https://laravel.com/app.js' => [ + 'rel="modulepreload"', + 'foo="bar"', + ], + ]; + }); + Facade::setFacadeApplication($app); + + $response = (new AddLinkHeadersForPreloadedAssets)->handle(new Request, function () { + return new SymfonyResponse('Hello Laravel'); + }); + + $this->assertNull($response->headers->get('Link')); + } }