refactor: with pint

This commit is contained in:
b1ek 2024-08-30 17:40:57 +10:00
parent 9922ebbc39
commit c67c96cf92
Signed by: blek
GPG Key ID: 14546221E3595D0C
23 changed files with 67 additions and 58 deletions

View File

@ -5,6 +5,8 @@ namespace App\Facade\Filters;
class Filter class Filter
{ {
public FilterTypeEnum $type; public FilterTypeEnum $type;
public string $column; public string $column;
public mixed $filter; public mixed $filter;
} }

View File

@ -2,11 +2,9 @@
namespace App\Facade\Filters; namespace App\Facade\Filters;
use App\Facade\Filters\Pagination; use Error;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Exceptions\HttpResponseException; use Illuminate\Http\Exceptions\HttpResponseException;
use Error;
use JsonMapper; use JsonMapper;
class Filters class Filters
@ -23,9 +21,9 @@ class Filters
public ?Pagination $pagination; public ?Pagination $pagination;
public static function fromArrayOrObject(array | object $data): Filters public static function fromArrayOrObject(array|object $data): Filters
{ {
$mapper = new JsonMapper(); $mapper = new JsonMapper;
if (is_array($data)) { if (is_array($data)) {
$data = json_decode(json_encode($data), false); $data = json_decode(json_encode($data), false);
} }
@ -37,7 +35,7 @@ class Filters
try { try {
return $mapper->map($data, \App\Facade\Filters\Filters::class); return $mapper->map($data, \App\Facade\Filters\Filters::class);
} catch (Error $err) { } catch (Error $err) {
throw new HttpResponseException(response()->json([ 'unknown' => $err->getMessage() ], 422)); throw new HttpResponseException(response()->json(['unknown' => $err->getMessage()], 422));
} }
} }
@ -61,7 +59,7 @@ class Filters
$builder->orderBy($order->by, $order->sort->value); $builder->orderBy($order->by, $order->sort->value);
} }
if (!is_null($this->pagination)) { if (! is_null($this->pagination)) {
$builder->paginate($this->pagination->size, ['*'], 'page', $this->pagination->page); $builder->paginate($this->pagination->size, ['*'], 'page', $this->pagination->page);
} }
} }

View File

@ -5,5 +5,6 @@ namespace App\Facade\Filters;
class Order class Order
{ {
public string $by; public string $by;
public OrderTypeEnum $sort; public OrderTypeEnum $sort;
} }

View File

@ -5,5 +5,6 @@ namespace App\Facade\Filters;
class Pagination class Pagination
{ {
public int $size; public int $size;
public int $page; public int $page;
} }

View File

