Skip to content

Commit aef0b4b

Browse files
committed
feat: support Casbin UpdatableAdapter interface
1 parent ca34f2b commit aef0b4b

File tree

2 files changed

+59
-1
lines changed

2 files changed

+59
-1
lines changed

src/Adapters/DatabaseAdapter.php

+30-1
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,9 @@
1515
use Casbin\Persist\FilteredAdapter;
1616
use Casbin\Persist\Adapters\Filter;
1717
use Casbin\Exceptions\InvalidFilterTypeException;
18+
use Casbin\Persist\UpdatableAdapter;
1819

19-
class DatabaseAdapter implements Adapter, BatchAdapter, FilteredAdapter
20+
class DatabaseAdapter implements Adapter, BatchAdapter, FilteredAdapter, UpdatableAdapter
2021
{
2122
use AdapterHelper;
2223

@@ -261,4 +262,32 @@ public function setFiltered(bool $filtered): void
261262
{
262263
$this->filtered = $filtered;
263264
}
265+
266+
/**
267+
* Updates a policy rule from storage.
268+
* This is part of the Auto-Save feature.
269+
*
270+
* @param string $sec
271+
* @param string $ptype
272+
* @param string[] $oldRule
273+
* @param string[] $newPolicy
274+
*/
275+
public function updatePolicy(string $sec, string $ptype, array $oldRule, array $newPolicy): void
276+
{
277+
$instance = RulesModel::create();
278+
$where = [];
279+
$update = [];
280+
$where['ptype'] = $ptype;
281+
282+
foreach ($oldRule as $key => $value) {
283+
$where['v' . $key] = $value;
284+
}
285+
286+
$instance = $instance->where($where)->get();
287+
foreach ($newPolicy as $key => $value) {
288+
$update['v' . $key] = $value;
289+
}
290+
291+
$instance->update($update);
292+
}
264293
}

tests/DatabaseAdapterTest.php

+29
Original file line numberDiff line numberDiff line change
@@ -189,4 +189,33 @@ public function testLoadFilteredPolicy()
189189
['alice', 'data1', 'read'],
190190
], $e->getPolicy());
191191
}
192+
193+
public function testUpdatePolicy()
194+
{
195+
$e = $this->getEnforcer();
196+
197+
$this->assertEquals([
198+
['alice', 'data1', 'read'],
199+
['bob', 'data2', 'write'],
200+
['data2_admin', 'data2', 'read'],
201+
['data2_admin', 'data2', 'write'],
202+
], $e->getPolicy());
203+
204+
$e->updatePolicy(
205+
['alice', 'data1', 'read'],
206+
['alice', 'data1', 'write']
207+
);
208+
209+
$e->updatePolicy(
210+
['bob', 'data2', 'write'],
211+
['bob', 'data2', 'read']
212+
);
213+
214+
$this->assertEquals([
215+
['alice', 'data1', 'write'],
216+
['bob', 'data2', 'read'],
217+
['data2_admin', 'data2', 'read'],
218+
['data2_admin', 'data2', 'write'],
219+
], $e->getPolicy());
220+
}
192221
}

0 commit comments

Comments
 (0)