Handler::render()   C
last analyzed

Complexity

Conditions 7
Paths 10

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 12
nc 10
nop 2
dl 0
loc 23
rs 6.7272
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This file is part of laravel.su package.
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
declare(strict_types=1);
9
10
namespace App\Exceptions;
11
12
use Whoops\Run;
13
use Illuminate\Http\Response;
14
use Illuminate\Http\JsonResponse;
15
use Illuminate\Http\RedirectResponse;
16
use Whoops\Handler\PrettyPageHandler;
17
use Illuminate\Auth\AuthenticationException;
18
use Symfony\Component\HttpKernel\Exception\HttpException;
19
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
20
21
/**
22
 * Class Handler.
23
 * Класс обработки всех исключений в нашем приложении.
24
 * Тут мы их будем обрабатывать и отображать ошибки, в случае проблем.
25
 */
26
class Handler extends ExceptionHandler
27
{
28
    /**
29
     * Список исключений, которые являются частью нормальной работы приложения
30
     * и которые не надо как-то обрабатывать. Например, "ошибка 404" и прочие.
31
     * @var array
32
     */
33
    protected $dontReport = [
34
        \Illuminate\Auth\AuthenticationException::class,
35
        \Illuminate\Auth\Access\AuthorizationException::class,
36
        \Symfony\Component\HttpKernel\Exception\HttpException::class,
37
        \Illuminate\Database\Eloquent\ModelNotFoundException::class,
38
        \Illuminate\Session\TokenMismatchException::class,
39
        \Illuminate\Validation\ValidationException::class,
40
    ];
41
42
    /**
43
     * Метод, куда прилетают все наши исключения для обработки.
44
     * Отличное место для отправки оных в Sentry, Bugsnag, и проч.
45
     * @param  \Exception $exception
46
     * @throws \Exception
47
     */
48
    public function report(\Exception $exception): void
49
    {
50
        if ($this->shouldReport($exception) && app('app')->bound('sentry')) {
51
            app('sentry')->captureException($exception);
52
        }
53
54
        parent::report($exception);
55
    }
56
57
    /**
58
     * Отображение наших необработанных ошибок.
59
     * @param \Illuminate\Http\Request $request
60
     * @param \Exception $exception
61
     * @return string|\Symfony\Component\HttpFoundation\Response
62
     * @throws \Throwable
63
     * @throws \InvalidArgumentException
64
     */
65
    public function render($request, \Exception $exception)
66
    {
67
        $exception = $this->prepareException($exception);
68
69
        $htmlAccepted = ! $request->ajax() && $request->acceptsHtml();
70
71
        if ($htmlAccepted && config('app.debug')) {
72
            $whoops = new Run();
73
            $whoops->pushHandler(new PrettyPageHandler());
0 ignored issues
show
Documentation introduced by
new \Whoops\Handler\PrettyPageHandler() is of type object<Whoops\Handler\PrettyPageHandler>, but the function expects a callable.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
74
75
            return $whoops->handleException($exception);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $whoops->handleException($exception); (string|false) is incompatible with the return type declared by the interface Illuminate\Contracts\Deb...xceptionHandler::render of type Symfony\Component\HttpFoundation\Response.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
76
        }
77
78
        if (! $this->isHttpException($exception)) {
79
            $exception = new HttpException(500, $exception->getMessage(), $exception);
80
        }
81
82
        if ($request->ajax() || $request->acceptsJson()) {
83
            return new JsonResponse($this->getError($exception), $exception->getStatusCode());
0 ignored issues
show
Compatibility introduced by
$exception of type object<Exception> is not a sub-type of object<Symfony\Component...xception\HttpException>. It seems like you assume a child class of the class Exception to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
84
        }
85
86
        return response($this->getErrorView($exception)->render(), $exception->getStatusCode());
0 ignored issues
show
Compatibility introduced by
$exception of type object<Exception> is not a sub-type of object<Symfony\Component...xception\HttpException>. It seems like you assume a child class of the class Exception to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
Bug introduced by
The method render does only exist in Illuminate\View\View, but not in Illuminate\Contracts\View\Factory.

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...
87
    }
88
89
    /**
90
     * @param HttpException $exception
91
     * @return array
92
     */
93
    private function getError(HttpException $exception): array
94
    {
95
        if (config('app.debug')) {
96
            return $this->getDebugError($exception);
97
        }
98
99
        return [
100
            'message' => Response::$statusTexts[$exception->getStatusCode()],
101
            'code'    => $exception->getStatusCode(),
102
        ];
103
    }
104
105
    /**
106
     * @param HttpException $exception
107
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
108
     */
109
    private function getErrorView(HttpException $exception)
110
    {
111
        return view('layout.error', array_merge($this->getError($exception), [
112
            'error' => $exception,
113
        ]));
114
    }
115
116
    /**
117
     * Преобразовываем ошибки аутентификации в разлогинивающий ответ.
118
     * @param  \Illuminate\Http\Request $request
119
     * @param  \Illuminate\Auth\AuthenticationException $exception
120
     * @return Response|RedirectResponse
121
     */
122
    protected function unauthenticated($request, AuthenticationException $exception)
123
    {
124
        if ($request->expectsJson()) {
125
            return response()->json(['error' => 'Unauthenticated.'], 401);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return response()->json(...authenticated.'), 401); (Illuminate\Http\JsonResponse) is incompatible with the return type documented by App\Exceptions\Handler::unauthenticated of type Illuminate\Http\Response...e\Http\RedirectResponse.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
126
        }
127
128
        return redirect()->guest('login')
129
            ->withException($exception);
130
    }
131
132
    /**
133
     * @param HttpException $exception
134
     * @return array
135
     */
136
    private function getDebugError(HttpException $exception): array
137
    {
138
        $trace = $exception->getPrevious()
139
            ? $exception->getPrevious()->getTraceAsString()
140
            : $exception->getTraceAsString();
141
142
        return [
143
            'message' => $exception->getMessage(),
144
            'code'    => $exception->getStatusCode(),
145
            'trace'   => explode("\n", $trace),
146
        ];
147
    }
148
}
149