]> BookStack Code Mirror - bookstack/blob - tests/Helpers/UserRoleProvider.php
8c2718bc3e2831ef37663df41d7641a3c2ac3d2f
[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 without any relations.
55      */
56     public function newUser(array $attrs = []): User
57     {
58         return User::factory()->create($attrs);
59     }
60
61     /**
62      * Create a new fresh user, with the given attrs, that has assigned a fresh role
63      * that has the given role permissions.
64      * Intended as a helper to create a blank slate baseline user and role.
65      * @return array{0: User, 1: Role}
66      */
67     public function newUserWithRole(array $userAttrs = [], array $rolePermissions = []): array
68     {
69         $user = $this->newUser($userAttrs);
70         $role = $this->attachNewRole($user, $rolePermissions);
71
72         return [$user, $role];
73     }
74
75     /**
76      * Attach a new role, with the given role permissions, to the given user
77      * and return that role.
78      */
79     public function attachNewRole(User $user, array $rolePermissions = []): Role
80     {
81         $role = $this->createRole($rolePermissions);
82         $user->attachRole($role);
83         return $role;
84     }
85
86     /**
87      * Create a new basic role with the given role permissions.
88      */
89     public function createRole(array $rolePermissions = []): Role
90     {
91         $permissionRepo = app(PermissionsRepo::class);
92         $roleData = Role::factory()->make()->toArray();
93         $roleData['permissions'] = $rolePermissions;
94
95         return $permissionRepo->saveNewRole($roleData);
96     }
97 }