|
8 | 8 | use Casbin\Persist\AdapterHelper;
|
9 | 9 | use Casbin\Persist\UpdatableAdapter;
|
10 | 10 | use Casbin\Persist\BatchAdapter;
|
| 11 | +use Casbin\Persist\FilteredAdapter; |
| 12 | +use Casbin\Persist\Adapters\Filter; |
| 13 | +use Casbin\Exceptions\InvalidFilterTypeException; |
11 | 14 | use think\facade\Db;
|
12 | 15 |
|
13 | 16 | /**
|
14 | 17 | * DatabaseAdapter.
|
15 | 18 | *
|
16 | 19 |
|
17 | 20 | */
|
18 |
| -class DatabaseAdapter implements Adapter, UpdatableAdapter, BatchAdapter |
| 21 | +class DatabaseAdapter implements Adapter, UpdatableAdapter, BatchAdapter, FilteredAdapter |
19 | 22 | {
|
20 | 23 | use AdapterHelper;
|
21 | 24 |
|
| 25 | + /** |
| 26 | + * @var bool |
| 27 | + */ |
| 28 | + private $filtered = false; |
| 29 | + |
22 | 30 | /**
|
23 | 31 | * Rules model.
|
24 | 32 | *
|
@@ -238,4 +246,59 @@ public function updatePolicies(string $sec, string $ptype, array $oldRules, arra
|
238 | 246 | }
|
239 | 247 | });
|
240 | 248 | }
|
| 249 | + |
| 250 | + /** |
| 251 | + * Returns true if the loaded policy has been filtered. |
| 252 | + * |
| 253 | + * @return bool |
| 254 | + */ |
| 255 | + public function isFiltered(): bool |
| 256 | + { |
| 257 | + return $this->filtered; |
| 258 | + } |
| 259 | + |
| 260 | + /** |
| 261 | + * Sets filtered parameter. |
| 262 | + * |
| 263 | + * @param bool $filtered |
| 264 | + */ |
| 265 | + public function setFiltered(bool $filtered): void |
| 266 | + { |
| 267 | + $this->filtered = $filtered; |
| 268 | + } |
| 269 | + |
| 270 | + /** |
| 271 | + * Loads only policy rules that match the filter. |
| 272 | + * |
| 273 | + * @param Model $model |
| 274 | + * @param mixed $filter |
| 275 | + */ |
| 276 | + public function loadFilteredPolicy(Model $model, $filter): void |
| 277 | + { |
| 278 | + $instance = $this->model; |
| 279 | + |
| 280 | + if (is_string($filter)) { |
| 281 | + $instance = $instance->whereRaw($filter); |
| 282 | + } elseif ($filter instanceof Filter) { |
| 283 | + foreach ($filter->p as $k => $v) { |
| 284 | + $where[$v] = $filter->g[$k]; |
| 285 | + $instance = $instance->where($v, $filter->g[$k]); |
| 286 | + } |
| 287 | + } elseif ($filter instanceof \Closure) { |
| 288 | + $instance = $instance->where($filter); |
| 289 | + } else { |
| 290 | + throw new InvalidFilterTypeException('invalid filter type'); |
| 291 | + } |
| 292 | + $rows = $instance->select()->hidden(['id'])->toArray(); |
| 293 | + foreach ($rows as $row) { |
| 294 | + $row = array_filter($row, function ($value) { |
| 295 | + return !is_null($value) && $value !== ''; |
| 296 | + }); |
| 297 | + $line = implode(', ', array_filter($row, function ($val) { |
| 298 | + return '' != $val && !is_null($val); |
| 299 | + })); |
| 300 | + $this->loadPolicyLine(trim($line), $model); |
| 301 | + } |
| 302 | + $this->setFiltered(true); |
| 303 | + } |
241 | 304 | }
|
0 commit comments