Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Develop #15

Merged
merged 3 commits into from
Dec 20, 2024
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
15 changes: 7 additions & 8 deletions .github/workflows/build.yml → .github/workflows/phpunit.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: build
name: PHPUnit

on: [push, pull_request]

Expand All @@ -19,14 +19,13 @@ jobs:
strategy:
fail-fast: true
matrix:
php: [ 8.0, 8.1, 8.2, 8.3 ]
stability: [ prefer-lowest, prefer-stable ]
php: [ 8.0, 8.1, 8.2, 8.3, 8.4 ]

name: PHP ${{ matrix.php }} - ${{ matrix.stability }}
name: PHP ${{ matrix.php }}

steps:
- name: Checkout code
uses: actions/checkout@v2
uses: actions/checkout@v4

- name: Setup PHP
uses: shivammathur/setup-php@v2
Expand All @@ -40,7 +39,7 @@ jobs:

- name: Cache Composer packages
id: composer-cache
uses: actions/cache@v2
uses: actions/cache@v4
with:
path: vendor
key: ${{ runner.os }}-${{ matrix.php }}-${{ hashFiles('**/composer.lock') }}
Expand All @@ -58,8 +57,8 @@ jobs:
runs-on: ubuntu-latest
needs: [ test ]
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 'lts/*'

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Doctrine DBAL Adapter for Casbin

