Skip to content

Commit e9242fe

Browse files
authored
Support non required model instance (#6)
* fix Type Error when calling policy methods which don't require a model instance
1 parent d19db37 commit e9242fe

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

src/LaravelPolicySoftCache.php

+6
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,12 @@ protected function callPolicyMethod(Model $user, object $policy, string $ability
8080
return $this->cache[$cacheKey];
8181
}
8282

83+
// If this first argument is a string, that means they are passing a class name to
84+
// the policy, so we remove it because it shouldn't be in the method as parameter.
85+
if (isset($args[0]) && is_string($args[0])) {
86+
array_shift($args);
87+
}
88+
8389
$result = $policy->{$ability}(...array_merge([$user], $args));
8490
$this->cache[$cacheKey] = $result;
8591

tests/PolicySoftCacheTest.php

+18
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,16 @@
8282
expect(true)->toBeTrue();
8383
});
8484

85+
it('does not break if the action does not require a model instance', function () {
86+
$user = new User();
87+
88+
Gate::policy(TestModel::class, PolicyWithoutRequiredModel::class);
89+
90+
$user->can('create', [TestModel::class, 1]);
91+
92+
expect(true)->toBeTrue();
93+
});
94+
8595
class PolicyWithSoftCache implements SoftCacheable
8696
{
8797
public static int $called = 0;
@@ -106,6 +116,14 @@ public function view(User $user, TestModel $model): bool
106116
}
107117
}
108118

119+
class PolicyWithoutRequiredModel
120+
{
121+
public function create(User $user, int $value): bool
122+
{
123+
return true;
124+
}
125+
}
126+
109127
class TestModel extends Model
110128
{
111129
}

0 commit comments

Comments
 (0)