Skip to content

Commit 5b02e5c

Browse files
authored
Merge pull request #5 from basakest/updatable-adapter
feat: support Casbin UpdatableAdapter interface
2 parents 1f3e0b9 + 853ab2b commit 5b02e5c

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed

src/Adapter.php

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use Casbin\Exceptions\CasbinException;
66
use Casbin\Persist\Adapter as AdapterContract;
77
use Casbin\Persist\BatchAdapter as BatchAdapterContract;
8+
use Casbin\Persist\UpdatableAdapter as UpdatableAdapterContract;
89
use Casbin\Persist\AdapterHelper;
910
use Cake\ORM\TableRegistry;
1011
use CasbinAdapter\Cake\Model\Table\CasbinRuleTable;
@@ -14,7 +15,7 @@
1415
*
1516
1617
*/
17-
class Adapter implements AdapterContract, BatchAdapterContract
18+
class Adapter implements AdapterContract, BatchAdapterContract, UpdatableAdapterContract
1819
{
1920
use AdapterHelper;
2021

@@ -134,6 +135,30 @@ public function removePolicies(string $sec, string $ptype, array $rules): void
134135
});
135136
}
136137

138+
/**
139+
* Updates a policy rule from storage.
140+
* This is part of the Auto-Save feature.
141+
*
142+
* @param string $sec
143+
* @param string $ptype
144+
* @param string[] $oldRule
145+
* @param string[] $newPolicy
146+
*/
147+
public function updatePolicy(string $sec, string $ptype, array $oldRule, array $newPolicy): void
148+
{
149+
$entity = $this->table->find()->where(['ptype' => $ptype]);
150+
foreach ($oldRule as $k => $v) {
151+
$entity->where(['v' . $k => $v]);
152+
}
153+
$first = $entity->first();
154+
155+
foreach ($newPolicy as $k => $v) {
156+
$key = 'v' . $k;
157+
$first->$key = $v;
158+
}
159+
$this->table->save($first);
160+
}
161+
137162
protected function getTable()
138163
{
139164
return TableRegistry::getTableLocator()->get('CasbinRule', [

tests/DatabaseAdapterTest.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,4 +133,32 @@ public function testRemovePolicies()
133133
['bob', 'data2', 'write']
134134
], $e->getPolicy());
135135
}
136+
137+
public function testUpdatePolicy()
138+
{
139+
$e = $this->getEnforcer();
140+
$this->assertEquals([
141+
['alice', 'data1', 'read'],
142+
['bob', 'data2', 'write'],
143+
['data2_admin', 'data2', 'read'],
144+
['data2_admin', 'data2', 'write'],
145+
], $e->getPolicy());
146+
147+
$e->updatePolicy(
148+
['alice', 'data1', 'read'],
149+
['alice', 'data1', 'write']
150+
);
151+
152+
$e->updatePolicy(
153+
['bob', 'data2', 'write'],
154+
['bob', 'data2', 'read']
155+
);
156+
157+
$this->assertEquals([
158+
['alice', 'data1', 'write'],
159+
['bob', 'data2', 'read'],
160+
['data2_admin', 'data2', 'read'],
161+
['data2_admin', 'data2', 'write'],
162+
], $e->getPolicy());
163+
}
136164
}

0 commit comments

Comments
 (0)