Skip to content

Commit 020b48f

Browse files
authored
Merge pull request #127 from kenjis/refactor-autorizable-model
refactor: extract Models from Authorizable
2 parents 79ed3e2 + 90b2eb3 commit 020b48f

File tree

3 files changed

+195
-54
lines changed

3 files changed

+195
-54
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
<?php
2+
3+
namespace CodeIgniter\Shield\Authorization\Models;
4+
5+
use CodeIgniter\Model;
6+
7+
class GroupModel extends Model
8+
{
9+
protected $table = 'auth_groups_users';
10+
protected $primaryKey = 'id';
11+
protected $returnType = 'array';
12+
protected $useSoftDeletes = false;
13+
protected $allowedFields = [
14+
'user_id',
15+
'group',
16+
'created_at',
17+
];
18+
protected $useTimestamps = false;
19+
protected $validationRules = [];
20+
protected $validationMessages = [];
21+
protected $skipValidation = false;
22+
23+
/**
24+
* @param int|string $userId
25+
*/
26+
public function getByUserId($userId): array
27+
{
28+
$groups = $this->builder()
29+
->select('group')
30+
->where('user_id', $userId)
31+
->get()
32+
->getResultArray();
33+
34+
return array_column($groups, 'group');
35+
}
36+
37+
/**
38+
* @param int|string $userId
39+
*/
40+
public function deleteAll($userId): void
41+
{
42+
$this->builder()
43+
->where('user_id', $userId)
44+
->delete();
45+
}
46+
47+
/**
48+
* @param int|string $userId
49+
* @param mixed $cache
50+
*/
51+
public function deleteNotIn($userId, $cache): void
52+
{
53+
$this->builder()
54+
->where('user_id', $userId)
55+
->whereNotIn('group', $cache)
56+
->delete();
57+
}
58+
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
<?php
2+
3+
namespace CodeIgniter\Shield\Authorization\Models;
4+
5+
use CodeIgniter\Model;
6+
7+
class PermissionModel extends Model
8+
{
9+
protected $table = 'auth_permissions_users';
10+
protected $primaryKey = 'id';
11+
protected $returnType = 'array';
12+
protected $useSoftDeletes = false;
13+
protected $allowedFields = [
14+
'user_id',
15+
'permission',
16+
'created_at',
17+
];
18+
protected $useTimestamps = false;
19+
protected $validationRules = [];
20+
protected $validationMessages = [];
21+
protected $skipValidation = false;
22+
23+
/**
24+
* @param int|string $userId
25+
*/
26+
public function getByUserId($userId): array
27+
{
28+
$permission = $this->builder()
29+
->select('permission')
30+
->where('user_id', $userId)
31+
->get()
32+
->getResultArray();
33+
34+
return array_column($permission, 'permission');
35+
}
36+
37+
/**
38+
* @param int|string $userId
39+
*/
40+
public function deleteAll($userId): void
41+
{
42+
$this->builder()
43+
->where('user_id', $userId)
44+
->delete();
45+
}
46+
47+
/**
48+
* @param int|string $userId
49+
* @param mixed $cache
50+
*/
51+
public function deleteNotIn($userId, $cache): void
52+
{
53+
$this->builder()
54+
->where('user_id', $userId)
55+
->whereNotIn('permission', $cache)
56+
->delete();
57+
}
58+
}

src/Authorization/Traits/Authorizable.php

Lines changed: 79 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
44

55
use CodeIgniter\I18n\Time;
66
use CodeIgniter\Shield\Authorization\AuthorizationException;
7-
use Exception;
7+
use CodeIgniter\Shield\Authorization\Models\GroupModel;
8+
use CodeIgniter\Shield\Authorization\Models\PermissionModel;
89

910
trait Authorizable
1011
{
@@ -19,9 +20,8 @@ trait Authorizable
1920
public function addGroup(string ...$groups): self
2021
{
2122
$this->populateGroups();
22-
$configGroups = function_exists('setting')
23-
? array_keys(setting('AuthGroups.groups'))
24-
: array_keys(config('AuthGroups')->groups);
23+
24+
$configGroups = $this->getConfigGroups();
2525

2626
$groupCount = count($this->groupCache);
2727

@@ -43,7 +43,7 @@ public function addGroup(string ...$groups): self
4343

4444
// Only save the results if there's anything new.
4545
if (count($this->groupCache) > $groupCount) {
46-
$this->saveGroupsOrPermissions('group');
46+
$this->saveGroups();
4747
}
4848

4949
return $this;
@@ -66,7 +66,7 @@ public function removeGroup(string ...$groups): self
6666
$this->groupCache = array_diff($this->groupCache, $groups);
6767

6868
// Update the database.
69-
$this->saveGroupsOrPermissions('group');
69+
$this->saveGroups();
7070

7171
return $this;
7272
}
@@ -83,9 +83,8 @@ public function removeGroup(string ...$groups): self
8383
public function syncGroups(array $groups): self
8484
{
8585
$this->populateGroups();
86-
$configGroups = function_exists('setting')
87-
? array_keys(setting('AuthGroups.groups'))
88-
: array_keys(config('AuthGroups')->groups);
86+
87+
$configGroups = $this->getConfigGroups();
8988

9089
foreach ($groups as $group) {
9190
if (! in_array($group, $configGroups, true)) {
@@ -94,7 +93,7 @@ public function syncGroups(array $groups): self
9493
}
9594

9695
$this->groupCache = $groups;
97-
$this->saveGroupsOrPermissions('group');
96+
$this->saveGroups();
9897

9998
return $this;
10099
}
@@ -130,9 +129,8 @@ public function getPermissions(): ?array
130129
public function addPermission(string ...$permissions): self
131130
{
132131
$this->populatePermissions();
133-
$configPermissions = function_exists('setting')
134-
? array_keys(setting('AuthGroups.permissions'))
135-
: array_keys(config('AuthGroups')->permissions);
132+
133+
$configPermissions = $this->getConfigPermissions();
136134

137135
$permissionCount = count($this->permissionsCache);
138136

@@ -154,7 +152,7 @@ public function addPermission(string ...$permissions): self
154152

155153
// Only save the results if there's anything new.
156154
if (count($this->permissionsCache) > $permissionCount) {
157-
$this->saveGroupsOrPermissions('permission');
155+
$this->savePermissions();
158156
}
159157

160158
return $this;
@@ -177,7 +175,7 @@ public function removePermission(string ...$permissions): self
177175
$this->permissionsCache = array_diff($this->permissionsCache, $permissions);
178176

179177
// Update the database.
180-
$this->saveGroupsOrPermissions('permission');
178+
$this->savePermissions();
181179

182180
return $this;
183181
}
@@ -194,9 +192,8 @@ public function removePermission(string ...$permissions): self
194192
public function syncPermissions(array $permissions): self
195193
{
196194
$this->populatePermissions();
197-
$configPermissions = function_exists('setting')
198-
? array_keys(setting('AuthGroups.permissions'))
199-
: array_keys(config('AuthGroups')->permissions);
195+
196+
$configPermissions = $this->getConfigPermissions();
200197

201198
foreach ($permissions as $permission) {
202199
if (! in_array($permission, $configPermissions, true)) {
@@ -205,7 +202,7 @@ public function syncPermissions(array $permissions): self
205202
}
206203

207204
$this->permissionsCache = $permissions;
208-
$this->saveGroupsOrPermissions('permission');
205+
$this->savePermissions();
209206

210207
return $this;
211208
}
@@ -218,6 +215,7 @@ public function syncPermissions(array $permissions): self
218215
public function hasPermission(string $permission): bool
219216
{
220217
$this->populatePermissions();
218+
221219
$permission = strtolower($permission);
222220

223221
return in_array($permission, $this->permissionsCache, true);
@@ -230,6 +228,7 @@ public function hasPermission(string $permission): bool
230228
public function can(string $permission): bool
231229
{
232230
$this->populatePermissions();
231+
233232
$permission = strtolower($permission);
234233

235234
// Check user's permissions
@@ -291,12 +290,10 @@ private function populateGroups(): void
291290
return;
292291
}
293292

294-
$groups = db_connect()->table('auth_groups_users')
295-
->where('user_id', $this->id)
296-
->get()
297-
->getResultArray();
293+
/** @var GroupModel $groupModel */
294+
$groupModel = model(GroupModel::class);
298295

299-
$this->groupCache = array_column($groups, 'group');
296+
$this->groupCache = $groupModel->getByUserId($this->id);
300297
}
301298

302299
/**
@@ -309,50 +306,57 @@ private function populatePermissions(): void
309306
return;
310307
}
311308

312-
$permissions = db_connect()->table('auth_permissions_users')
313-
->where('user_id', $this->id)
314-
->get()
315-
->getResultArray();
309+
/** @var PermissionModel $permissionModel */
310+
$permissionModel = model(PermissionModel::class);
316311

317-
$this->permissionsCache = array_column($permissions, 'permission');
312+
$this->permissionsCache = $permissionModel->getByUserId($this->id);
318313
}
319314

320315
/**
321-
* Inserts or Updates either the current groups
322-
* or the current permissions.
316+
* Inserts or Updates the current groups.
317+
*/
318+
private function saveGroups(): void
319+
{
320+
/** @var GroupModel $model */
321+
$model = model(GroupModel::class);
322+
323+
$cache = $this->groupCache;
324+
325+
$this->saveGroupsOrPermissions('group', $model, $cache);
326+
}
327+
328+
/**
329+
* Inserts or Updates either the current permissions.
330+
*/
331+
private function savePermissions(): void
332+
{
333+
/** @var PermissionModel $model */
334+
$model = model(PermissionModel::class);
335+
336+
$cache = $this->permissionsCache;
337+
338+
$this->saveGroupsOrPermissions('permission', $model, $cache);
339+
}
340+
341+
/**
342+
* @phpstan-param 'group'|'permission' $type
323343
*
324-
* @throws Exception
344+
* @param GroupModel|PermissionModel $model
325345
*/
326-
private function saveGroupsOrPermissions(string $type): void
346+
private function saveGroupsOrPermissions(string $type, $model, array $cache): void
327347
{
328-
$table = $type === 'group'
329-
? 'auth_groups_users'
330-
: 'auth_permissions_users';
331-
$cache = $type === 'group'
332-
? $this->groupCache
333-
: $this->permissionsCache;
334-
335-
$existing = db_connect()->table($table)
336-
->where('user_id', $this->id)
337-
->get()
338-
->getResultArray();
339-
$existing = array_column($existing, $type);
348+
$existing = $model->getByUserId($this->id);
340349

341350
$new = array_diff($cache, $existing);
342351

343352
// Delete any not in the cache
344-
if (count($cache)) {
345-
db_connect()->table($table)
346-
->where('user_id', $this->id)
347-
->whereNotIn($type, $cache)
348-
->delete();
353+
if ($cache !== []) {
354+
$model->deleteNotIn($this->id, $cache);
349355
}
350356
// Nothing in the cache? Then make sure
351357
// we delete all from this user
352358
else {
353-
db_connect()->table($table)
354-
->where('user_id', $this->id)
355-
->delete();
359+
$model->deleteAll($this->id);
356360
}
357361

358362
// Insert new ones
@@ -366,7 +370,28 @@ private function saveGroupsOrPermissions(string $type): void
366370
'created_at' => Time::now()->toDateTimeString(),
367371
];
368372
}
369-
db_connect()->table($table)->insertBatch($inserts);
373+
374+
$model->insertBatch($inserts);
370375
}
371376
}
377+
378+
/**
379+
* @return string[]
380+
*/
381+
private function getConfigGroups(): array
382+
{
383+
return function_exists('setting')
384+
? array_keys(setting('AuthGroups.groups'))
385+
: array_keys(config('AuthGroups')->groups);
386+
}
387+
388+
/**
389+
* @return string[]
390+
*/
391+
private function getConfigPermissions(): array
392+
{
393+
return function_exists('setting')
394+
? array_keys(setting('AuthGroups.permissions'))
395+
: array_keys(config('AuthGroups')->permissions);
396+
}
372397
}

0 commit comments

Comments
 (0)