From feb4f1766533f542a9026b441b79d740741ca239 Mon Sep 17 00:00:00 2001 From: basakest Date: Mon, 2 Aug 2021 13:20:36 +0800 Subject: [PATCH] feat: support updatePolicies method --- src/Adapter.php | 18 ++++++++++++++++++ tests/AdapterTest.php | 30 ++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/src/Adapter.php b/src/Adapter.php index 6b3f4a6..92f728a 100644 --- a/src/Adapter.php +++ b/src/Adapter.php @@ -361,6 +361,24 @@ public function updatePolicy(string $sec, string $ptype, array $oldRule, array $ $queryBuilder->execute(); } + /** + * 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 + { + $this->connection->transactional(function () use ($sec, $ptype, $oldRules, $newRules) { + foreach ($oldRules as $i => $oldRule) { + $this->updatePolicy($sec, $ptype, $oldRule, $newRules[$i]); + } + }); + } + /** * Returns true if the loaded policy has been filtered. * diff --git a/tests/AdapterTest.php b/tests/AdapterTest.php index 483707a..eaa9c87 100644 --- a/tests/AdapterTest.php +++ b/tests/AdapterTest.php @@ -181,4 +181,34 @@ public function testUpdatePolicy() ['data2_admin', 'data2', 'write'], ], $e->getPolicy()); } + + public function testUpdatePolicies() + { + $e = $this->getEnforcer(); + $this->assertEquals([ + ['alice', 'data1', 'read'], + ['bob', 'data2', 'write'], + ['data2_admin', 'data2', 'read'], + ['data2_admin', 'data2', 'write'], + ], $e->getPolicy()); + + $oldPolicies = [ + ['alice', 'data1', 'read'], + ['bob', 'data2', 'write'] + ]; + + $newPolicies = [ + ['alice', 'data1', 'write'], + ['bob', 'data2', 'read'] + ]; + + $e->updatePolicies($oldPolicies, $newPolicies); + + $this->assertEquals([ + ['alice', 'data1', 'write'], + ['bob', 'data2', 'read'], + ['data2_admin', 'data2', 'read'], + ['data2_admin', 'data2', 'write'], + ], $e->getPolicy()); + } }