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