From 299d409298bd93a18dba3f2610fb4de1fa29bffb Mon Sep 17 00:00:00 2001 From: gabriel Date: Mon, 3 Jun 2024 22:39:23 -0300 Subject: [PATCH] =?UTF-8?q?refactor:=20melhora=20tacada=20de=20exce=C3=A7?= =?UTF-8?q?=C3=B5es=20para=20m=C3=B3dulo=20de=20usu=C3=A1rios?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../InvalidCredentialsException.php | 24 +++++++++ .../UniqueConstraintExistsException.php | 24 +++++++++ app/Http/Controllers/UserController.php | 52 +++++++++++++++---- app/Http/Services/TransferenceService.php | 16 ++++-- app/Http/Services/UserService.php | 37 +++++++------ 5 files changed, 119 insertions(+), 34 deletions(-) create mode 100644 app/Exceptions/InvalidCredentialsException.php create mode 100644 app/Exceptions/UniqueConstraintExistsException.php diff --git a/app/Exceptions/InvalidCredentialsException.php b/app/Exceptions/InvalidCredentialsException.php new file mode 100644 index 0000000..2af9e96 --- /dev/null +++ b/app/Exceptions/InvalidCredentialsException.php @@ -0,0 +1,24 @@ +json($this->userService->login($request)); - } catch (\Throwable $th) { - throw $th; - } - } + } catch (\Exception $ex) { + if (method_exists($ex, 'render')) { + return $ex->render($request); + } - public function logout() - { - return $this->userService->logout(); + Log::error($ex); + + return response([ + 'error' => [ + 'httpCode' => ResponseAlias::HTTP_INTERNAL_SERVER_ERROR, + 'message' => 'Erro de servidor', + ], + ], ResponseAlias::HTTP_INTERNAL_SERVER_ERROR); + } } public function registerCommonUser(UserRegister $request) { try { return response()->json($this->userService->registerCommonUser($request)); - } catch (\Throwable $th) { - throw $th; + } catch (\Exception $ex) { + if (method_exists($ex, 'render')) { + return $ex->render($request); + } + + Log::error($ex); + + return response([ + 'error' => [ + 'httpCode' => ResponseAlias::HTTP_INTERNAL_SERVER_ERROR, + 'message' => 'Erro de servidor', + ], + ], ResponseAlias::HTTP_INTERNAL_SERVER_ERROR); } } @@ -41,8 +60,19 @@ public function registerStoreKeeper(UserRegisterStoreKeeper $request) { try { return response()->json($this->userService->registerStoreKeeper($request)); - } catch (\Throwable $th) { - throw $th; + } catch (\Exception $ex) { + if (method_exists($ex, 'render')) { + return $ex->render($request); + } + + Log::error($ex); + + return response([ + 'error' => [ + 'httpCode' => ResponseAlias::HTTP_INTERNAL_SERVER_ERROR, + 'message' => 'Erro de servidor', + ], + ], ResponseAlias::HTTP_INTERNAL_SERVER_ERROR); } } } diff --git a/app/Http/Services/TransferenceService.php b/app/Http/Services/TransferenceService.php index 03cefcb..ba5bd6d 100644 --- a/app/Http/Services/TransferenceService.php +++ b/app/Http/Services/TransferenceService.php @@ -17,7 +17,7 @@ class TransferenceService { public function __construct( - public Wallet $walletModel, + public Wallet $walletModel, public AntiFraudInterface $antiFraud, ) { } @@ -36,7 +36,7 @@ public function transfer(Transfer $request): TranseferenceResource $payeeWallet = $this->walletModel::with('user')->where('user_id', $request['payee'])->sharedLock()->first(); $payerWallet = $this->walletModel::with('user')->where('user_id', $request['payer'])->sharedLock()->first(); - if (!$payeeWallet) { + if (! $payeeWallet) { throw new PayeeNotFoundException(['payee' => $request['payee']]); } @@ -51,7 +51,12 @@ public function transfer(Transfer $request): TranseferenceResource return new TranseferenceResource($transferenceWithAgents); } - private function firstChecks(Transfer $request) + /** + * @throws AntiFraudException + * @throws TransferToYourSelfException + * @throws TransferActingAsAnotherUserException + */ + private function firstChecks(Transfer $request): void { if ($request['payer'] != auth()->id()) { throw new TransferActingAsAnotherUserException([]); @@ -61,11 +66,14 @@ private function firstChecks(Transfer $request) throw new TransferToYourSelfException([]); } - if (!$this->antiFraud->authorize()) { + if (! $this->antiFraud->authorize()) { throw new AntiFraudException([]); } } + /** + * @throws NoBalanceException + */ private function checkPayerBalance(Wallet $payerWallet, int $transferenceAmount) { if ($payerWallet->balance < $transferenceAmount) { diff --git a/app/Http/Services/UserService.php b/app/Http/Services/UserService.php index 43e3ae4..58c3861 100644 --- a/app/Http/Services/UserService.php +++ b/app/Http/Services/UserService.php @@ -2,6 +2,8 @@ namespace App\Http\Services; +use App\Exceptions\InvalidCredentialsException; +use App\Exceptions\UniqueConstraintExistsException; use App\Http\Requests\UserAuthRequest; use App\Http\Requests\UserRegister; use App\Http\Requests\UserRegisterStoreKeeper; @@ -11,41 +13,38 @@ class UserService { - public function login(UserAuthRequest $request) + public function login(UserAuthRequest $request): \Illuminate\Http\JsonResponse|array { $loginUserData = $request; $user = User::where('email', $loginUserData['email'])->first(); - if (!$user || !Hash::check($loginUserData['password'], $user->password)) { - return response()->json([ - 'message' => 'Credenciais inválidas.' - ], 401); + if (! $user || ! Hash::check($loginUserData['password'], $user->password)) { + throw new InvalidCredentialsException([]); } - $token = $user->createToken($user->name . '-AuthToken')->plainTextToken; + $token = $user->createToken($user->name.'-AuthToken')->plainTextToken; + return [ 'access_token' => $token, ]; } - public function logout() - { - return 'logout'; - } - - private function commonUserParamsExistenceChecks(UserRegister $request) + private function commonUserParamsExistenceChecks(UserRegister $request): void { if (User::where('cpf', $request['cpf'])->exists()) { - throw new Exception('Já existe um usuário cadastrado com esse CPF'); + throw new UniqueConstraintExistsException('Já existe um usuário cadastrado com esse CPF', []); } if (User::where('email', $request['email'])->exists()) { - throw new Exception('Já existe um usuário cadastrado com esse E-mail'); + throw new UniqueConstraintExistsException('Já existe um usuário cadastrado com esse E-mail', []); } } - public function registerCommonUser(UserRegister $request) + /** + * @throws Exception + */ + public function registerCommonUser(UserRegister $request): array { $this->commonUserParamsExistenceChecks($request); @@ -57,16 +56,16 @@ public function registerCommonUser(UserRegister $request) ])->assignRole('common-user'); return [ - 'Usuário cadastrado com sucesso!' + 'Usuário cadastrado com sucesso!', ]; } - public function registerStoreKeeper(UserRegisterStoreKeeper $request) + public function registerStoreKeeper(UserRegisterStoreKeeper $request): array { $this->commonUserParamsExistenceChecks($request); if (User::where('cnpj', $request['cnpj'])->exists()) { - throw new Exception('Já existe um usuário cadastrado com esse CNPJ'); + throw new UniqueConstraintExistsException('Já existe um usuário cadastrado com esse CNPJ', []); } User::create([ @@ -78,7 +77,7 @@ public function registerStoreKeeper(UserRegisterStoreKeeper $request) ])->assignRole('store-keeper'); return [ - 'Usuário cadastrado com sucesso!' + 'Usuário cadastrado com sucesso!', ]; } }