Skip to content

Commit

Permalink
bugfixing
Browse files Browse the repository at this point in the history
  • Loading branch information
geisi committed Nov 3, 2022
1 parent b48a82f commit 3418f64
Showing 1 changed file with 22 additions and 7 deletions.
29 changes: 22 additions & 7 deletions src/LaravelPolicySoftCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ public static function flushCache(): void
app()->make(static::class)->cache = [];
}

/**
* @param mixed $user
* @param string $ability
* @param mixed $args
* @return mixed
*/
public function handleGateCall(mixed $user, string $ability, mixed $args): mixed
{
if (! is_array($args)) {
Expand All @@ -37,42 +43,51 @@ public function handleGateCall(mixed $user, string $ability, mixed $args): mixed
$policy = Gate::getPolicyFor($model);

if ($model && $this->shouldCache($policy)) {
return $this->callPolicyMethod($user, $model, $policy, $ability, $args);
return $this->callPolicyMethod($user, $policy, $ability, $args);
}

return null;
}

/**
* @param object|null $policy
* @return bool
*/
protected function shouldCache(?object $policy): bool
{
return $policy && ($policy instanceof SoftCacheable || config('policy-soft-cache.cache_all_policies', false) === true);
}

/**
* @param Model $user
* @param Model $model
* @param object $policy
* @param string $ability
* @param array<int,mixed> $args
* @return mixed
*/
protected function callPolicyMethod(Model $user, Model $model, object $policy, string $ability, array $args): mixed
protected function callPolicyMethod(Model $user, object $policy, string $ability, array $args): mixed
{
$cacheKey = $this->getCacheKey($user, $model, $ability);
$cacheKey = $this->getCacheKey($user, $policy, $args, $ability);

if (isset($this->cache[$cacheKey])) {
return $this->cache[$cacheKey];
}

$result = $policy->{$ability}(...array_merge([$user], $args));

$this->cache[$cacheKey] = $result;

return $result;
}

protected function getCacheKey(Model $user, Model $model, string $ability): string
/**
* @param Model $user
* @param object $policy
* @param array<int,mixed> $args
* @param string $ability
* @return string
*/
protected function getCacheKey(Model $user, object $policy, array $args, string $ability): string
{
return $user->{$user->getKeyName()}.'_'.$model::class.'_'.$ability;
return $user->{$user->getKeyName()}.'_'.hash_hmac('sha512', (string) json_encode($args), config('app.key')).'_'.$ability.'_'.$policy::class;
}
}

0 comments on commit 3418f64

Please sign in to comment.