Skip to content

Commit 55f435b

Browse files
[11.x] Allow the authorize method to accept Backed Enums directly (#53330)
* Make it possible to use a BackedEnum for Authorization checks * Use enum_value
1 parent 8a876b6 commit 55f435b

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/Illuminate/Foundation/Auth/Access/AuthorizesRequests.php

+4
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
use Illuminate\Contracts\Auth\Access\Gate;
66
use Illuminate\Support\Str;
77

8+
use function Illuminate\Support\enum_value;
9+
810
trait AuthorizesRequests
911
{
1012
/**
@@ -49,6 +51,8 @@ public function authorizeForUser($user, $ability, $arguments = [])
4951
*/
5052
protected function parseAbilityAndArguments($ability, $arguments)
5153
{
54+
$ability = enum_value($ability);
55+
5256
if (is_string($ability) && ! str_contains($ability, '\\')) {
5357
return [$ability, $arguments];
5458
}

tests/Foundation/FoundationAuthorizesRequestsTraitTest.php

+23
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,24 @@ public function testBasicGateCheck()
3535
$this->assertTrue($_SERVER['_test.authorizes.trait']);
3636
}
3737

38+
public function testAcceptsBackedEnumAsAbility()
39+
{
40+
unset($_SERVER['_test.authorizes.trait.enum']);
41+
42+
$gate = $this->getBasicGate();
43+
44+
$gate->define('baz', function () {
45+
$_SERVER['_test.authorizes.trait.enum'] = true;
46+
47+
return true;
48+
});
49+
50+
$response = (new FoundationTestAuthorizeTraitClass)->authorize(TestAbility::BAZ);
51+
52+
$this->assertInstanceOf(Response::class, $response);
53+
$this->assertTrue($_SERVER['_test.authorizes.trait.enum']);
54+
}
55+
3856
public function testExceptionIsThrownIfGateCheckFails()
3957
{
4058
$this->expectException(AuthorizationException::class);
@@ -163,3 +181,8 @@ public function store($object)
163181
$this->authorize($object);
164182
}
165183
}
184+
185+
enum TestAbility: string
186+
{
187+
case BAZ = 'baz';
188+
}

0 commit comments

Comments
 (0)