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:
- Collects the parameters from the request route.
- Gets the 'status' and 'destination' parameters.
- Removes the 'status' and 'destination' parameters from the collection.
- Creates a new
Route
object with the 'GET' method and the destination. - Binds the request to the route.
- Filters the parameters collection to only include the path variables defined in the route.
- Generates a URL for the route using the
UrlGenerator
. - If the destination does not start with '/', but the URL does, removes the leading '/' from the URL.
- 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);
}
}