Skip to content

Commit

Permalink
Support non required model instance (#6)
Browse files Browse the repository at this point in the history
* fix Type Error when calling policy methods which don't require a model instance
  • Loading branch information
Perer876 authored Apr 5, 2023
1 parent d19db37 commit e9242fe
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/LaravelPolicySoftCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
18 changes: 18 additions & 0 deletions tests/PolicySoftCacheTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
{
}

0 comments on commit e9242fe

Please sign in to comment.