Completed
Pull Request — master (#45)
by Şəhriyar
10:29
created

Handler::unauthenticated()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 0
cts 4
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 2
crap 6
1
<?php namespace App\Exceptions;
2
3
use App\Exceptions\Users\UserNotActivatedException;
4
use Illuminate\Auth\Access\AuthorizationException;
5
use Illuminate\Auth\AuthenticationException;
6
use Illuminate\Database\Eloquent\ModelNotFoundException;
7
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
8
use Illuminate\Http\Response as IlluminateResponse;
9
use Illuminate\Session\TokenMismatchException;
10
use Illuminate\Validation\ValidationException as IlluminateValidationException;
11
use Symfony\Component\HttpKernel\Exception\HttpException;
12
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
13
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
14
15
class Handler extends ExceptionHandler
16
{
17
    /**
18
     * A list of the exception types that should not be reported.
19
     *
20
     * @var array
21
     */
22
    protected $dontReport = [
23
        AuthorizationException::class,
24
        HttpException::class,
25
        IlluminateValidationException::class,
26
        ModelNotFoundException::class,
27
    ];
28
29
    /**
30
     * Report or log an exception.
31
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
32
     *
33
     * @param \Exception $e
34
     *
35
     * @return void
36
     */
37 5
    public function report(\Exception $e)
38
    {
39 5
        parent::report($e);
40 5
    }
41
42
    /**
43
     * Render an exception into an HTTP response.
44
     *
45
     * @param \Illuminate\Http\Request $request
46
     * @param \Exception               $e
47
     *
48
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
49
     */
50 4
    public function render($request, \Exception $e)
51
    {
52 4
        if ($e instanceof ModelNotFoundException) {
53 2
            $e = new NotFoundHttpException($e->getMessage(), $e);
54
        }
55
56 4
        if ($request->expectsJson()) {
57 4
            $exceptionClass = get_class($e);
58 4
            $responseBody = ['exception' => $exceptionClass, 'message' => $e->getMessage()];
59
60
            # FileStream exceptions response body
61 4
            $preventRetry = true;
62 4
            $resetUpload = false;
63 4
            if ($e instanceof FileStream\UploadFilenameIsEmptyException) {
64
                $preventRetry = false;
65
            } elseif ($e instanceof FileStream\UploadIncompleteException) {
66
                $preventRetry = false;
67
                $resetUpload = true;
68
            } elseif ($e instanceof FileStream\UploadAttemptFailedException) {
69
                $preventRetry = false;
70
            }
71 4
            if (strpos($exceptionClass, 'App\Exceptions\FileStream') !== false) {
72
                $responseBody = ['exception' => $exceptionClass, 'error' => $e->getMessage(), 'preventRetry' => $preventRetry, 'reset' => $resetUpload];
73
            }
74
75
            # Status codes
76 4
            if ($e instanceof UnauthorizedHttpException) {
77
                $statusCode = IlluminateResponse::HTTP_UNAUTHORIZED;
78
            } elseif ($e instanceof UserNotActivatedException) {
79
                $statusCode = IlluminateResponse::HTTP_FORBIDDEN;
80
            } elseif ($e instanceof NotFoundHttpException) {
81 2
                $statusCode = IlluminateResponse::HTTP_NOT_FOUND;
82
            } elseif ($e instanceof \BadMethodCallException) {
83
                $statusCode = IlluminateResponse::HTTP_METHOD_NOT_ALLOWED;
84 4
            } elseif ($e instanceof \UnexpectedValueException || $e instanceof IlluminateValidationException || $e instanceof TokenMismatchException) {
85 3
                $statusCode = IlluminateResponse::HTTP_UNPROCESSABLE_ENTITY;
86 3
                if ($e instanceof IlluminateValidationException) {
87 3
                    $messageBag = $e->validator->errors();
88 3
                    $responseBody['message'] = $messageBag->getMessages();
89
                }
90
            } elseif ($e instanceof \OverflowException) {
91
                $statusCode = IlluminateResponse::HTTP_REQUEST_ENTITY_TOO_LARGE;
92
            } else {
93 1
                $statusCode = method_exists($e, 'getStatusCode') ? $e->getStatusCode() : $e->getCode();
94
            }
95
96 4
            if (empty($statusCode)) {
97
                $statusCode = IlluminateResponse::HTTP_INTERNAL_SERVER_ERROR;
98
            }
99
100 4
            return response()->json($responseBody)->setStatusCode($statusCode);
101
        }
102
103
        if ($request->method() != 'GET' && $request->header('content-type') == 'application/x-www-form-urlencoded') {
104
            return redirect()->back()->withInput($request->all())->withErrors($e->getMessage());
105
        }
106
107
        return parent::render($request, $e);
108
    }
109
110
    /**
111
     * Convert an authentication exception into an unauthenticated response.
112
     *
113
     * @param  \Illuminate\Http\Request                 $request
114
     * @param  \Illuminate\Auth\AuthenticationException $exception
115
     *
116
     * @return \Illuminate\Http\Response
117
     */
118
    protected function unauthenticated($request, AuthenticationException $exception)
0 ignored issues
show
Unused Code introduced by
The parameter $exception is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
119
    {
120
        if ($request->expectsJson()) {
121
            return response()->json(['error' => 'Unauthenticated.'], 401);
122
        }
123
124
        return redirect()->guest('login');
125
    }
126
}
127