feat: support updatePolicies method, fix #27 (#28)

This commit is contained in:
basakest 2021-07-28 18:43:58 +08:00 committed by GitHub
parent f81f206dbe
commit 877f2f27b4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 46 additions and 0 deletions

View File

@ -224,6 +224,24 @@ class DatabaseAdapter implements DatabaseAdapterContract, BatchDatabaseAdapterCo
Rule::fireModelEvent('saved'); Rule::fireModelEvent('saved');
} }
/**
* UpdatePolicies updates some policy rules to storage, like db, redis.
*
* @param string $sec
* @param string $ptype
* @param string[][] $oldRules
* @param string[][] $newRules
* @return void
*/
public function updatePolicies(string $sec, string $ptype, array $oldRules, array $newRules): void
{
DB::transaction(function () use ($sec, $ptype, $oldRules, $newRules) {
foreach ($oldRules as $i => $oldRule) {
$this->updatePolicy($sec, $ptype, $oldRule, $newRules[$i]);
}
});
}
/** /**
* Loads only policy rules that match the filter. * Loads only policy rules that match the filter.
* *

View File

@ -131,6 +131,34 @@ class DatabaseAdapterTest extends TestCase
], Enforcer::getPolicy()); ], Enforcer::getPolicy());
} }
public function testUpdatePolicies()
{
$this->assertEquals([
['alice', 'data1', 'read'],
['bob', 'data2', 'write'],
['data2_admin', 'data2', 'read'],
['data2_admin', 'data2', 'write'],
], Enforcer::getPolicy());
$oldPolicies = [
['alice', 'data1', 'read'],
['bob', 'data2', 'write']
];
$newPolicies = [
['alice', 'data1', 'write'],
['bob', 'data2', 'read']
];
Enforcer::updatePolicies($oldPolicies, $newPolicies);
$this->assertEquals([
['alice', 'data1', 'write'],
['bob', 'data2', 'read'],
['data2_admin', 'data2', 'read'],
['data2_admin', 'data2', 'write'],
], Enforcer::getPolicy());
}
public function testLoadFilteredPolicy() public function testLoadFilteredPolicy()
{ {
$this->initTable(); $this->initTable();