Completed
Branch master (a6481d)
by Fèvre
02:09
created

Handler::render()   B

Complexity

Conditions 6
Paths 3

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 8.8571
c 0
b 0
f 0
cc 6
eloc 11
nc 3
nop 2
1
<?php
2
3
namespace Xetaravel\Exceptions;
4
5
use Exception;
6
use Illuminate\Auth\AuthenticationException;
7
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
8
use Illuminate\Support\Facades\Auth;
9
10
class Handler extends ExceptionHandler
11
{
12
    /**
13
     * A list of the exception types that should not be reported.
14
     *
15
     * @var array
16
     */
17
    protected $dontReport = [
18
        \Illuminate\Auth\AuthenticationException::class,
19
        \Illuminate\Auth\Access\AuthorizationException::class,
20
        \Symfony\Component\HttpKernel\Exception\HttpException::class,
21
        \Illuminate\Database\Eloquent\ModelNotFoundException::class,
22
        \Illuminate\Session\TokenMismatchException::class,
23
        \Illuminate\Validation\ValidationException::class,
24
    ];
25
26
    /**
27
     * Report or log an exception.
28
     *
29
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
30
     *
31
     * @param  \Exception  $exception
32
     * @return void
33
     */
34
    public function report(Exception $exception)
35
    {
36
        parent::report($exception);
37
    }
38
39
    /**
40
     * Render an exception into an HTTP response.
41
     *
42
     * @param  \Illuminate\Http\Request  $request
43
     * @param  \Exception  $exception
44
     * @return \Illuminate\Http\Response
45
     */
46
    public function render($request, Exception $exception)
47
    {
48
        if ($exception instanceof \Ultraware\Roles\Exceptions\RoleDeniedException ||
49
            $exception instanceof \Ultraware\Roles\Exceptions\PermissionDeniedException ||
50
            $exception instanceof \Ultraware\Roles\Exceptions\LevelDeniedException) {
51
            //If the user is banished, redirect him to the banished page.
52
            if (Auth::check() && Auth::user()->hasRole('banished')) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Illuminate\Contracts\Auth\Authenticatable as the method hasRole() does only exist in the following implementations of said interface: Xetaravel\Models\User.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
53
                return redirect()
54
                    ->route('page_banished');
55
            }
56
57
            return redirect()
58
                ->route('page_index')
59
                ->with('danger', 'You don\'t have the permission to view this page.');
60
        }
61
62
        return parent::render($request, $exception);
63
    }
64
65
    /**
66
     * Convert an authentication exception into an unauthenticated response.
67
     *
68
     * @param \Illuminate\Http\Request $request
69
     * @param \Illuminate\Auth\AuthenticationException $exception
70
     *
71
     * @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...
72
     */
73
    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...
74
    {
75
        if ($request->expectsJson()) {
76
            return response()->json(['error' => 'Unauthenticated.'], 401);
77
        }
78
79
        return redirect()->guest(route('users_auth_login'));
80
    }
81
82
    /**
83
     * Create a Symfony response for the given exception.
84
     *
85
     * @param \Exception $e The exception to convert.
86
     *
87
     * @return mixed
88
     */
89
    protected function convertExceptionToResponse(Exception $e)
90
    {
91
        if (config('app.debug')) {
92
            $whoops = new \Whoops\Run;
93
            $whoops->pushHandler(new \Whoops\Handler\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...
94
95
            return response()->make(
96
                $whoops->handleException($e),
0 ignored issues
show
Security Bug introduced by
It seems like $whoops->handleException($e) targeting Whoops\Run::handleException() can also be of type false; however, Illuminate\Contracts\Rou...ResponseFactory::make() does only seem to accept string, did you maybe forget to handle an error condition?
Loading history...
97
                method_exists($e, 'getStatusCode') ? $e->getStatusCode() : 500,
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Exception as the method getStatusCode() does only exist in the following sub-classes of Exception: Illuminate\Foundation\Ht...aintenanceModeException, Symfony\Component\HttpKe...cessDeniedHttpException, Symfony\Component\HttpKe...BadRequestHttpException, Symfony\Component\HttpKe...n\ConflictHttpException, Symfony\Component\HttpKe...ption\GoneHttpException, Symfony\Component\HttpKe...Exception\HttpException, Symfony\Component\HttpKe...thRequiredHttpException, Symfony\Component\HttpKe...NotAllowedHttpException, Symfony\Component\HttpKe...AcceptableHttpException, Symfony\Component\HttpKe...n\NotFoundHttpException, Symfony\Component\HttpKe...tionFailedHttpException, Symfony\Component\HttpKe...onRequiredHttpException, Symfony\Component\HttpKe...navailableHttpException, Symfony\Component\HttpKe...nyRequestsHttpException, Symfony\Component\HttpKe...authorizedHttpException, Symfony\Component\HttpKe...ableEntityHttpException, Symfony\Component\HttpKe...dMediaTypeHttpException. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
98
                method_exists($e, 'getHeaders') ? $e->getHeaders() : []
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Exception as the method getHeaders() does only exist in the following sub-classes of Exception: Illuminate\Foundation\Ht...aintenanceModeException, Symfony\Component\HttpKe...cessDeniedHttpException, Symfony\Component\HttpKe...BadRequestHttpException, Symfony\Component\HttpKe...n\ConflictHttpException, Symfony\Component\HttpKe...ption\GoneHttpException, Symfony\Component\HttpKe...Exception\HttpException, Symfony\Component\HttpKe...thRequiredHttpException, Symfony\Component\HttpKe...NotAllowedHttpException, Symfony\Component\HttpKe...AcceptableHttpException, Symfony\Component\HttpKe...n\NotFoundHttpException, Symfony\Component\HttpKe...tionFailedHttpException, Symfony\Component\HttpKe...onRequiredHttpException, Symfony\Component\HttpKe...navailableHttpException, Symfony\Component\HttpKe...nyRequestsHttpException, Symfony\Component\HttpKe...authorizedHttpException, Symfony\Component\HttpKe...ableEntityHttpException, Symfony\Component\HttpKe...dMediaTypeHttpException. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
99
            );
100
        }
101
102
        return parent::convertExceptionToResponse($e);
103
    }
104
}
105