Completed
Push — develop ( 3b0920...64bbf6 )
by Abdelrahman
01:51
created

Handler::render()   C

Complexity

Conditions 12
Paths 11

Size

Total Lines 64
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 64
rs 6.0561
c 0
b 0
f 0
cc 12
eloc 44
nc 11
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
declare(strict_types=1);
4
5
namespace Cortex\Foundation\Exceptions;
6
7
use Exception;
8
use Illuminate\Auth\AuthenticationException;
9
use Illuminate\Session\TokenMismatchException;
10
use Illuminate\Validation\ValidationException;
11
use Illuminate\Auth\Access\AuthorizationException;
12
use Illuminate\Database\Eloquent\ModelNotFoundException;
13
use Symfony\Component\HttpKernel\Exception\HttpException;
14
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
15
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
16
use Watson\Validating\ValidationException as WatsonValidationException;
17
18
class Handler extends ExceptionHandler
19
{
20
    /**
21
     * A list of the exception types that should not be reported.
22
     *
23
     * @var array
24
     */
25
    protected $dontReport = [];
26
27
    /**
28
     * A list of the inputs that are never flashed for validation exceptions.
29
     *
30
     * @var array
31
     */
32
    protected $dontFlash = [
33
        'password',
34
        'password_confirmation',
35
    ];
36
37
    /**
38
     * Report or log an exception.
39
     *
40
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
41
     *
42
     * @param \Exception $exception
43
     *
44
     * @return void
45
     */
46
    public function report(Exception $exception): void
47
    {
48
        parent::report($exception);
49
    }
50
51
    /**
52
     * Render an exception into an HTTP response.
53
     *
54
     * @param \Illuminate\Http\Request $request
55
     * @param \Exception               $exception
56
     *
57
     * @return \Illuminate\Http\Response
58
     */
59
    public function render($request, Exception $exception)
60
    {
61
        if ($exception instanceof TokenMismatchException) {
62
            return intend([
63
                'back' => true,
64
                'with' => ['warning' => trans('cortex/foundation::messages.token_mismatch')],
65
            ]);
66
        } elseif ($exception instanceof WatsonValidationException) {
67
            return intend([
68
                'back' => true,
69
                'withInput' => $request->all(),
70
                'withErrors' => $exception->errors(),
71
            ]);
72
        } elseif ($exception instanceof ValidationException) {
73
            return intend([
74
                'back' => true,
75
                'withInput' => $request->all(),
76
                'withErrors' => $exception->errors(),
77
            ]);
78
        } elseif ($exception instanceof GenericException) {
79
            return intend([
80
                'url' => $exception->getRedirection() ?? route($request->get('accessarea').'.home'),
81
                'withInput' => $exception->getInputs() ?? $request->all(),
82
                'with' => ['warning' => $exception->getMessage()],
83
            ]);
84
        } elseif ($exception instanceof AuthorizationException) {
85
            return intend([
86
                'url' => route($request->get('accessarea').'.home'),
87
                'with' => ['warning' => $exception->getMessage()],
88
            ]);
89
        } elseif ($exception instanceof NotFoundHttpException) {
90
            // Catch localized routes with missing {locale}
91
            // and redirect them to the correct localized version
92
            if (config('cortex.foundation.route.locale_redirect')) {
93
                $originalUrl = $request->url();
94
                $localizedUrl = app('laravellocalization')->getLocalizedURL(null, $originalUrl);
95
96
                try {
97
                    // Will return `NotFoundHttpException` exception if no match found!
98
                    app('router')->getRoutes()->match(request()->create($localizedUrl));
99
100
                    return intend([
101
                        'url' => $originalUrl !== $localizedUrl ? $localizedUrl : route($request->get('accessarea').'.home'),
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 125 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
102
                        'with' => ['warning' => $exception->getMessage()],
103
                    ]);
104
                } catch (Exception $exception) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
105
                }
106
            }
107
108
            return $this->prepareResponse($request, $exception);
109
        } elseif ($exception instanceof ModelNotFoundException) {
110
            $area = $request->get('accessarea');
111
            $model = str_replace('Contract', '', $exception->getModel());
112
            $single = mb_strtolower(mb_substr($model, mb_strrpos($model, '\\') + 1));
113
            $plural = str_plural($single);
114
115
            return intend([
116
                'url' => $area ? route("{$area}.{$plural}.index") : route("{$area}.home"),
117
                'with' => ['warning' => trans('cortex/foundation::messages.resource_not_found', ['resource' => $single, 'id' => $request->route()->parameter($single)])],
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 169 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
118
            ]);
119
        }
120
121
        return parent::render($request, $exception);
122
    }
123
124
    /**
125
     * Render the given HttpException.
126
     *
127
     * @param \Symfony\Component\HttpKernel\Exception\HttpException $exception
128
     *
129
     * @return \Symfony\Component\HttpFoundation\Response
130
     */
131
    protected function renderHttpException(HttpException $exception)
132
    {
133
        $status = $exception->getStatusCode();
134
135
        if (view()->exists("cortex/foundation::common.errors.{$status}")) {
0 ignored issues
show
Bug introduced by
The method exists does only exist in Illuminate\Contracts\View\Factory, but not in Illuminate\View\View.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
136
            return response()->view("cortex/foundation::common.errors.{$status}", ['exception' => $exception], $status, $exception->getHeaders());
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 146 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
137
        } else {
138
            return parent::renderHttpException($exception);
139
        }
140
    }
141
142
    /**
143
     * Convert a validation exception into a response.
144
     *
145
     * @param  \Illuminate\Http\Request  $request
146
     * @param  \Illuminate\Validation\ValidationException  $exception
147
     * @return \Illuminate\Http\Response
0 ignored issues
show
Documentation introduced by
Should the return type not be \Illuminate\Http\RedirectResponse?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
148
     */
149
    protected function invalid($request, ValidationException $exception)
150
    {
151
        $url = $exception->redirectTo ?? url()->previous();
152
153
        return redirect($url)
154
            ->withInput($request->except($this->dontFlash))
155
            ->withErrors(
156
                $exception->errors(),
157
                $exception->errorBag
158
            );
159
    }
160
161
    /**
162
     * Convert an authentication exception into an unauthenticated response.
163
     *
164
     * @param \Illuminate\Http\Request                 $request
165
     * @param \Illuminate\Auth\AuthenticationException $exception
166
     *
167
     * @return \Illuminate\Http\Response
0 ignored issues
show
Documentation introduced by
Should the return type not be \Illuminate\Http\JsonRes...e\Http\RedirectResponse?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
168
     */
169
    protected function unauthenticated($request, AuthenticationException $exception)
170
    {
171
        return intend([
172
            'url' => route($request->get('accessarea').'.login'),
173
            'with' => ['warning' => trans('cortex/foundation::messages.session_required')],
174
        ]);
175
    }
176
}
177