Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[9.x] Allow using backed enums as route parameters #43294

Merged
merged 1 commit into from
Jul 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/Illuminate/Routing/UrlGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Illuminate\Routing;

use BackedEnum;
use Closure;
use Illuminate\Contracts\Routing\UrlGenerator as UrlGeneratorContract;
use Illuminate\Contracts\Routing\UrlRoutable;
Expand Down Expand Up @@ -479,9 +480,13 @@ public function route($name, $parameters = [], $absolute = true)
public function toRoute($route, $parameters, $absolute)
{
$parameters = collect(Arr::wrap($parameters))->map(function ($value, $key) use ($route) {
return $value instanceof UrlRoutable && $route->bindingFieldFor($key)
$value = $value instanceof UrlRoutable && $route->bindingFieldFor($key)
? $value->{$route->bindingFieldFor($key)}
: $value;

return function_exists('enum_exists') && $value instanceof BackedEnum
? $value->value
: $value;
})->all();

return $this->routeUrl()->to(
Expand Down
20 changes: 20 additions & 0 deletions tests/Routing/RoutingUrlGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
use Symfony\Component\Routing\Exception\RouteNotFoundException;

if (PHP_VERSION_ID >= 80100) {
include_once 'Enums.php';
}

class RoutingUrlGeneratorTest extends TestCase
{
public function testBasicGeneration()
Expand Down Expand Up @@ -847,6 +851,22 @@ public function testSignedUrlParameterCannotBeNamedExpires()

Request::create($url->signedRoute('foo', ['expires' => 253402300799]));
}

/**
* @requires PHP >= 8.1
*/
public function testRouteGenerationWithBackedEnums()
{
$url = new UrlGenerator(
$routes = new RouteCollection,
Request::create('http://www.foo.com/')
);

$namedRoute = new Route(['GET'], '/foo/{bar}', ['as' => 'foo.bar']);
$routes->add($namedRoute);

$this->assertSame('http://www.foo.com/foo/fruits', $url->route('foo.bar', CategoryBackedEnum::Fruits));
}
}

class RoutableInterfaceStub implements UrlRoutable
Expand Down