|
9 | 9 |
|
10 | 10 | class SharpAuthorizationManager |
11 | 11 | { |
| 12 | + private bool $cacheEnabled; |
12 | 13 | private array $cachedPolicies = []; |
13 | 14 |
|
14 | | - public function __construct(protected SharpEntityManager $entityManager, protected Gate $gate) {} |
| 15 | + public function __construct(protected SharpEntityManager $entityManager, protected Gate $gate) |
| 16 | + { |
| 17 | + $this->cacheEnabled = ! app()->environment('testing'); |
| 18 | + } |
15 | 19 |
|
16 | 20 | public function isAllowed(string $ability, string $entityKey, ?string $instanceId = null): bool |
17 | 21 | { |
@@ -52,25 +56,29 @@ protected function isGloballyForbidden(string $ability, string $entityKey): bool |
52 | 56 |
|
53 | 57 | protected function isPolicyForbidden(string $ability, string $entityKey, ?string $instanceId = null): bool |
54 | 58 | { |
55 | | - if (! Arr::exists($this->cachedPolicies, "$ability-$entityKey-$instanceId")) { |
56 | | - $entity = $this->entityManager->entityFor($entityKey); |
57 | | - $policy = $entity->getPolicyOrDefault(); |
58 | | - |
59 | | - $forbidden = true; |
60 | | - if (in_array($ability, ['entity', 'create', 'reorder'])) { |
61 | | - // Always checked |
62 | | - $forbidden = ! $policy->$ability(auth()->user()); |
63 | | - } elseif (in_array($ability, ['view', 'update', 'delete'])) { |
64 | | - // Not checked in create case, as it could lead to unwanted errors in functional policy code (with findOrFail for instance) |
65 | | - if ($instanceId || $entity->isSingle()) { |
66 | | - $forbidden = ! $policy->$ability(auth()->user(), $instanceId); |
67 | | - } |
| 59 | + if ($this->cacheEnabled && Arr::exists($this->cachedPolicies, "$ability-$entityKey-$instanceId")) { |
| 60 | + return $this->cachedPolicies["$ability-$entityKey-$instanceId"]; |
| 61 | + } |
| 62 | + |
| 63 | + $entity = $this->entityManager->entityFor($entityKey); |
| 64 | + $policy = $entity->getPolicyOrDefault(); |
| 65 | + |
| 66 | + $forbidden = true; |
| 67 | + if (in_array($ability, ['entity', 'create', 'reorder'])) { |
| 68 | + // Always checked |
| 69 | + $forbidden = ! $policy->$ability(auth()->user()); |
| 70 | + } elseif (in_array($ability, ['view', 'update', 'delete'])) { |
| 71 | + // Not checked in create case, as it could lead to unwanted errors in functional policy code (with findOrFail for instance) |
| 72 | + if ($instanceId || $entity->isSingle()) { |
| 73 | + $forbidden = ! $policy->$ability(auth()->user(), $instanceId); |
68 | 74 | } |
| 75 | + } |
69 | 76 |
|
| 77 | + if ($this->cacheEnabled) { |
70 | 78 | $this->cachedPolicies["$ability-$entityKey-$instanceId"] = $forbidden; |
71 | 79 | } |
72 | 80 |
|
73 | | - return $this->cachedPolicies["$ability-$entityKey-$instanceId"]; |
| 81 | + return $forbidden; |
74 | 82 | } |
75 | 83 |
|
76 | 84 | private function deny() |
|
0 commit comments