@ -11,8 +11,7 @@ class PrivateUserController extends Controller
{ {
public function __construct( public function __construct(
private UserService $userService private UserService $userService
) { ) {}
}
public function list(AuthorizedRequest $request) public function list(AuthorizedRequest $request)
{ {
@ -22,6 +21,7 @@ class PrivateUserController extends Controller
public function listFilters(AuthorizedRequest $request) public function listFilters(AuthorizedRequest $request)
{ {
$filters = Filters::fromArrayOrObject($request->all()); $filters = Filters::fromArrayOrObject($request->all());
return $this->userService->listAll($filters); return $this->userService->listAll($filters);
} }

View File

@ -10,8 +10,7 @@ class PublicUserController extends Controller
{ {
public function __construct( public function __construct(
private UserService $userService private UserService $userService
) { ) {}
}
public function register(RegisterRequest $request) public function register(RegisterRequest $request)
{ {
@ -20,7 +19,7 @@ class PublicUserController extends Controller
public function login(LoginRequest $request) public function login(LoginRequest $request)
{ {
if (!$this->userService->login($request->all())) { if (! $this->userService->login($request->all())) {
return response() return response()
->json('bad_password', 400); ->json('bad_password', 400);
} }

View File

@ -2,7 +2,6 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Http\Requests\AuthorizedRequest;
use App\Http\Requests\TrashGroupRequest; use App\Http\Requests\TrashGroupRequest;
use App\Services\UserTrashService; use App\Services\UserTrashService;
@ -10,9 +9,7 @@ class TrashUserController extends Controller
{ {
public function __construct( public function __construct(
private UserTrashService $userTrashService private UserTrashService $userTrashService
) { ) {}
}
public function addMultiple(TrashGroupRequest $request) public function addMultiple(TrashGroupRequest $request)
{ {

View File

@ -3,7 +3,6 @@
namespace App\Http\Requests; namespace App\Http\Requests;
use App\Rules\ZxcvbnRule; use App\Rules\ZxcvbnRule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rules\Password; use Illuminate\Validation\Rules\Password;
class LoginRequest extends RestRequest class LoginRequest extends RestRequest
@ -25,7 +24,7 @@ class LoginRequest extends RestRequest
{ {
return [ return [
'email' => ['required', 'email'], 'email' => ['required', 'email'],
'password' => ['required', Password::min(1)->rules([ new ZxcvbnRule() ])], 'password' => ['required', Password::min(1)->rules([new ZxcvbnRule])],
]; ];
} }
} }

View File

@ -4,7 +4,6 @@ namespace App\Http\Requests;
use App\Models\User; use App\Models\User;
use App\Rules\ZxcvbnRule; use App\Rules\ZxcvbnRule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rules\Password; use Illuminate\Validation\Rules\Password;
class RegisterRequest extends RestRequest class RegisterRequest extends RestRequest
@ -29,8 +28,8 @@ class RegisterRequest extends RestRequest
'name' => ['required', 'string'], 'name' => ['required', 'string'],
'middle_name' => ['required', 'string'], 'middle_name' => ['required', 'string'],
'email' => ['required', 'email'], 'email' => ['required', 'email'],
'phone' => ['required', 'regex:' . User::PHONE_REGEX ], 'phone' => ['required', 'regex:'.User::PHONE_REGEX],
'password' => ['required', Password::min(1)->rules([ new ZxcvbnRule() ])], 'password' => ['required', Password::min(1)->rules([new ZxcvbnRule])],
]; ];
} }
} }

View File

@ -10,14 +10,15 @@ class TrashGroupRequest extends AuthorizedRequest
{ {
$ids = explode(',', $this->query('ids')); $ids = explode(',', $this->query('ids'));
$validator = validator([ $validator = validator([
'ids' => $ids 'ids' => $ids,
], [ ], [
'ids' => 'required|array|min:1', 'ids' => 'required|array|min:1',
'ids.*' => 'required|uuid|distinct' 'ids.*' => 'required|uuid|distinct',
]); ]);
if ($validator->fails()) { if ($validator->fails()) {
throw new HttpResponseException(response()->json($validator->errors(), 422)); throw new HttpResponseException(response()->json($validator->errors(), 422));
} }
return $ids; return $ids;
} }
} }

View File

@ -4,7 +4,6 @@ namespace App\Http\Requests;
use App\Models\User; use App\Models\User;
use App\Rules\ZxcvbnRule; use App\Rules\ZxcvbnRule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rules\Password; use Illuminate\Validation\Rules\Password;
class UserEditRequest extends AuthorizedRequest class UserEditRequest extends AuthorizedRequest
@ -17,13 +16,13 @@ class UserEditRequest extends AuthorizedRequest
public function rules(): array public function rules(): array
{ {
return [ return [
'user.last_name' => [ 'string' ], 'user.last_name' => ['string'],
'user.name' => [ 'string' ], 'user.name' => ['string'],
'user.middle_name' => [ 'string' ], 'user.middle_name' => ['string'],
'user.email' => [ 'email' ], 'user.email' => ['email'],
'user.phone' => [ 'string', 'regex:' . User::PHONE_REGEX ], 'user.phone' => ['string', 'regex:'.User::PHONE_REGEX],
'user' => 'required', 'user' => 'required',
'password' => [ Password::min(1)->rules([ new ZxcvbnRule() ]) ], 'password' => [Password::min(1)->rules([new ZxcvbnRule])],
'user.email_verified_at' => 'prohibited', 'user.email_verified_at' => 'prohibited',
'user.created_at' => 'prohibited', 'user.created_at' => 'prohibited',

View File

@ -12,9 +12,9 @@ use Illuminate\Notifications\Notifiable;
class User extends Authenticatable class User extends Authenticatable
{ {
use HasFactory; use HasFactory;
use HasHistory;
use Notifiable; use Notifiable;
use UuidId; use UuidId;
use HasHistory;
public const PHONE_REGEX = '/^\+\d+$/'; public const PHONE_REGEX = '/^\+\d+$/';

View File

@ -16,7 +16,7 @@ class ZxcvbnRule implements ValidationRule
public function validate(string $attribute, mixed $value, Closure $fail): void public function validate(string $attribute, mixed $value, Closure $fail): void
{ {
$value = (string) $value; $value = (string) $value;
$zxcvbn = new Zxcvbn(); $zxcvbn = new Zxcvbn;
if ($zxcvbn->passwordStrength($value)['score'] < 3) { if ($zxcvbn->passwordStrength($value)['score'] < 3) {
$fail('Password is not secure enough!'); $fail('Password is not secure enough!');
} }

View File

@ -12,12 +12,12 @@ class UserService
{ {
/** /**
* Create(register) new user * Create(register) new user
* @param array $data This is expected to be validated already *
* @return User * @param array $data This is expected to be validated already
*/ */
public function create($data, $autoLogin = true): User public function create($data, $autoLogin = true): User
{ {
if (User::where([ 'email' => $data['email'] ])->count() !== 0) { if (User::where(['email' => $data['email']])->count() !== 0) {
throw new HttpResponseException(response()->json('email_taken', 400)); throw new HttpResponseException(response()->json('email_taken', 400));
} }
@ -27,26 +27,30 @@ class UserService
if ($autoLogin) { if ($autoLogin) {
Auth::login($user); Auth::login($user);
} }
return $user; return $user;
} }
/** /**
* Login to user * Login to user
* @param array $data This is expected to be validated already *
* @param array $data This is expected to be validated already
* @return User * @return User
*/ */
public function login($data): bool public function login($data): bool
{ {
if (Auth::attempt($data)) { if (Auth::attempt($data)) {
request()->session()->regenerate(); request()->session()->regenerate();
return true; return true;
} }
return false; return false;
} }
public function setPassword($data) public function setPassword($data)
{ {
$user = User::where([ 'email' => $data['email'] ])->first(); $user = User::where(['email' => $data['email']])->first();
if ($user === null) { if ($user === null) {
return; return;
} }
@ -62,18 +66,19 @@ class UserService
} }
$builder = User::query(); $builder = User::query();
$filters->apply($builder); $filters->apply($builder);
return $builder->get()->toArray(); return $builder->get()->toArray();
} }
public function getOneById(string $id): User | null public function getOneById(string $id): ?User
{ {
return User::where([ 'id' => $id ])->first(); return User::where(['id' => $id])->first();
} }
/** /**
* Will return `null` if failed * Will return `null` if failed
*/ */
public function editUser(array $data, string $id): User | null public function editUser(array $data, string $id): ?User
{ {
$user = $this->getOneById($id); $user = $this->getOneById($id);
if ($user === null) { if ($user === null) {
@ -81,15 +86,16 @@ class UserService
} }
if (array_key_exists('password', $data)) { if (array_key_exists('password', $data)) {
$this->setPassword([ 'email' => $user['email'], 'password' => $data['password'] ]); $this->setPassword(['email' => $user['email'], 'password' => $data['password']]);
} }
$user->fill($data['user']); $user->fill($data['user']);
$user->save(); $user->save();
return $user; return $user;
} }
public function getUnexistingIds(array $ids): null | array public function getUnexistingIds(array $ids): ?array
{ {
$users = User::whereIn('id', $ids)->get(); $users = User::whereIn('id', $ids)->get();
if ($users->count() != count($ids)) { if ($users->count() != count($ids)) {
@ -98,8 +104,10 @@ class UserService
return $model->id; return $model->id;
} }
)->toArray(); )->toArray();
return array_diff($ids, $existingIds); return array_diff($ids, $existingIds);
} }
return null; return null;
} }
} }

View File

@ -8,31 +8,29 @@ class UserTrashService
{ {
public function __construct( public function __construct(
private UserService $userService private UserService $userService
) { ) {}
} public function moveUsersToTrash(array $ids): bool|array
public function moveUsersToTrash(array $ids): bool | array
{ {
$unexisting = $this->userService->getUnexistingIds($ids); $unexisting = $this->userService->getUnexistingIds($ids);
if (is_array($unexisting)) { if (is_array($unexisting)) {
return $unexisting; return $unexisting;
} }
return User::whereIn('id', $ids)->update([ 'deleted_at' => now()->toDateTimeImmutable() ]); return User::whereIn('id', $ids)->update(['deleted_at' => now()->toDateTimeImmutable()]);
} }
public function moveUsersFromTrash(array $ids): bool | array public function moveUsersFromTrash(array $ids): bool|array
{ {
$unexisting = $this->userService->getUnexistingIds($ids); $unexisting = $this->userService->getUnexistingIds($ids);
if (is_array($unexisting)) { if (is_array($unexisting)) {
return $unexisting; return $unexisting;
} }
return User::whereIn('id', $ids)->update([ 'deleted_at' => null ]); return User::whereIn('id', $ids)->update(['deleted_at' => null]);
} }
public function cleanUsersFromTrash(array $ids): bool | null | array public function cleanUsersFromTrash(array $ids): bool|null|array
{ {
$unexisting = $this->userService->getUnexistingIds($ids); $unexisting = $this->userService->getUnexistingIds($ids);
if (is_array($unexisting)) { if (is_array($unexisting)) {

View File

@ -13,10 +13,12 @@ trait UuidId
$model->id = Uuid::uuid6()->toString(); $model->id = Uuid::uuid6()->toString();
}); });
} }
public function getIncrementing(): bool public function getIncrementing(): bool
{ {
return false; return false;
} }
public function getKeyType(): string public function getKeyType(): string
{ {
return 'string'; return 'string';

View File

@ -12,7 +12,7 @@ return Application::configure(basePath: dirname(__DIR__))
) )
->withMiddleware(function (Middleware $middleware) { ->withMiddleware(function (Middleware $middleware) {
// https://upload.wikimedia.org/wikipedia/commons/thumb/8/8a/Axillary_Crutches.jpg/90px-Axillary_Crutches.jpg // https://upload.wikimedia.org/wikipedia/commons/thumb/8/8a/Axillary_Crutches.jpg/90px-Axillary_Crutches.jpg
$middleware->validateCsrfTokens([ '*' ]); $middleware->validateCsrfTokens(['*']);
}) })
->withExceptions(function (Exceptions $exceptions) { ->withExceptions(function (Exceptions $exceptions) {
// //

View File

@ -30,7 +30,7 @@ class UserFactory extends Factory
'phone' => fake()->unique()->phoneNumber, 'phone' => fake()->unique()->phoneNumber,
'email' => fake()->unique()->safeEmail, 'email' => fake()->unique()->safeEmail,
'password' => Hash::make('password'), 'password' => Hash::make('password'),
'remember_token' => Str::random() 'remember_token' => Str::random(),
]; ];
} }

View File

@ -5,7 +5,8 @@ use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Builder; use Illuminate\Database\Schema\Builder;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
return new class () extends Migration { return new class extends Migration
{
/** /**
* Run the migrations. * Run the migrations.
*/ */

View File

@ -4,7 +4,8 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
return new class () extends Migration { return new class extends Migration
{
/** /**
* Run the migrations. * Run the migrations.
*/ */

View File

@ -4,7 +4,8 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
return new class () extends Migration { return new class extends Migration
{
/** /**
* Run the migrations. * Run the migrations.
*/ */

View File

@ -4,7 +4,8 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
return new class () extends Migration { return new class extends Migration
{
/** /**
* Run the migrations. * Run the migrations.
*/ */
@ -16,7 +17,7 @@ return new class () extends Migration {
$table->string('model_name', 250); $table->string('model_name', 250);
$table->jsonb('before'); $table->jsonb('before');
$table->jsonb('after'); $table->jsonb('after');
$table->enum('action', [ 'insert', 'update', 'delete' ]); $table->enum('action', ['insert', 'update', 'delete']);
$table->timestamps(); $table->timestamps();
}); });
} }

View File

@ -4,7 +4,8 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
return new class () extends Migration { return new class extends Migration
{
/** /**
* Run the migrations. * Run the migrations.
*/ */