diff --git a/src/Adapter.php b/src/Adapter.php index 5463227..d7af7ed 100644 --- a/src/Adapter.php +++ b/src/Adapter.php @@ -6,11 +6,11 @@ use Casbin\Persist\Adapter as AdapterContract; use TechOne\Database\Manager; use Casbin\Persist\AdapterHelper; -use Casbin\Persist\FilteredAdapter; +use Casbin\Persist\FilteredAdapter as FilteredAdapterContract; use Casbin\Persist\Adapters\Filter; use Casbin\Exceptions\InvalidFilterTypeException; -use Casbin\Persist\BatchAdapter; -use Casbin\Persist\UpdatableAdapter; +use Casbin\Persist\BatchAdapter as BatchAdapterContract; +use Casbin\Persist\UpdatableAdapter as UpdatableAdapterContract; use Closure; use Throwable; @@ -19,7 +19,7 @@ * * @author techlee@qq.com */ -class Adapter implements AdapterContract, FilteredAdapter, BatchAdapter, UpdatableAdapter +class Adapter implements AdapterContract, FilteredAdapterContract, BatchAdapterContract, UpdatableAdapterContract { use AdapterHelper; @@ -305,4 +305,27 @@ public function updatePolicy(string $sec, string $ptype, array $oldRule, array $ $this->connection->execute($sql, array_merge($updateValue, $where)); } + + /** + * 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->getPdo()->beginTransaction(); + try { + foreach ($oldRules as $i => $oldRule) { + $this->updatePolicy($sec, $ptype, $oldRule, $newRules[$i]); + } + $this->connection->getPdo()->commit(); + } catch (Throwable $e) { + $this->connection->getPdo()->rollback(); + throw $e; + } + } } diff --git a/tests/AdapterTest.php b/tests/AdapterTest.php index 403f334..5493b29 100644 --- a/tests/AdapterTest.php +++ b/tests/AdapterTest.php @@ -245,6 +245,34 @@ public function testUpdatePolicy() ], $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()); + } + protected function env($key, $default = null) { $value = getenv($key);