Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 51 additions & 1 deletion src/Adapters/DatabaseAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@
use EasySwoole\ORM\Exception\Exception;
use EasySwoole\Permission\Model\RulesModel;
use Throwable;
use Casbin\Persist\BatchAdapter;

class DatabaseAdapter implements Adapter
class DatabaseAdapter implements Adapter, BatchAdapter
{
use AdapterHelper;

Expand Down Expand Up @@ -145,4 +146,53 @@ public function removeFilteredPolicy(string $sec, string $ptype, int $fieldIndex

$instance->destroy();
}

/**
* adds a policy rules to the storage.
* This is part of the Auto-Save feature.
*
* @param string $sec
* @param string $ptype
* @param array $rules
*/
public function addPolicies(string $sec, string $ptype, array $rules): void
{
$cols = [];

foreach($rules as $rule) {
$temp = [];
$temp['ptype'] = $ptype;
foreach ($rule as $key => $value) {
$temp['v'.strval($key)] = $value;
}
$cols[] = $temp;
}

RulesModel::create()->saveAll($cols);
}

/**
* removes policy rules from the storage.
* This is part of the Auto-Save feature.
*
* @param string $sec
* @param string $ptype
* @param array $rules
*/
public function removePolicies(string $sec, string $ptype, array $rules): void
{
$ids = [];

foreach($rules as $rule) {
$where = [];
$where['ptype'] = $ptype;
foreach ($rule as $key => $value) {
$where['v'.strval($key)] = $value;
}
$ret = RulesModel::create()->get($where);
$ret && $ids[] = $ret->id;
}

RulesModel::create()->destroy($ids);
}
}
35 changes: 35 additions & 0 deletions tests/DatabaseAdapterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,4 +108,39 @@ public function testSavePolicy()
$adapter->savePolicy($model);
$this->assertTrue($e->enforce('alice', 'data4', 'read'));
}

public function testAddPolicies()
{
$policies = [
['u1', 'd1', 'read'],
['u2', 'd2', 'read'],
['u3', 'd3', 'read'],
];
$e = $this->getEnforcer();
$e->clearPolicy();
$this->assertEquals([], $e->getPolicy());
$e->addPolicies($policies);
$this->assertEquals($policies, $e->getPolicy());
}

public function testRemovePolicies()
{
$e = $this->getEnforcer();
$this->assertEquals([
['alice', 'data1', 'read'],
['bob', 'data2', 'write'],
['data2_admin', 'data2', 'read'],
['data2_admin', 'data2', 'write'],
], $e->getPolicy());

$e->removePolicies([
['data2_admin', 'data2', 'read'],
['data2_admin', 'data2', 'write'],
]);

$this->assertEquals([
['alice', 'data1', 'read'],
['bob', 'data2', 'write']
], $e->getPolicy());
}
}