Created
November 7, 2019 10:02
-
-
Save juampi92/fff250719122a596c716c64e5b0afef6 to your computer and use it in GitHub Desktop.
Build Requests with routes on Laravel for testing.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Illuminate\Http\Request; | |
use Illuminate\Routing\Route; | |
use Illuminate\Support\Facades\Route as Router; | |
class RequestBuilder | |
{ | |
/** | |
* Will create a request with the correct fullUrl, route parameters and input parameters. | |
* | |
* @example RequestBuilder::create('post.show', ['postId' => 1], PostShowRequest::class); | |
* @example RequestBuilder::create('post.index'); | |
* | |
* @param string $routeName Name of the route. | |
* @param array $parameters Array of route or input parameters. | |
* @param string $class Request class. | |
* @throws \Exception If the route name doesn't exist. | |
* @return Request | |
*/ | |
public static function create(string $routeName, array $parameters = [], string $class = Request::class) | |
{ | |
// Find the route properties. | |
$route = Router::getRoutes()->getByName($routeName); | |
throw_if(is_null($route), new \Exception("[RequestBuilder] Couldn't find route by the name of {$routeName}.")); | |
// Recreate the full url | |
$fullUrl = route($routeName, $parameters); | |
$method = $route->methods()[0]; | |
$uri = $route->uri; | |
$request = $class::create($fullUrl); | |
$request->setRouteResolver(function () use ($request, $method, $uri) { | |
// Associate Route to request so we can access route parameters. | |
return (new Route($method, $uri, []))->bind($request); | |
}); | |
return $request; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment