Skip to content

Commit 877f2f2

Browse files
authored
feat: support updatePolicies method, fix #27 (#28)
1 parent f81f206 commit 877f2f2

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/Adapters/DatabaseAdapter.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,24 @@ public function updatePolicy(string $sec, string $ptype, array $oldRule, array $
224224
Rule::fireModelEvent('saved');
225225
}
226226

227+
/**
228+
* UpdatePolicies updates some policy rules to storage, like db, redis.
229+
*
230+
* @param string $sec
231+
* @param string $ptype
232+
* @param string[][] $oldRules
233+
* @param string[][] $newRules
234+
* @return void
235+
*/
236+
public function updatePolicies(string $sec, string $ptype, array $oldRules, array $newRules): void
237+
{
238+
DB::transaction(function () use ($sec, $ptype, $oldRules, $newRules) {
239+
foreach ($oldRules as $i => $oldRule) {
240+
$this->updatePolicy($sec, $ptype, $oldRule, $newRules[$i]);
241+
}
242+
});
243+
}
244+
227245
/**
228246
* Loads only policy rules that match the filter.
229247
*

tests/DatabaseAdapterTest.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,34 @@ public function testUpdatePolicy()
131131
], Enforcer::getPolicy());
132132
}
133133

134+
public function testUpdatePolicies()
135+
{
136+
$this->assertEquals([
137+
['alice', 'data1', 'read'],
138+
['bob', 'data2', 'write'],
139+
['data2_admin', 'data2', 'read'],
140+
['data2_admin', 'data2', 'write'],
141+
], Enforcer::getPolicy());
142+
143+
$oldPolicies = [
144+
['alice', 'data1', 'read'],
145+
['bob', 'data2', 'write']
146+
];
147+
$newPolicies = [
148+
['alice', 'data1', 'write'],
149+
['bob', 'data2', 'read']
150+
];
151+
152+
Enforcer::updatePolicies($oldPolicies, $newPolicies);
153+
154+
$this->assertEquals([
155+
['alice', 'data1', 'write'],
156+
['bob', 'data2', 'read'],
157+
['data2_admin', 'data2', 'read'],
158+
['data2_admin', 'data2', 'write'],
159+
], Enforcer::getPolicy());
160+
}
161+
134162
public function testLoadFilteredPolicy()
135163
{
136164
$this->initTable();

0 commit comments

Comments
 (0)