Files
nexusphp/app/Repositories/UserRepository.php

100 lines
3.0 KiB
PHP
Raw Normal View History

2021-04-17 19:01:33 +08:00
<?php
namespace App\Repositories;
2021-04-27 19:13:32 +08:00
use App\Http\Resources\ExamUserResource;
use App\Http\Resources\UserResource;
use App\Models\ExamUser;
2021-04-17 19:01:33 +08:00
use App\Models\Setting;
use App\Models\User;
2021-05-12 13:45:00 +08:00
use Illuminate\Database\Eloquent\Builder;
2021-04-17 19:01:33 +08:00
class UserRepository extends BaseRepository
{
public function getList(array $params)
{
$query = User::query();
list($sortField, $sortType) = $this->getSortFieldAndType($params);
$query->orderBy($sortField, $sortType);
return $query->paginate();
}
2021-04-23 01:28:41 +08:00
public function getBase($id)
{
$user = User::query()->findOrFail($id, ['id', 'username', 'email', 'avatar']);
return $user;
}
2021-04-27 19:13:32 +08:00
public function getDetail($id)
{
2021-05-12 13:45:00 +08:00
$with = [
2021-05-13 21:31:09 +08:00
'inviter' => function ($query) {return $query->select(User::$commonFields);}
2021-05-12 13:45:00 +08:00
];
$user = User::query()->with($with)->findOrFail($id, User::$commonFields);
2021-04-27 19:13:32 +08:00
$userResource = new UserResource($user);
$baseInfo = $userResource->response()->getData(true)['data'];
$examRep = new ExamRepository();
$examProgress = $examRep->getUserExamProgress($id, ExamUser::STATUS_NORMAL, ['exam']);
if ($examProgress) {
$examResource = new ExamUserResource($examProgress);
$examInfo = $examResource->response()->getData(true)['data'];
} else {
$examInfo = null;
}
return [
'base_info' => $baseInfo,
'exam_info' => $examInfo,
];
}
2021-04-17 19:01:33 +08:00
public function store(array $params)
{
$password = $params['password'];
if ($password != $params['password_confirmation']) {
throw new \InvalidArgumentException("password confirmation != password");
}
$setting = Setting::get('main');
$secret = mksecret();
$passhash = md5($secret . $password . $secret);
$data = [
'username' => $params['username'],
'email' => $params['email'],
'secret' => $secret,
'editsecret' => '',
'passhash' => $passhash,
'stylesheet' => $setting['defstylesheet'],
'added' => now()->toDateTimeString(),
'status' => User::STATUS_CONFIRMED,
];
$user = User::query()->create($data);
return $user;
}
public function resetPassword($username, $password, $passwordConfirmation)
{
if ($password != $passwordConfirmation) {
throw new \InvalidArgumentException("password confirmation != password");
}
2021-05-08 18:27:35 +08:00
$user = User::query()->where('username', $username)->firstOrFail(['id', 'username']);
2021-04-17 19:01:33 +08:00
$secret = mksecret();
$passhash = md5($secret . $password . $secret);
$update = [
'secret' => $secret,
'passhash' => $passhash,
];
$user->update($update);
return $user;
}
2021-04-19 20:13:21 +08:00
public function listClass()
{
$out = [];
foreach(User::$classes as $key => $value) {
$out[(string)$key] = $value['text'];
}
return $out;
}
2021-04-17 19:01:33 +08:00
}