-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbacChainRequest.php
More file actions
85 lines (74 loc) · 2.49 KB
/
AbacChainRequest.php
File metadata and controls
85 lines (74 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php
namespace zennit\ABAC\Http\Requests;
use Illuminate\Validation\Rule;
use zennit\ABAC\Enums\Operators\LogicalOperators;
use zennit\ABAC\Models\AbacChain;
class AbacChainRequest extends Request
{
protected function getRules(): array
{
$baseRules = [
'operator' => ['required', 'string', Rule::enum(LogicalOperators::class)],
];
return $this->route('policy')
? $this->getSingleChainRules($baseRules)
: $this->getBulkChainRules();
}
protected function getSingleChainRules(array $baseRules): array
{
return array_merge($baseRules, [
'policy_id' => ['prohibited'],
'chain_id' => ['integer', 'exists:' . AbacChain::class . ',id'],
'chains' => [
'array',
'max:2',
function ($attribute, $value, $fail) {
$this->validateChildrenCount($value, $fail);
},
],
'chains.*' => $this->getRecursiveChainRules(),
]);
}
protected function validateChildrenCount($chain, $fail): void
{
$childCount = 0;
if (isset($chain['chains'])) {
$childCount += count($chain['chains']);
}
if (isset($chain['checks'])) {
$childCount += count($chain['checks']);
}
if ($childCount > 2) {
$fail('Each chain can have a maximum of 2 children (chains or checks combined)');
}
}
protected function getRecursiveChainRules(): array
{
return [
'array',
function ($attribute, $value, $fail) {
if (!isset($value['policy_id']) && !isset($value['chain_id']) && !isset($value['chains'])) {
$fail('Each chain must have either policy_id, chain_id, or nested chains');
}
if (isset($value['policy_id']) && isset($value['chain_id'])) {
$fail('You cannot set both chain_id and policy_id at the same time');
}
},
];
}
protected function getBulkChainRules(): array
{
return [
'chains' => [
'array',
'required',
function ($attribute, $value, $fail) {
foreach ($value as $chain) {
$this->validateChildrenCount($chain, $fail);
}
},
],
'chains.*' => $this->getRecursiveChainRules(),
];
}
}