Completed
Push — master ( 486598...7261f1 )
by Ryan
12:27
created

ExceptionHandler::render()   D

Complexity

Conditions 9
Paths 7

Size

Total Lines 32
Code Lines 16

Duplication

Lines 7
Ratio 21.88 %

Importance

Changes 0
Metric Value
cc 9
eloc 16
nc 7
nop 2
dl 7
loc 32
rs 4.909
c 0
b 0
f 0
1
<?php namespace Anomaly\Streams\Platform\Exception;
2
3
use Exception;
4
use GrahamCampbell\Exceptions\NewExceptionHandler;
5
use Illuminate\Auth\AuthenticationException;
6
use Illuminate\Http\RedirectResponse;
7
use Illuminate\Http\Request;
8
use Illuminate\Http\Response;
9
use Illuminate\Validation\ValidationException;
10
use Symfony\Component\Debug\ExceptionHandler as SymfonyDisplayer;
11
use Symfony\Component\HttpKernel\Exception\HttpException;
12
13
/**
14
 * Class ExceptionHandler
15
 *
16
 * @link   http://pyrocms.com/
17
 * @author PyroCMS, Inc. <[email protected]>
18
 * @author Ryan Thompson <[email protected]>
19
 */
20
class ExceptionHandler extends NewExceptionHandler
21
{
22
23
    /**
24
     * A list of the exception types that should not be reported.
25
     *
26
     * @var array
27
     */
28
    protected $dontReport = [
29
        \Illuminate\Auth\AuthenticationException::class,
30
        \Illuminate\Auth\Access\AuthorizationException::class,
31
        \Symfony\Component\HttpKernel\Exception\HttpException::class,
32
        \Illuminate\Database\Eloquent\ModelNotFoundException::class,
33
        \Illuminate\Session\TokenMismatchException::class,
34
        \Illuminate\Validation\ValidationException::class,
35
    ];
36
37
    /**
38
     * Render an exception into an HTTP response.
39
     *
40
     * @param  Request   $request
41
     * @param  Exception $e
42
     * @return Response
43
     */
44
    public function render($request, Exception $e)
45
    {
46
        /**
47
         * Have to catch this for some reason.
48
         * Not sure why our handler passes this.
49
         *
50
         * @todo: Clean up
51
         */
52 View Code Duplication
        if ($e instanceof AuthenticationException) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
53
            if ($request->segment(1) === 'admin') {
54
                return redirect()->guest('admin/login');
0 ignored issues
show
Bug Best Practice introduced by
The return type of return redirect()->guest('admin/login'); (Illuminate\Http\RedirectResponse) is incompatible with the return type documented by Anomaly\Streams\Platform...xceptionHandler::render of type Illuminate\Http\Response|null.

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...
55
            } else {
56
                return redirect()->guest('login');
0 ignored issues
show
Bug Best Practice introduced by
The return type of return redirect()->guest('login'); (Illuminate\Http\RedirectResponse) is incompatible with the return type documented by Anomaly\Streams\Platform...xceptionHandler::render of type Illuminate\Http\Response|null.

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...
57
            }
58
        }
59
60
        if ($e instanceof HttpException) {
61
            if (!$e->getStatusCode() == 404) {
62
                return $this->renderHttpException($e);
63
            }
64
65
            if (($redirect = config('streams::404.redirect')) && $request->path() !== $redirect) {
66
                return redirect($redirect, 301);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return redirect($redirect, 301); (Illuminate\Http\RedirectResponse) is incompatible with the return type documented by Anomaly\Streams\Platform...xceptionHandler::render of type Illuminate\Http\Response|null.

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...
67
            }
68
69
            return $this->renderHttpException($e);
70
        } elseif (!config('app.debug') && !$e instanceof ValidationException) { // Maybe shouldntRender here?
71
            return response()->view("streams::errors.500", ['message' => $e->getMessage()], 500);
72
        } else {
73
            return parent::render($request, $e);
74
        }
75
    }
76
77
    /**
78
     * Render the given HttpException.
79
     *
80
     * @param  \Symfony\Component\HttpKernel\Exception\HttpException $e
81
     * @return \Symfony\Component\HttpFoundation\Response
82
     */
83
    protected function renderHttpException(HttpException $e)
84
    {
85
        $status = $e->getStatusCode();
86
87
        if (!config('app.debug') && view()->exists("streams::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...
88
            return response()->view("streams::errors.{$status}", ['message' => $e->getMessage()], $status);
89
        } else {
90
            return (new SymfonyDisplayer(config('app.debug')))->handle($e);
91
        }
92
    }
93
94
    /**
95
     * Map exception into an illuminate response.
96
     *
97
     * @param  \Symfony\Component\HttpFoundation\Response $response
98
     * @param  \Exception                                 $e
99
     * @return \Illuminate\Http\Response
100
     */
101
    protected function toIlluminateResponse($response, Exception $e)
0 ignored issues
show
Coding Style introduced by
toIlluminateResponse uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
102
    {
103
        if ($response instanceof SymfonyRedirectResponse) {
0 ignored issues
show
Bug introduced by
The class Anomaly\Streams\Platform...SymfonyRedirectResponse does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
104
            $response = new RedirectResponse(
105
                $response->getTargetUrl(),
106
                $response->getStatusCode(),
107
                $response->headers->all()
108
            );
109
        } else {
110
            $response = new Response($response->getContent(), $response->getStatusCode(), $response->headers->all());
111
        }
112
113
        /**
114
         * Have to catch this for some reason.
115
         * Not sure why our handler passes this.
116
         *
117
         * @todo: Clean up
118
         */
119
        if ($e instanceof AuthenticationException) {
120
121
            $path     = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
122
            $segments = array_filter(explode('/', $path));
123
124
            if (array_shift($segments) === 'admin') {
125
                return redirect()->guest('admin/login');
0 ignored issues
show
Bug Best Practice introduced by
The return type of return redirect()->guest('admin/login'); (Illuminate\Http\RedirectResponse) is incompatible with the return type documented by Anomaly\Streams\Platform...r::toIlluminateResponse 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...
126
            } else {
127
                return redirect()->guest('login');
0 ignored issues
show
Bug Best Practice introduced by
The return type of return redirect()->guest('login'); (Illuminate\Http\RedirectResponse) is incompatible with the return type documented by Anomaly\Streams\Platform...r::toIlluminateResponse 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...
128
            }
129
        }
130
131
        return $response->withException($e);
132
    }
133
134
    /**
135
     * Convert an authentication exception into an unauthenticated response.
136
     *
137
     * @param  \Illuminate\Http\Request                 $request
138
     * @param  \Illuminate\Auth\AuthenticationException $exception
139
     * @return \Illuminate\Http\Response
140
     */
141
    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...
142
    {
143
        if ($request->expectsJson()) {
144
            return response()->json(['error' => 'Unauthenticated.'], 401);
145
        }
146
147 View Code Duplication
        if ($request->segment(1) === 'admin') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
148
            return redirect()->guest('admin/login');
149
        } else {
150
            return redirect()->guest('login');
151
        }
152
    }
153
}
154