Completed
Pull Request — dev (#235)
by Alies
07:44
created

EloquentUserRepository::save()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 5
nc 4
nop 2
dl 0
loc 11
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace App\Repositories;
4
5
use Exception;
6
use Carbon\Carbon;
7
use App\Models\User;
8
use App\Events\UserCreated;
9
use App\Events\UserDeleted;
10
use App\Events\UserUpdated;
11
use Illuminate\Support\Arr;
12
use Illuminate\Support\Facades\DB;
13
use App\Exceptions\GeneralException;
14
use Illuminate\Support\Facades\Hash;
15
use Illuminate\Contracts\Config\Repository;
16
use App\Repositories\Contracts\RoleRepository;
0 ignored issues
show
Bug introduced by
The type App\Repositories\Contracts\RoleRepository was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
17
use App\Repositories\Contracts\UserRepository;
18
use Mcamara\LaravelLocalization\LaravelLocalization;
19
20
/**
21
 * Class EloquentUserRepository.
22
 */
23
class EloquentUserRepository extends EloquentBaseRepository implements UserRepository
24
{
25
    /**
26
     * @var \Mcamara\LaravelLocalization\LaravelLocalization
27
     */
28
    protected $localization;
29
30
    /**
31
     * @var \Illuminate\Contracts\Config\Repository
32
     */
33
    protected $config;
34
35
    /**
36
     * @var RoleRepository
37
     */
38
    protected $roles;
39
40
    /**
41
     * EloquentUserRepository constructor.
42
     *
43
     * @param User                                             $user
44
     * @param \App\Repositories\Contracts\RoleRepository       $roles
45
     * @param \Mcamara\LaravelLocalization\LaravelLocalization $localization
46
     * @param \Illuminate\Contracts\Config\Repository          $config
47
     */
48
    public function __construct(
49
        User $user,
50
        RoleRepository $roles,
51
        LaravelLocalization $localization,
52
        Repository $config
53
    ) {
54
        parent::__construct($user);
55
        $this->roles = $roles;
56
        $this->localization = $localization;
57
        $this->config = $config;
58
    }
59
60
    /**
61
     * @param string $slug
62
     *
63
     * @return User
64
     */
65
    public function findBySlug($slug)
66
    {
67
        return $this->query()->whereSlug($slug)->first();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->query()->whereSlug($slug)->first() also could return the type Illuminate\Database\Eloquent\Model which includes types incompatible with the return type mandated by App\Repositories\Contrac...epository::findBySlug() of App\Models\User. Consider adding a type-check to rule them out.
Loading history...
68
    }
69
70
    /**
71
     * @param array $input
72
     * @param bool  $confirmed
73
     *
74
     * @throws \App\Exceptions\GeneralException
75
     *
76
     * @return \App\Models\User
77
     */
78
    public function store(array $input, $confirmed = false)
79
    {
80
        /** @var User $user */
81
        $user = $this->make(Arr::only($input, ['name', 'email', 'active']));
82
83
        if (isset($input['password'])) {
84
            $user->password = Hash::make($input['password']);
85
        }
86
87
        if ($confirmed) {
88
            $user->email_verified_at = Carbon::now();
89
        }
90
91
        if (empty($user->locale)) {
92
            $user->locale = $this->localization->getDefaultLocale();
93
        }
94
95
        if (empty($user->timezone)) {
96
            $user->timezone = $this->config->get('app.timezone');
97
        }
98
99
        if (! $this->save($user, $input)) {
100
            throw new GeneralException(__('exceptions.backend.users.create'));
101
        }
102
103
        event(new UserCreated($user));
104
105
        return $user;
106
    }
107
108
    /**
109
     * @param User  $user
110
     * @param array $input
111
     *
112
     * @throws Exception
113
     * @throws \Exception|\Throwable
114
     *
115
     * @return \App\Models\User
116
     */
117
    public function update(User $user, array $input)
118
    {
119
        if (! $user->can_edit) {
120
            throw new GeneralException(__('exceptions.backend.users.first_user_cannot_be_edited'));
121
        }
122
123
        $user->fill(Arr::except($input, 'password'));
124
125
        if ($user->is_super_admin && ! $user->active) {
126
            throw new GeneralException(__('exceptions.backend.users.first_user_cannot_be_disabled'));
127
        }
128
129
        if (! $this->save($user, $input)) {
130
            throw new GeneralException(__('exceptions.backend.users.update'));
131
        }
132
133
        event(new UserUpdated($user));
134
135
        return $user;
136
    }
137
138
    /**
139
     * @param \App\Models\User $user
140
     * @param array            $input
141
     *
142
     * @throws \App\Exceptions\GeneralException
143
     *
144
     * @return bool
145
     */
146
    private function save(User $user, array $input)
147
    {
148
        if (isset($input['password']) && ! empty($input['password'])) {
149
            $user->password = Hash::make($input['password']);
150
        }
151
152
        if (! $user->save()) {
153
            return false;
154
        }
155
156
        return true;
157
    }
158
159
    /**
160
     * @param User $user
161
     *
162
     * @throws \Exception|\Throwable
163
     *
164
     * @return bool|null
165
     */
166
    public function destroy(User $user)
167
    {
168
        if (! $user->can_delete) {
169
            throw new GeneralException(__('exceptions.backend.users.first_user_cannot_be_destroyed'));
170
        }
171
172
        if (! $user->delete()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $user->delete() of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
173
            throw new GeneralException(__('exceptions.backend.users.delete'));
174
        }
175
176
        event(new UserDeleted($user));
177
178
        return true;
179
    }
180
181
    /**
182
     * @param User $user
183
     *
184
     * @throws Exception
185
     *
186
     * @return \Illuminate\Http\RedirectResponse
187
     */
188
    public function impersonate(User $user)
189
    {
190
        if ($user->is_super_admin) {
191
            throw new GeneralException(__('exceptions.backend.users.first_user_cannot_be_impersonated'));
192
        }
193
194
        $authenticatedUser = auth()->user();
195
196
        if ($authenticatedUser->id === $user->id
197
            || session()->get('admin_user_id') === $user->id
198
        ) {
199
            return redirect()->route('admin.home');
200
        }
201
202
        if (! session()->get('admin_user_id')) {
203
            session(['admin_user_id' => $authenticatedUser->id]);
204
            session(['admin_user_name' => $authenticatedUser->name]);
205
            session(['temp_user_id' => $user->id]);
206
        }
207
208
        //Login user
209
        auth()->loginUsingId($user->id);
210
211
        return redirect(home_route());
212
    }
213
214
    /**
215
     * @param array $ids
216
     *
217
     * @throws \Exception|\Throwable
218
     *
219
     * @return mixed
220
     */
221
    public function batchDestroy(array $ids)
222
    {
223
        DB::transaction(function () use ($ids) {
224
            // This wont call eloquent events, change to destroy if needed
225
            if ($this->query()->whereIn('id', $ids)->delete()) {
226
                return true;
227
            }
228
229
            throw new GeneralException(__('exceptions.backend.users.delete'));
230
        });
231
232
        return true;
233
    }
234
235
    /**
236
     * @param array $ids
237
     *
238
     * @throws \Exception|\Throwable
239
     *
240
     * @return mixed
241
     */
242
    public function batchEnable(array $ids)
243
    {
244
        DB::transaction(function () use ($ids) {
245
            if ($this->query()->whereIn('id', $ids)
246
                ->update(['active' => true])
247
            ) {
248
                return true;
249
            }
250
251
            throw new GeneralException(__('exceptions.backend.users.update'));
252
        });
253
254
        return true;
255
    }
256
257
    /**
258
     * @param array $ids
259
     *
260
     * @throws \Exception|\Throwable
261
     *
262
     * @return mixed
263
     */
264
    public function batchDisable(array $ids)
265
    {
266
        DB::transaction(function () use ($ids) {
267
            if ($this->query()->whereIn('id', $ids)
268
                ->update(['active' => false])
269
            ) {
270
                return true;
271
            }
272
273
            throw new GeneralException(__('exceptions.backend.users.update'));
274
        });
275
276
        return true;
277
    }
278
}
279