phpvms/app/Services/UserService.php

95 lines
2.0 KiB
PHP
Raw Normal View History

<?php
namespace App\Services;
2017-12-03 00:55:17 +08:00
use App\Events\UserRegistered;
use App\Facades\Utils;
use App\Models\Enums\PilotState;
use App\Models\User;
use App\Models\Rank;
2017-08-12 09:51:55 +08:00
use App\Models\Role;
2017-12-03 00:55:17 +08:00
use App\Events\UserStateChanged;
use Illuminate\Support\Facades\Cache;
2017-08-12 09:51:55 +08:00
use Illuminate\Support\Facades\Hash;
2017-12-13 04:48:03 +08:00
class UserService extends BaseService
{
2017-12-15 13:51:57 +08:00
/**
* Register a pilot
* @param User $user
2017-12-15 13:51:57 +08:00
* @return mixed
*/
public function createPilot(User $user)
2017-12-15 13:51:57 +08:00
{
# Determine if we want to auto accept
/*if(setting('pilot.auto_accept') === true) {
$user->state = PilotState::ACTIVE;
2017-12-15 13:51:57 +08:00
} else {
$user->state = PilotState::PENDING;
}*/
2017-12-15 13:51:57 +08:00
$user->save();
2017-12-15 13:51:57 +08:00
# Attach the user roles
$role = Role::where('name', 'user')->first();
$user->attachRole($role);
# Let's check their rank
$this->calculatePilotRank($user);
$user->refresh();
2017-12-15 13:51:57 +08:00
event(new UserRegistered($user));
return $user;
}
public function adjustFlightCount(User $user, int $count): User
{
$user->refresh();
$user->flights += $count;
$user->save();
event(new UserStateChanged($user));
2017-12-03 00:55:17 +08:00
return $user;
}
public function adjustFlightTime(User $user, int $minutes): User
{
$user->refresh();
$user->flight_time += $minutes;
$user->save();
event(new UserStateChanged($user));
2017-12-03 00:55:17 +08:00
return $user;
}
public function calculatePilotRank(User $user): User
{
$user->refresh();
$pilot_hours = Utils::minutesToHours($user->flight_time);
# TODO: Cache
$ranks = Rank::where('auto_promote', true)->orderBy('hours', 'asc')->get();
foreach ($ranks as $rank) {
if($rank->hours > $pilot_hours) {
break;
} else {
$user->rank_id = $rank->id;
}
}
$user->save();
event(new UserStateChanged($user));
2017-12-03 00:55:17 +08:00
return $user;
}
}