master

laravel/framework

Last updated at: 29/12/2023 09:23

AddLinkHeadersForPreloadedAssets.php

TLDR

This file contains the AddLinkHeadersForPreloadedAssets class which is a middleware for handling incoming requests. This middleware adds a Link header to the response if there are preloaded assets available.

Classes

AddLinkHeadersForPreloadedAssets

This class is a middleware that handles incoming requests. It adds a Link header to the response if there are preloaded assets available. The handle method takes in the request and a closure representing the next middleware in the pipeline. It then calls that closure with the request and sets the Link header on the response if preloaded assets are found.

Methods

None

<?php

namespace Illuminate\Http\Middleware;

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

class AddLinkHeadersForPreloadedAssets
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return \Illuminate\Http\Response
     */
    public function handle($request, $next)
    {
        return tap($next($request), function ($response) {
            if (Vite::preloadedAssets() !== []) {
                $response->header('Link', Collection::make(Vite::preloadedAssets())
                    ->map(fn ($attributes, $url) => "<{$url}>; ".implode('; ', $attributes))
                    ->join(', '));
            }
        });
    }
}