Skip to content

Commit

Permalink
refactor: melhora tacada de exceções para módulo de usuários
Browse files Browse the repository at this point in the history
  • Loading branch information
Gabrielcefetzada committed Jun 4, 2024
1 parent 5200695 commit 299d409
Show file tree
Hide file tree
Showing 5 changed files with 119 additions and 34 deletions.
24 changes: 24 additions & 0 deletions app/Exceptions/InvalidCredentialsException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

namespace App\Exceptions;

use Symfony\Component\HttpFoundation\Response as ResponseAlias;

class InvalidCredentialsException extends AbstractException
{
public function __construct(
array $contextualData,
?int $code = ResponseAlias::HTTP_BAD_REQUEST,
) {
$message = 'Credenciais inválidas';
$debugMessage = "Credenciais inválidas ao logar";
$type = 'InvalidCredentialsException';
parent::__construct(
$type,
$contextualData,
$message,
$debugMessage,
$code,
);
}
}
24 changes: 24 additions & 0 deletions app/Exceptions/UniqueConstraintExistsException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

namespace App\Exceptions;

use Symfony\Component\HttpFoundation\Response as ResponseAlias;

class UniqueConstraintExistsException extends AbstractException
{
public function __construct(
string $message,
array $contextualData,
?int $code = ResponseAlias::HTTP_UNPROCESSABLE_ENTITY,
) {
$debugMessage = $message;
$type = 'PayeeNotFoundException';
parent::__construct(
$type,
$contextualData,
$message,
$debugMessage,
$code,
);
}
}
52 changes: 41 additions & 11 deletions app/Http/Controllers/UserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
use App\Http\Requests\UserRegister;
use App\Http\Requests\UserRegisterStoreKeeper;
use App\Http\Services\UserService;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response as ResponseAlias;

class UserController
{
Expand All @@ -18,31 +20,59 @@ public function login(UserAuthRequest $request)
{
try {
return response()->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);
}
}

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);
}
}
}
16 changes: 12 additions & 4 deletions app/Http/Services/TransferenceService.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
class TransferenceService
{
public function __construct(
public Wallet $walletModel,
public Wallet $walletModel,
public AntiFraudInterface $antiFraud,
) {
}
Expand All @@ -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']]);
}

Expand All @@ -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([]);
Expand All @@ -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) {
Expand Down
37 changes: 18 additions & 19 deletions app/Http/Services/UserService.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);

Expand All @@ -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([
Expand All @@ -78,7 +77,7 @@ public function registerStoreKeeper(UserRegisterStoreKeeper $request)
])->assignRole('store-keeper');

return [
'Usuário cadastrado com sucesso!'
'Usuário cadastrado com sucesso!',
];
}
}

0 comments on commit 299d409

Please sign in to comment.