master

laravel/framework

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

RedirectController.php

TLDR

This file, RedirectController.php, is part of the Illuminate\Routing namespace in the Demo Projects project. It contains a class called "RedirectController" that extends the Controller class. The class has a method __invoke that is used to handle controller invocations.

Methods

__invoke

This method is responsible for handling controller invocations. It takes a Request object and a UrlGenerator object as parameters. It performs the following steps:

  1. Collects the parameters from the request route.
  2. Gets the 'status' and 'destination' parameters.
  3. Removes the 'status' and 'destination' parameters from the collection.
  4. Creates a new Route object with the 'GET' method and the destination.
  5. Binds the request to the route.
  6. Filters the parameters collection to only include the path variables defined in the route.
  7. Generates a URL for the route using the UrlGenerator.
  8. If the destination does not start with '/', but the URL does, removes the leading '/' from the URL.
  9. Returns a new RedirectResponse object with the generated URL and the status.

Classes

RedirectController

This class extends the Controller class and is responsible for handling redirects. It implements the __invoke method to handle controller invocations.

<?php

namespace Illuminate\Routing;

use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class RedirectController extends Controller
{
    /**
     * Invoke the controller method.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Routing\UrlGenerator  $url
     * @return \Illuminate\Http\RedirectResponse
     */
    public function __invoke(Request $request, UrlGenerator $url)
    {
        $parameters = collect($request->route()->parameters());

        $status = $parameters->get('status');

        $destination = $parameters->get('destination');

        $parameters->forget('status')->forget('destination');

        $route = (new Route('GET', $destination, [
            'as' => 'laravel_route_redirect_destination',
        ]))->bind($request);

        $parameters = $parameters->only(
            $route->getCompiled()->getPathVariables()
        )->all();

        $url = $url->toRoute($route, $parameters, false);

        if (! str_starts_with($destination, '/') && str_starts_with($url, '/')) {
            $url = Str::after($url, '/');
        }

        return new RedirectResponse($url, $status);
    }
}