Completed
Pull Request — dev (#235)
by Alies
07:06
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\UserRepository;
17
use Mcamara\LaravelLocalization\LaravelLocalization;
18
19
/**
20
 * Class EloquentUserRepository.
21
 */
22
class EloquentUserRepository extends EloquentBaseRepository implements UserRepository
23
{
24
    /**
25
     * @var \Mcamara\LaravelLocalization\LaravelLocalization
26
     */
27
    protected $localization;
28
29
    /**
30
     * @var \Illuminate\Contracts\Config\Repository
31
     */
32
    protected $config;
33
34
    /**
35
     * EloquentUserRepository constructor.
36
     *
37
     * @param User                                             $user
38
     * @param \Mcamara\LaravelLocalization\LaravelLocalization $localization
39
     * @param \Illuminate\Contracts\Config\Repository          $config
40
     */
41
    public function __construct(
42
        User $user,
43
        LaravelLocalization $localization,
44
        Repository $config
45
    ) {
46
        parent::__construct($user);
47
        $this->localization = $localization;
48
        $this->config = $config;
49
    }
50
51
    /**
52
     * @param string $slug
53
     *
54
     * @return User
55
     */
56
    public function findBySlug($slug)
57
    {
58
        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...
59
    }
60
61
    /**
62
     * @param array $input
63
     * @param bool  $confirmed
64
     *
65
     * @throws \App\Exceptions\GeneralException
66
     *
67
     * @return \App\Models\User
68
     */
69
    public function store(array $input, $confirmed = false)
70
    {
71
        /** @var User $user */
72
        $user = $this->make(Arr::only($input, ['name', 'email', 'active']));
73
74
        if (isset($input['password'])) {
75
            $user->password = Hash::make($input['password']);
76
        }
77
78
        if ($confirmed) {
79
            $user->email_verified_at = Carbon::now();
80
        }
81
82
        if (empty($user->locale)) {
83
            $user->locale = $this->localization->getDefaultLocale();
84
        }
85
86
        if (empty($user->timezone)) {
87
            $user->timezone = $this->config->get('app.timezone');
88
        }
89
90
        if (! $this->save($user, $input)) {
91
            throw new GeneralException(__('exceptions.backend.users.create'));
92
        }
93
94
        event(new UserCreated($user));
95
96
        return $user;
97
    }
98
99
    /**
100
     * @param User  $user
101
     * @param array $input
102
     *
103
     * @throws Exception
104
     * @throws \Exception|\Throwable
105
     *
106
     * @return \App\Models\User
107
     */
108
    public function update(User $user, array $input)
109
    {
110
        if (! $user->can_edit) {
111
            throw new GeneralException(__('exceptions.backend.users.first_user_cannot_be_edited'));
112
        }
113
114
        $user->fill(Arr::except($input, 'password'));
115
116
        if ($user->is_super_admin && ! $user->active) {
117
            throw new GeneralException(__('exceptions.backend.users.first_user_cannot_be_disabled'));
118
        }
119
120
        if (! $this->save($user, $input)) {
121
            throw new GeneralException(__('exceptions.backend.users.update'));
122
        }
123
124
        event(new UserUpdated($user));
125
126
        return $user;
127
    }
128
129
    /**
130
     * @param \App\Models\User $user
131
     * @param array            $input
132
     *
133
     * @throws \App\Exceptions\GeneralException
134
     *
135
     * @return bool
136
     */
137
    private function save(User $user, array $input)
138
    {
139
        if (isset($input['password']) && ! empty($input['password'])) {
140
            $user->password = Hash::make($input['password']);
141
        }
142
143
        if (! $user->save()) {
144
            return false;
145
        }
146
147
        return true;
148
    }
149
150
    /**
151
     * @param User $user
152
     *
153
     * @throws \Exception|\Throwable
154
     *
155
     * @return bool|null
156
     */
157
    public function destroy(User $user)
158
    {
159
        if (! $user->can_delete) {
160
            throw new GeneralException(__('exceptions.backend.users.first_user_cannot_be_destroyed'));
161
        }
162
163
        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...
164
            throw new GeneralException(__('exceptions.backend.users.delete'));
165
        }
166
167
        event(new UserDeleted($user));
168
169
        return true;
170
    }
171
172
    /**
173
     * @param User $user
174
     *
175
     * @throws Exception
176
     *
177
     * @return \Illuminate\Http\RedirectResponse
178
     */
179
    public function impersonate(User $user)
180
    {
181
        if ($user->is_super_admin) {
182
            throw new GeneralException(__('exceptions.backend.users.first_user_cannot_be_impersonated'));
183
        }
184
185
        $authenticatedUser = auth()->user();
186
187
        if ($authenticatedUser->id === $user->id
188
            || session()->get('admin_user_id') === $user->id
189
        ) {
190
            return redirect()->route('admin.home');
191
        }
192
193
        if (! session()->get('admin_user_id')) {
194
            session(['admin_user_id' => $authenticatedUser->id]);
195
            session(['admin_user_name' => $authenticatedUser->name]);
196
            session(['temp_user_id' => $user->id]);
197
        }
198
199
        //Login user
200
        auth()->loginUsingId($user->id);
201
202
        return redirect(home_route());
203
    }
204
205
    /**
206
     * @param array $ids
207
     *
208
     * @throws \Exception|\Throwable
209
     *
210
     * @return mixed
211
     */
212
    public function batchDestroy(array $ids)
213
    {
214
        DB::transaction(function () use ($ids) {
215
            // This wont call eloquent events, change to destroy if needed
216
            if ($this->query()->whereIn('id', $ids)->delete()) {
217
                return true;
218
            }
219
220
            throw new GeneralException(__('exceptions.backend.users.delete'));
221
        });
222
223
        return true;
224
    }
225
226
    /**
227
     * @param array $ids
228
     *
229
     * @throws \Exception|\Throwable
230
     *
231
     * @return mixed
232
     */
233
    public function batchEnable(array $ids)
234
    {
235
        DB::transaction(function () use ($ids) {
236
            if ($this->query()->whereIn('id', $ids)
237
                ->update(['active' => true])
238
            ) {
239
                return true;
240
            }
241
242
            throw new GeneralException(__('exceptions.backend.users.update'));
243
        });
244
245
        return true;
246
    }
247
248
    /**
249
     * @param array $ids
250
     *
251
     * @throws \Exception|\Throwable
252
     *
253
     * @return mixed
254
     */
255
    public function batchDisable(array $ids)
256
    {
257
        DB::transaction(function () use ($ids) {
258
            if ($this->query()->whereIn('id', $ids)
259
                ->update(['active' => false])
260
            ) {
261
                return true;
262
            }
263
264
            throw new GeneralException(__('exceptions.backend.users.update'));
265
        });
266
267
        return true;
268
    }
269
}
270