akaunting/app/Jobs/Auth/UpdateUser.php

100 lines
2.6 KiB
PHP
Raw Normal View History

2019-11-16 10:21:14 +03:00
<?php
namespace App\Jobs\Auth;
use App\Abstracts\Job;
2021-08-15 10:11:54 +03:00
use App\Events\Auth\UserUpdated;
use App\Events\Auth\UserUpdating;
2019-11-16 10:21:14 +03:00
use App\Models\Auth\User;
class UpdateUser extends Job
{
protected $user;
protected $request;
/**
* Create a new job instance.
*
* @param $user
* @param $request
*/
public function __construct($user, $request)
{
$this->user = $user;
$this->request = $this->getRequestInstance($request);
}
/**
* Execute the job.
*
* @return User
*/
public function handle()
{
$this->authorize();
// Do not reset password if not entered/changed
if (empty($this->request['password'])) {
unset($this->request['password']);
unset($this->request['password_confirmation']);
}
2021-08-15 10:11:54 +03:00
event(new UserUpdating($this->user, $this->request));
2020-06-26 13:40:19 +03:00
\DB::transaction(function () {
$this->user->update($this->request->input());
2019-11-16 10:21:14 +03:00
2020-06-26 13:40:19 +03:00
// Upload picture
if ($this->request->file('picture')) {
$media = $this->getMedia($this->request->file('picture'), 'users');
2019-11-16 10:21:14 +03:00
2020-06-26 13:40:19 +03:00
$this->user->attachMedia($media, 'picture');
}
2019-11-16 10:21:14 +03:00
2020-06-26 13:40:19 +03:00
if ($this->request->has('roles')) {
$this->user->roles()->sync($this->request->get('roles'));
}
2019-11-16 10:21:14 +03:00
2020-06-26 13:40:19 +03:00
if ($this->request->has('companies')) {
2021-05-15 10:00:14 +03:00
if (app()->runningInConsole() || request()->isInstall()) {
2021-05-15 11:10:04 +03:00
$this->user->companies()->sync($this->request->get('companies'));
2021-05-15 10:00:14 +03:00
} else {
$user = user();
$companies = $user->withoutEvents(function () use ($user) {
return $user->companies()->whereIn('id', $this->request->get('companies'))->pluck('id');
});
if ($companies->isNotEmpty()) {
$this->user->companies()->sync($companies->toArray());
}
2021-05-14 18:29:24 +03:00
}
2020-06-26 13:40:19 +03:00
}
2021-04-29 11:43:52 +03:00
if ($this->user->contact) {
$this->user->contact->update($this->request->input());
}
2020-06-26 13:40:19 +03:00
});
2019-11-16 10:21:14 +03:00
2021-08-15 10:11:54 +03:00
event(new UserUpdated($this->user, $this->request));
2019-11-16 10:21:14 +03:00
return $this->user;
}
/**
* Determine if this action is applicable.
*
* @return void
*/
public function authorize()
{
// Can't disable yourself
if (($this->request->get('enabled', 1) == 0) && ($this->user->id == user()->id)) {
$message = trans('auth.error.self_disable');
throw new \Exception($message);
}
}
}