Skip to content

Commit

Permalink
Ensure headers are only attached to illuminate responses (#53019)
Browse files Browse the repository at this point in the history
  • Loading branch information
timacdonald authored Oct 3, 2024
1 parent 1b3ef8f commit 646520a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Illuminate\Http\Middleware;

use Illuminate\Http\Response;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Vite;

Expand All @@ -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(', '));
Expand Down
26 changes: 24 additions & 2 deletions tests/Http/Middleware/VitePreloadingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -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 = [];
Expand All @@ -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 = [
Expand All @@ -57,4 +58,25 @@ public function testItAddsPreloadLinkHeader()
'<https://laravel.com/app.js>; 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'));
}
}

0 comments on commit 646520a

Please sign in to comment.