Completed
Push — master ( 125cc2...d66793 )
by Avtandil
05:09 queued 02:38
created

Handler::shouldRenderAsJson()   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
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 8
ccs 0
cts 7
cp 0
crap 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/*
3
 * This file is part of the Laravel Platfourm package.
4
 *
5
 * (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Longman\Platfourm\Foundation\Exceptions;
12
13
use App;
14
use Exception;
15
use Illuminate\Database\Eloquent\ModelNotFoundException;
16
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
17
use Illuminate\Foundation\Validation\ValidationException;
18
use Slack;
19
use Symfony\Component\HttpKernel\Exception\HttpException;
20
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
21
22
class Handler extends ExceptionHandler
23
{
24
    /**
25
     * A list of the exception types that should not be reported.
26
     *
27
     * @var array
28
     */
29
    protected $dontReport = [
30
        AuthorizationException::class,
31
        HttpException::class,
32
        ModelNotFoundException::class,
33
        ValidationException::class,
34
    ];
35
36
    public function sendToSlack(Exception $e)
37
    {
38
        if (!App::environment('production')) {
39
            return false;
40
        }
41
42
        $endpoint = config('slack.endpoint');
43
        if (strlen($endpoint) < 40) {
44
            return false;
45
        }
46
47
        Slack::send($e->getMessage());
48
    }
49
50
    /**
51
     * Render the given HttpException.
52
     *
53
     * @param  \Symfony\Component\HttpKernel\Exception\HttpException $e
54
     * @return \Symfony\Component\HttpFoundation\Response
55
     */
56
    protected function renderHttpException(HttpException $e)
57
    {
58
        $status = $e->getStatusCode();
59
60
        if (view()->exists("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...
61
            return response()->view("common.errors.{$status}", ['exception' => $e], $status, $e->getHeaders());
62
        } else {
63
            return $this->convertExceptionToResponse($e);
64
        }
65
    }
66
67
    /**
68
     * Render an exception into an HTTP response.
69
     *
70
     * @param  \Illuminate\Http\Request $request
71
     * @param  \Exception               $e
72
     * @return \Illuminate\Http\Response
73
     */
74
    public function render($request, Exception $e)
75
    {
76
        if ($e instanceof ModelNotFoundException) {
77
            $e = new NotFoundHttpException($e->getMessage(), $e);
78
        }
79
80
        if ($this->shouldRenderAsJson($request, $e)) {
81
            return $this->renderAsJson($request, $e);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->renderAsJson($request, $e); (Illuminate\Http\JsonResponse) is incompatible with the return type documented by Longman\Platfourm\Founda...eptions\Handler::render of type Illuminate\Http\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...
82
        }
83
84
        return parent::render($request, $e);
85
    }
86
87
    protected function shouldRenderAsJson($request, Exception $e)
88
    {
89
        if ($e instanceof ValidationException) {
90
            return false;
91
        }
92
93
        return $request->wantsJson();
94
    }
95
96
    protected function renderAsJson($request, Exception $e)
0 ignored issues
show
Unused Code introduced by
The parameter $request 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...
97
    {
98
        // Define the response
99
        $response = [
100
            'errors' => 'Sorry, something went wrong.'
101
        ];
102
103
        // If the app is in debug mode
104
        if (config('app.debug')) {
105
            // Add the exception class name, message and stack trace to response
106
            $response['exception'] = (new \ReflectionClass($e))->getName();
0 ignored issues
show
Bug introduced by
Consider using (new \ReflectionClass($e))->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
107
            $response['message']   = $e->getMessage();
108
            $response['trace']     = $e->getTrace();
109
        }
110
111
        // Default response of 400
112
        $status = 400;
113
114
        // If this exception is an instance of HttpException
115
        if ($this->isHttpException($e)) {
116
            // Grab the HTTP status code from the Exception
117
            $status = $e->getStatusCode();
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: Longman\Platfourm\Auth\E...ions\ForbiddenException, Longman\Platfourm\Auth\E...s\UnauthorizedException, Longman\Platfourm\Founda...ions\ForbiddenException, Longman\Platfourm\Founda...s\InvalidValueException, Longman\Platfourm\Founda...s\UnauthorizedException, Longman\Platfourm\Founda...\ValueNotFoundException, 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...
118
        }
119
120
        // Return a JSON response with the response array and status code
121
        return response()->json($response, $status);
122
    }
123
124
}
125