master

laravel/framework

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

TrustHosts.php

TLDR

The TrustHosts class is a middleware in the Illuminate\Http\Middleware namespace. It is responsible for managing trusted host patterns in the Laravel application.

Methods

hosts

This method returns an array of host patterns that should be trusted.

handle

This method handles the incoming request. It checks if the application should specify trusted hosts and sets the trusted hosts using the Request::setTrustedHosts method. It then passes the request to the next middleware.

shouldSpecifyTrustedHosts

This method determines if the application should specify trusted hosts. It returns true if the application is not in the local environment and not running unit tests.

allSubdomainsOfApplicationUrl

This method returns a regular expression matching the application URL and all of its subdomains. It uses the parse_url function to extract the host from the application URL and constructs a regex pattern.

<?php

namespace Illuminate\Http\Middleware;

use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\Request;

class TrustHosts
{
    /**
     * The application instance.
     *
     * @var \Illuminate\Contracts\Foundation\Application
     */
    protected $app;

    /**
     * Create a new middleware instance.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @return void
     */
    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    /**
     * Get the host patterns that should be trusted.
     *
     * @return array
     */
    public function hosts()
    {
        return [
            $this->allSubdomainsOfApplicationUrl(),
        ];
    }

    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return \Illuminate\Http\Response
     */
    public function handle(Request $request, $next)
    {
        if ($this->shouldSpecifyTrustedHosts()) {
            Request::setTrustedHosts(array_filter($this->hosts()));
        }

        return $next($request);
    }

    /**
     * Determine if the application should specify trusted hosts.
     *
     * @return bool
     */
    protected function shouldSpecifyTrustedHosts()
    {
        return ! $this->app->environment('local') &&
               ! $this->app->runningUnitTests();
    }

    /**
     * Get a regular expression matching the application URL and all of its subdomains.
     *
     * @return string|null
     */
    protected function allSubdomainsOfApplicationUrl()
    {
        if ($host = parse_url($this->app['config']->get('app.url'), PHP_URL_HOST)) {
            return '^(.+\.)?'.preg_quote($host).'$';
        }
    }
}