Skip to content

Commit

Permalink
[11.x] Add support for enums in whereIn route constraints (#51121)
Browse files Browse the repository at this point in the history
* Add support for enums in `whereIn` route constraints

* Update CreatesRegularExpressionRouteConstraints.php

* Update CreatesRegularExpressionRouteConstraints.php

---------

Co-authored-by: Taylor Otwell <[email protected]>
  • Loading branch information
osbre and taylorotwell authored Apr 18, 2024
1 parent c01a87f commit 9c1b34c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Illuminate\Routing;

use BackedEnum;
use Illuminate\Support\Arr;

trait CreatesRegularExpressionRouteConstraints
Expand Down Expand Up @@ -70,7 +71,12 @@ public function whereUuid($parameters)
*/
public function whereIn($parameters, array $values)
{
return $this->assignExpressionToParameters($parameters, implode('|', $values));
return $this->assignExpressionToParameters(
$parameters,
collect($values)
->map(fn ($value) => $value instanceof BackedEnum ? $value->value : $value)
->implode('|')
);
}

/**
Expand Down
15 changes: 15 additions & 0 deletions tests/Routing/RouteRegistrarTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
use PHPUnit\Framework\TestCase;
use Stringable;

include_once 'Enums.php';

class RouteRegistrarTest extends TestCase
{
/**
Expand Down Expand Up @@ -942,6 +944,19 @@ public function testWhereInRegistration()
}
}

public function testWhereInEnumRegistration()
{
$this->router->get('/posts/{category}')->whereIn('category', CategoryBackedEnum::cases());

$invalidRequest = Request::create('/posts/invalid-value', 'GET');
$this->assertFalse($this->getRoute()->matches($invalidRequest));

foreach (CategoryBackedEnum::cases() as $case) {
$request = Request::create('/posts/'.$case->value, 'GET');
$this->assertTrue($this->getRoute()->matches($request));
}
}

public function testGroupWhereNumberRegistrationOnRouteRegistrar()
{
$wheres = ['foo' => '[0-9]+', 'bar' => '[0-9]+'];
Expand Down

0 comments on commit 9c1b34c

Please sign in to comment.