Skip to content

Commit 56d6194

Browse files
authored
[11.x] Allow BackedEnum to be passed to Route::can() (#52792)
* Add backed enum support to can * Add RouteCanBackedEnumTest and related enum file
1 parent 0890706 commit 56d6194

File tree

3 files changed

+52
-1
lines changed

3 files changed

+52
-1
lines changed

src/Illuminate/Routing/Route.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1081,12 +1081,14 @@ public function middleware($middleware = null)
10811081
/**
10821082
* Specify that the "Authorize" / "can" middleware should be applied to the route with the given options.
10831083
*
1084-
* @param string $ability
1084+
* @param \BackedEnum|string $ability
10851085
* @param array|string $models
10861086
* @return $this
10871087
*/
10881088
public function can($ability, $models = [])
10891089
{
1090+
$ability = $ability instanceof BackedEnum ? $ability->value : $ability;
1091+
10901092
return empty($models)
10911093
? $this->middleware(['can:'.$ability])
10921094
: $this->middleware(['can:'.$ability.','.implode(',', Arr::wrap($models))]);
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<?php
2+
3+
namespace Illuminate\Tests\Integration\Routing;
4+
5+
enum AbilityBackedEnum: string
6+
{
7+
case AccessRoute = 'access-route';
8+
case NotAccessRoute = 'not-access-route';
9+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
3+
namespace Illuminate\Tests\Integration\Routing;
4+
5+
use Illuminate\Support\Facades\Gate;
6+
use Illuminate\Support\Facades\Route;
7+
use Orchestra\Testbench\TestCase;
8+
use User;
9+
10+
class RouteCanBackedEnumTest extends TestCase
11+
{
12+
public function testSimpleRouteWithStringBackedEnumCanAbilityGuestForbiddenThroughTheFramework()
13+
{
14+
$gate = Gate::define(AbilityBackedEnum::NotAccessRoute, fn (?User $user) => false);
15+
$this->assertArrayHasKey('not-access-route', $gate->abilities());
16+
17+
$route = Route::get('/', function () {
18+
return 'Hello World';
19+
})->can(AbilityBackedEnum::NotAccessRoute);
20+
$this->assertEquals(['can:not-access-route'], $route->middleware());
21+
22+
$response = $this->get('/');
23+
$response->assertForbidden();
24+
}
25+
26+
public function testSimpleRouteWithStringBackedEnumCanAbilityGuestAllowedThroughTheFramework()
27+
{
28+
$gate = Gate::define(AbilityBackedEnum::AccessRoute, fn (?User $user) => true);
29+
$this->assertArrayHasKey('access-route', $gate->abilities());
30+
31+
$route = Route::get('/', function () {
32+
return 'Hello World';
33+
})->can(AbilityBackedEnum::AccessRoute);
34+
$this->assertEquals(['can:access-route'], $route->middleware());
35+
36+
$response = $this->get('/');
37+
$response->assertOk();
38+
$response->assertContent('Hello World');
39+
}
40+
}

0 commit comments

Comments
 (0)