Passed
Push — feature/optimize ( 06281d )
by Fu
03:39
created

Handler::render()   C

Complexity

Conditions 16
Paths 19

Size

Total Lines 71
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 49
dl 0
loc 71
rs 5.5666
c 0
b 0
f 0
cc 16
nc 19
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Modules\Core\Supports;
4
5
use Exception;
6
use Illuminate\Database\Eloquent\ModelNotFoundException;
7
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
8
use Modules\Core\Enums\StatusCodeEnum;
9
use Modules\Core\ErrorCodes\JWTErrorCode;
10
use Symfony\Component\HttpKernel\Exception\{
11
    HttpException, UnauthorizedHttpException
12
};
13
use Tymon\JWTAuth\Exceptions\{
14
    InvalidClaimException,
15
    JWTException,
16
    PayloadException,
17
    TokenBlacklistedException,
18
    TokenExpiredException,
19
    TokenInvalidException,
20
    UserNotDefinedException
21
};
22
23
class Handler extends ExceptionHandler
24
{
25
    const STATUS_CODE = 'status_code';
26
    const ERROR_CODE = 'error_code';
27
    const MESSAGE = 'message';
28
    const DEBUG = 'debug';
29
30
    /**
31
     * Render an exception into an HTTP response.
32
     *
33
     * @param \Illuminate\Http\Request $request
34
     * @param \Exception|HttpException $exception
35
     *
36
     * @return \Illuminate\Http\Response|\Symfony\Component\HttpFoundation\Response
37
     */
38
    public function render($request, Exception $exception)
39
    {
40
        if ($request->is('api/*') || $request->wantsJson()) {
41
            if ('web' !== config('core.api.error_format')) {
42
                $response = [];
43
                $exceptionClass = get_class($exception);
44
                $exception = $this->overwrite($exception);
45
46
                if ($exception instanceof ModelNotFoundException) {
47
                    $response['meta'][self::STATUS_CODE] = StatusCodeEnum::HTTP_NOT_FOUND;
48
                    $response['meta'][self::MESSAGE] = $exception->getMessage();
49
                } elseif ($exception instanceof JWTException) {
50
                    switch ($exceptionClass) {
51
                        case InvalidClaimException::class:
52
                            $response['meta'][self::ERROR_CODE] = JWTErrorCode::INVALID_CLAIM;
53
                            break;
54
55
                        case PayloadException::class:
56
                            $response['meta'][self::ERROR_CODE] = JWTErrorCode::PAYLOAD;
57
                            break;
58
59
                        case TokenBlacklistedException::class:
60
                            $response['meta'][self::ERROR_CODE] = JWTErrorCode::TOKEN_BLACKLISTED;
61
                            break;
62
63
                        case TokenExpiredException::class:
64
                            if ('Token has expired and can no longer be refreshed' === $exception->getMessage()) {
65
                                $response['meta'][self::ERROR_CODE] = JWTErrorCode::CAN_NOT_REFRESHED;
66
                            } else {
67
                                $response['meta'][self::ERROR_CODE] = JWTErrorCode::TOKEN_EXPIRED;
68
                            }
69
                            break;
70
71
                        case TokenInvalidException::class:
72
                            $response['meta'][self::ERROR_CODE] = JWTErrorCode::TOKEN_INVALID;
73
                            break;
74
75
                        case UserNotDefinedException::class:
76
                            $response['meta'][self::ERROR_CODE] = JWTErrorCode::USER_NOT_DEFINED;
77
                            break;
78
79
                        default:
80
                            $response['meta'][self::ERROR_CODE] = JWTErrorCode::DEFAULT;;
81
                    }
82
                    $response['meta'][self::STATUS_CODE] = StatusCodeEnum::HTTP_UNAUTHORIZED;
83
                    $response['meta'][self::MESSAGE] = $exception->getMessage();
84
                } else {
85
                    if (method_exists($exception, 'getStatusCode')) {
86
                        $response['meta'][self::STATUS_CODE] = $exception->getStatusCode();
87
                    } else {
88
                        $response['meta'][self::STATUS_CODE] = StatusCodeEnum::HTTP_INTERNAL_SERVER_ERROR;
89
                    }
90
91
                    if (method_exists($exception, 'getCode')) {
92
                        $response['meta'][self::ERROR_CODE] = $exception->getCode();
93
                    }
94
95
                    if (null === $exception->getMessage()) {
96
                        $response['meta'][self::MESSAGE] = class_basename($exceptionClass);
97
                    } else {
98
                        $response['meta'][self::MESSAGE] = $exception->getMessage();
99
                    }
100
                }
101
102
                $response = $this->debug($response, $exception);
103
104
                return $this->response(collect($response)->toArray());
105
            }
106
        }
107
108
        return parent::render($request, $exception);
109
    }
110
111
    protected function response(array $response)
112
    {
113
        return (new Response($response))->render();
114
    }
115
116
    protected function debug(array $response, Exception $exception)
117
    {
118
        if (true === config('app.debug')) {
119
            $response['meta'][self::DEBUG]['file'] = $exception->getFile();
120
            $response['meta'][self::DEBUG]['line'] = $exception->getLine();
121
            $response['meta'][self::DEBUG]['trace'] = $exception->getTrace();
122
        }
123
124
        return $response;
125
    }
126
127
    protected function overwrite(Exception $exception)
128
    {
129
        if ($exception instanceof UnauthorizedHttpException && method_exists($exception, 'getPrevious')) {
130
            $exception = $exception->getPrevious();
131
        }
132
133
        return $exception;
134
    }
135
}
136