[![Build Status](https://github.com/php-casbin/dbal-adapter/actions/workflows/build.yml/badge.svg)](https://github.com/php-casbin/dbal-adapter/actions/workflows/build.yml)
[![PHPUnit](https://github.com/php-casbin/dbal-adapter/actions/workflows/phpunit.yml/badge.svg)](https://github.com/php-casbin/dbal-adapter/actions/workflows/phpunit.yml)
[![Coverage Status](https://coveralls.io/repos/github/php-casbin/dbal-adapter/badge.svg)](https://coveralls.io/github/php-casbin/dbal-adapter)
[![Latest Stable Version](https://poser.pugx.org/casbin/dbal-adapter/v/stable)](https://packagist.org/packages/casbin/dbal-adapter)
[![Total Downloads](https://poser.pugx.org/casbin/dbal-adapter/downloads)](https://packagist.org/packages/casbin/dbal-adapter)
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"authors": [
{
"name": "TechLee",
"email": "techlee@qq.com"
"email": "leeqvip@gmail.com"
}
],
"license": "Apache-2.0",
Expand Down
58 changes: 30 additions & 28 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -1,28 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="Application Test Suite">
<directory>./tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./src</directory>
</whitelist>
</filter>
<logging>
<log type="coverage-clover" target="build/logs/clover.xml"/>
<log type="coverage-html" target="build/html"/>
</logging>
<php>
<env name="DB_DATABASE" value="casbin"/>
</php>
</phpunit>
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
backupGlobals="false" backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd">
<coverage processUncoveredFiles="true">
<include>
<directory suffix=".php">./src</directory>
</include>
<report>
<clover outputFile="build/logs/clover.xml"/>
<html outputDirectory="build/html"/>
</report>
</coverage>
<testsuites>
<testsuite name="Application Test Suite">
<directory>./tests/</directory>
</testsuite>
</testsuites>
<logging/>
<php>
<env name="DB_DATABASE" value="casbin"/>
</php>
</phpunit>
89 changes: 25 additions & 64 deletions src/Adapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,20 @@

use Casbin\Persist\AdapterHelper;
use Casbin\Model\Model;
use Casbin\Persist\BatchAdapter;
use Casbin\Persist\FilteredAdapter;
use Casbin\Persist\UpdatableAdapter;
use Casbin\Persist\{BatchAdapter, FilteredAdapter, UpdatableAdapter};
use Closure;
use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Driver\ResultStatement;
use Doctrine\DBAL\{DBALException, Exception};
use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Exception;
use Doctrine\DBAL\Query\Expression\CompositeExpression;
use Doctrine\DBAL\Schema\Schema;
use Throwable;

/**
* DBAL Adapter.
*
* @author techlee@qq.com
* @author leeqvip@gmail.com
*/
class Adapter implements FilteredAdapter, BatchAdapter, UpdatableAdapter
{
Expand All @@ -34,32 +30,32 @@ class Adapter implements FilteredAdapter, BatchAdapter, UpdatableAdapter
*
* @var Connection
*/
protected $connection;
protected Connection $connection;

/**
* Casbin policies table name.
*
* @var string
*/
public $policyTableName = 'casbin_rule';
public string $policyTableName = 'casbin_rule';

/**
* @var bool
*/
private $filtered = false;
private bool $filtered = false;

/**
* @var string[]
*/
protected $columns = ['p_type', 'v0', 'v1', 'v2', 'v3', 'v4', 'v5'];
protected array $columns = ['p_type', 'v0', 'v1', 'v2', 'v3', 'v4', 'v5'];

/**
* Adapter constructor.
*
* @param Connection|array $connection
* @throws Exception
*/
public function __construct($connection)
public function __construct(Connection|array $connection)
{
if ($connection instanceof Connection) {
$this->connection = $connection;
Expand All @@ -85,7 +81,7 @@ public function __construct($connection)
* @return Adapter
* @throws Exception
*/
public static function newAdapter($connection): Adapter
public static function newAdapter(Connection|array $connection): Adapter
{
return new static($connection);
}
Expand All @@ -95,9 +91,9 @@ public static function newAdapter($connection): Adapter
*
* @return void
*/
public function initTable()
public function initTable(): void
{
$sm = method_exists($this->connection, "createSchemaManager") ? $sm = $this->connection->createSchemaManager() : $sm = $this->connection->getSchemaManager();
$sm = $this->connection->createSchemaManager();
if (!$sm->tablesExist([$this->policyTableName])) {
$schema = new Schema();
$table = $schema->createTable($this->policyTableName);
Expand All @@ -118,10 +114,10 @@ public function initTable()
* @param $pType
* @param array $rule
*
* @return ResultStatement|int
* @return int|string
* @throws Exception
*/
public function savePolicyLine($pType, array $rule)
public function savePolicyLine(string $pType, array $rule): int|string
{
$queryBuilder = $this->connection->createQueryBuilder();
$queryBuilder
Expand All @@ -135,7 +131,7 @@ public function savePolicyLine($pType, array $rule)
$queryBuilder->setValue('v' . strval($key), '?')->setParameter($key + 1, $value);
}

return $this->executeQuery($queryBuilder);
return $queryBuilder->executeStatement();
}

/**
Expand All @@ -147,9 +143,9 @@ public function savePolicyLine($pType, array $rule)
public function loadPolicy(Model $model): void
{
$queryBuilder = $this->connection->createQueryBuilder();
$stmt = $this->executeQuery($queryBuilder->select('p_type', 'v0', 'v1', 'v2', 'v3', 'v4', 'v5')->from($this->policyTableName));
$stmt = $queryBuilder->select('p_type', 'v0', 'v1', 'v2', 'v3', 'v4', 'v5')->from($this->policyTableName)->executeQuery();

while ($row = $this->fetch($stmt)) {
while ($row = $stmt->fetchAssociative()) {
$this->loadPolicyArray($this->filterRule($row), $model);
}
}
Expand Down Expand Up @@ -179,11 +175,9 @@ public function loadFilteredPolicy(Model $model, $filter): void
throw new \Exception('invalid filter type');
}

$stmt = $this->executeQuery($queryBuilder->from($this->policyTableName));
while ($row = $this->fetch($stmt)) {
$line = implode(', ', array_filter($row, function ($val) {
return '' != $val && !is_null($val);
}));
$stmt = $queryBuilder->from($this->policyTableName)->executeQuery();
while ($row = $stmt->fetchAssociative()) {
$line = implode(', ', array_filter($row, static fn ($val): bool => '' != $val && !is_null($val)));
$this->loadPolicyLine(trim($line), $model);
}

Expand Down Expand Up @@ -247,9 +241,7 @@ public function addPolicies(string $sec, string $ptype, array $rules): void
$sets[] = array_pad([], $columnsCount, '?');
}

$valuesStr = implode(', ', array_map(function ($set) {
return '(' . implode(', ', $set) . ')';
}, $sets));
$valuesStr = implode(', ', array_map(static fn ($set): string => '(' . implode(', ', $set) . ')', $sets));

$sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $columns) . ')' .
' VALUES' . $valuesStr;
Expand All @@ -274,7 +266,7 @@ private function _removePolicy(Connection $conn, string $sec, string $ptype, arr
$queryBuilder->andWhere('v' . strval($key) . ' = ?')->setParameter($key + 1, $value);
}

$this->executeQuery($queryBuilder->delete($this->policyTableName));
$queryBuilder->delete($this->policyTableName)->executeStatement();
}

/**
Expand Down Expand Up @@ -331,13 +323,13 @@ public function _removeFilteredPolicy(string $sec, string $ptype, int $fieldInde
$fieldIndex++;
}

$stmt = $this->executeQuery($queryBuilder->select(...$this->columns)->from($this->policyTableName));
$stmt = $queryBuilder->select(...$this->columns)->from($this->policyTableName)->executeQuery();

while ($row = $this->fetch($stmt)) {
while ($row = $stmt->fetchAssociative()) {
$removedRules[] = $this->filterRule($row);
}

$this->executeQuery($queryBuilder->delete($this->policyTableName));
$queryBuilder->delete($this->policyTableName)->executeStatement();
});

return $removedRules;
Expand Down Expand Up @@ -381,9 +373,7 @@ public function updatePolicy(string $sec, string $ptype, array $oldRule, array $
$queryBuilder->set('v' . strval($key), ':' . $placeholder)->setParameter($placeholder, $value);
}

$queryBuilder->update($this->policyTableName);

$this->executeQuery($queryBuilder);
$queryBuilder->update($this->policyTableName)->executeStatement();
}

/**
Expand Down Expand Up @@ -484,33 +474,4 @@ public function getColumns(): array
{
return $this->columns;
}

/**
* @param \Doctrine\DBAL\Result|\Doctrine\DBAL\Driver\PDOStatement $stmt
*
* @return mixed
* @throws Exception
*/
private function fetch($stmt)
{
if (method_exists($stmt, 'fetchAssociative')) {
return $stmt->fetchAssociative();
}

return $stmt->fetch();
}

/**
* Calls correct query execution method depending on Doctrine version and
* returns the result.
*
* @param \Doctrine\DBAL\Query\QueryBuilder $query
*
* @return mixed
*/
private function executeQuery($query)
{
return method_exists($query, "executeQuery") ? $query->executeQuery() : $query->execute();
}

}
6 changes: 3 additions & 3 deletions src/Filter.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,19 @@
/**
* Class Filter
*
* @author techlee@qq.com
* @author leeqvip@gmail.com
*/
class Filter
{
/**
* @var string
*/
private $predicates = "";
private string $predicates = '';

/**
* @var array<int, mixed>|array<string, mixed>
*/
private $params = "";
private array $params = [];

/**
* Filter constructor.
Expand Down
1 change: 0 additions & 1 deletion tests/AdapterFeatureTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

use CasbinAdapter\DBAL\Adapter as DatabaseAdapter;
use CasbinAdapter\DBAL\Filter;
use Doctrine\DBAL\Query\Expression\CompositeExpression;
use Doctrine\DBAL\Query\QueryBuilder;

class AdapterFeatureTest extends TestCase
Expand Down
4 changes: 2 additions & 2 deletions tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ protected function initDb(DatabaseAdapter $adapter)
$conn = $adapter->getConnection();
$queryBuilder = $conn->createQueryBuilder();
$query = $queryBuilder->delete($tableName)->where('1 = 1');
method_exists($query, "executeQuery") ? $query->executeQuery() : $query->execute();
$query->executeStatement();

$data = [
['p_type' => 'p', 'v0' => 'alice', 'v1' => 'data1', 'v2' => 'read'],
Expand All @@ -44,7 +44,7 @@ protected function initDb(DatabaseAdapter $adapter)
];
foreach ($data as $row) {
$query = $queryBuilder->insert($tableName)->values(array_combine(array_keys($row), array_fill(0, count($row), '?')))->setParameters(array_values($row));
method_exists($query, "executeQuery") ? $query->executeQuery() : $query->execute();
$query->executeStatement();
}
}

Expand Down
Loading