Skip to content

Commit

Permalink
[11.x] Allow BackedEnum to be passed to Route::can() (#52792)
Browse files Browse the repository at this point in the history
* Add backed enum support to can

* Add RouteCanBackedEnumTest and related enum file
  • Loading branch information
Omegadela authored Sep 16, 2024
1 parent 0890706 commit 56d6194
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/Illuminate/Routing/Route.php
Original file line number Diff line number Diff line change
Expand Up @@ -1081,12 +1081,14 @@ public function middleware($middleware = null)
/**
* Specify that the "Authorize" / "can" middleware should be applied to the route with the given options.
*
* @param string $ability
* @param \BackedEnum|string $ability
* @param array|string $models
* @return $this
*/
public function can($ability, $models = [])
{
$ability = $ability instanceof BackedEnum ? $ability->value : $ability;

return empty($models)
? $this->middleware(['can:'.$ability])
: $this->middleware(['can:'.$ability.','.implode(',', Arr::wrap($models))]);
Expand Down
9 changes: 9 additions & 0 deletions tests/Integration/Routing/AbilityBackedEnum.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

namespace Illuminate\Tests\Integration\Routing;

enum AbilityBackedEnum: string
{
case AccessRoute = 'access-route';
case NotAccessRoute = 'not-access-route';
}
40 changes: 40 additions & 0 deletions tests/Integration/Routing/RouteCanBackedEnumTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

namespace Illuminate\Tests\Integration\Routing;

use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Route;
use Orchestra\Testbench\TestCase;
use User;

class RouteCanBackedEnumTest extends TestCase
{
public function testSimpleRouteWithStringBackedEnumCanAbilityGuestForbiddenThroughTheFramework()
{
$gate = Gate::define(AbilityBackedEnum::NotAccessRoute, fn (?User $user) => false);
$this->assertArrayHasKey('not-access-route', $gate->abilities());

$route = Route::get('/', function () {
return 'Hello World';
})->can(AbilityBackedEnum::NotAccessRoute);
$this->assertEquals(['can:not-access-route'], $route->middleware());

$response = $this->get('/');
$response->assertForbidden();
}

public function testSimpleRouteWithStringBackedEnumCanAbilityGuestAllowedThroughTheFramework()
{
$gate = Gate::define(AbilityBackedEnum::AccessRoute, fn (?User $user) => true);
$this->assertArrayHasKey('access-route', $gate->abilities());

$route = Route::get('/', function () {
return 'Hello World';
})->can(AbilityBackedEnum::AccessRoute);
$this->assertEquals(['can:access-route'], $route->middleware());

$response = $this->get('/');
$response->assertOk();
$response->assertContent('Hello World');
}
}

0 comments on commit 56d6194

Please sign in to comment.