]> BookStack Code Mirror - bookstack/blob - app/Repos/UserRepo.php
Fixed name retrieval on missing users and added tests to cover along with some test...
[bookstack] / app / Repos / UserRepo.php
1 <?php namespace BookStack\Repos;
2
3
4 use BookStack\Role;
5 use BookStack\User;
6
7 class UserRepo
8 {
9
10     protected $user;
11     protected $role;
12
13     /**
14      * UserRepo constructor.
15      * @param $user
16      */
17     public function __construct(User $user, Role $role)
18     {
19         $this->user = $user;
20         $this->role = $role;
21     }
22
23     /**
24      * @param string $email
25      * @return User|null
26      */
27     public function getByEmail($email)
28     {
29         return $this->user->where('email', '=', $email)->first();
30     }
31
32     /**
33      * @param int $id
34      * @return User
35      */
36     public function getById($id)
37     {
38         return $this->user->findOrFail($id);
39     }
40
41     /**
42      * Creates a new user and attaches a role to them.
43      * @param array $data
44      * @return User
45      */
46     public function registerNew(array $data)
47     {
48         $user = $this->create($data);
49         $this->attachDefaultRole($user);
50         return $user;
51     }
52
53     /**
54      * Give a user the default role. Used when creating a new user.
55      * @param $user
56      */
57     public function attachDefaultRole($user)
58     {
59         $roleId = \Setting::get('registration-role');
60         if ($roleId === false) $roleId = $this->role->getDefault()->id;
61         $user->attachRoleId($roleId);
62     }
63
64     /**
65      * Checks if the give user is the only admin.
66      * @param User $user
67      * @return bool
68      */
69     public function isOnlyAdmin(User $user)
70     {
71         if ($user->role->name != 'admin') {
72             return false;
73         }
74
75         $adminRole = $this->role->where('name', '=', 'admin')->first();
76         if (count($adminRole->users) > 1) {
77             return false;
78         }
79
80         return true;
81     }
82
83     /**
84      * Create a new basic instance of user.
85      * @param array $data
86      * @return User
87      */
88     public function create(array $data)
89     {
90         return $this->user->create([
91             'name'     => $data['name'],
92             'email'    => $data['email'],
93             'password' => bcrypt($data['password'])
94         ]);
95     }
96
97     /**
98      * Remove the given user from storage, Delete all related content.
99      * @param User $user
100      */
101     public function destroy(User $user)
102     {
103         $user->socialAccounts()->delete();
104         $user->delete();
105     }
106 }