Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[11.x] Ensure headers are only attached to illuminate responses #52789

Merged
merged 1 commit into from
Sep 16, 2024
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
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'));
}
}