diff --git a/src/LaravelPolicySoftCache.php b/src/LaravelPolicySoftCache.php index cf01540..12e313a 100644 --- a/src/LaravelPolicySoftCache.php +++ b/src/LaravelPolicySoftCache.php @@ -80,6 +80,12 @@ protected function callPolicyMethod(Model $user, object $policy, string $ability return $this->cache[$cacheKey]; } + // If this first argument is a string, that means they are passing a class name to + // the policy, so we remove it because it shouldn't be in the method as parameter. + if (isset($args[0]) && is_string($args[0])) { + array_shift($args); + } + $result = $policy->{$ability}(...array_merge([$user], $args)); $this->cache[$cacheKey] = $result; diff --git a/tests/PolicySoftCacheTest.php b/tests/PolicySoftCacheTest.php index b452caf..bd8fbd4 100644 --- a/tests/PolicySoftCacheTest.php +++ b/tests/PolicySoftCacheTest.php @@ -82,6 +82,16 @@ expect(true)->toBeTrue(); }); +it('does not break if the action does not require a model instance', function () { + $user = new User(); + + Gate::policy(TestModel::class, PolicyWithoutRequiredModel::class); + + $user->can('create', [TestModel::class, 1]); + + expect(true)->toBeTrue(); +}); + class PolicyWithSoftCache implements SoftCacheable { public static int $called = 0; @@ -106,6 +116,14 @@ public function view(User $user, TestModel $model): bool } } +class PolicyWithoutRequiredModel +{ + public function create(User $user, int $value): bool + { + return true; + } +} + class TestModel extends Model { }