]> BookStack Code Mirror - bookstack/blob - tests/Helpers/UserRoleProvider.php
Added additional entity_role_permission scenario tests
[bookstack] / tests / Helpers / UserRoleProvider.php
1 <?php
2
3 namespace Tests\Helpers;
4
5 use BookStack\Auth\Permissions\PermissionsRepo;
6 use BookStack\Auth\Role;
7 use BookStack\Auth\User;
8
9 class UserRoleProvider
10 {
11     protected ?User $admin = null;
12     protected ?User $editor = null;
13
14     /**
15      * Get a typical "Admin" user.
16      */
17     public function admin(): User
18     {
19         if (is_null($this->admin)) {
20             $adminRole = Role::getSystemRole('admin');
21             $this->admin = $adminRole->users->first();
22         }
23
24         return $this->admin;
25     }
26
27     /**
28      * Get a typical "Editor" user.
29      */
30     public function editor(): User
31     {
32         if ($this->editor === null) {
33             $editorRole = Role::getRole('editor');
34             $this->editor = $editorRole->users->first();
35         }
36
37         return $this->editor;
38     }
39
40     /**
41      * Get a typical "Viewer" user.
42      */
43     public function viewer(array $attributes = []): User
44     {
45         $user = Role::getRole('viewer')->users()->first();
46         if (!empty($attributes)) {
47             $user->forceFill($attributes)->save();
48         }
49
50         return $user;
51     }
52
53     /**
54      * Create a new fresh user, with the given attrs, that has assigned a fresh role
55      * that has the given role permissions.
56      * Intended as a helper to create a blank slate baseline user and role.
57      * @return array{0: User, 1: Role}
58      */
59     public function newUserWithRole(array $userAttrs = [], array $rolePermissions = []): array
60     {
61         $user = User::factory()->create($userAttrs);
62         $role = $this->attachNewRole($user, $rolePermissions);
63
64         return [$user, $role];
65     }
66
67     /**
68      * Attach a new role, with the given role permissions, to the given user
69      * and return that role.
70      */
71     public function attachNewRole(User $user, array $rolePermissions = []): Role
72     {
73         $role = $this->createRole($rolePermissions);
74         $user->attachRole($role);
75         return $role;
76     }
77
78     /**
79      * Create a new basic role with the given role permissions.
80      */
81     public function createRole(array $rolePermissions = []): Role
82     {
83         $permissionRepo = app(PermissionsRepo::class);
84         $roleData = Role::factory()->make()->toArray();
85         $roleData['permissions'] = array_flip($rolePermissions);
86
87         return $permissionRepo->saveNewRole($roleData);
88     }
89 }