Completed
Push — master ( fa013f...2db18f )
by Ryan
05:29
created

ExceptionHandler::unauthenticated()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 3
nop 2
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
1
<?php namespace Anomaly\Streams\Platform\Exception;
2
3
use Exception;
4
use Illuminate\Auth\AuthenticationException;
5
use Illuminate\Http\Request;
6
use Illuminate\Http\Response;
7
use Symfony\Component\Debug\ExceptionHandler as SymfonyDisplayer;
8
use Symfony\Component\HttpKernel\Exception\HttpException;
9
10
/**
11
 * Class ExceptionHandler
12
 *
13
 * @link   http://pyrocms.com/
14
 * @author PyroCMS, Inc. <[email protected]>
15
 * @author Ryan Thompson <[email protected]>
16
 */
17
class ExceptionHandler extends \Illuminate\Foundation\Exceptions\Handler
18
{
19
20
    /**
21
     * A list of the exception types that should not be reported.
22
     *
23
     * @var array
24
     */
25
    protected $dontReport = [
26
        \Illuminate\Auth\AuthenticationException::class,
27
        \Illuminate\Auth\Access\AuthorizationException::class,
28
        \Symfony\Component\HttpKernel\Exception\HttpException::class,
29
        \Illuminate\Database\Eloquent\ModelNotFoundException::class,
30
        \Illuminate\Session\TokenMismatchException::class,
31
        \Illuminate\Validation\ValidationException::class,
32
    ];
33
34
    /**
35
     * Render an exception into an HTTP response.
36
     *
37
     * @param  Request   $request
38
     * @param  Exception $e
39
     * @return Response
40
     */
41
    public function render($request, Exception $e)
42
    {
43
        if ($e instanceof HttpException) {
44
            if (!$e->getStatusCode() == 404) {
45
                return $this->renderHttpException($e);
46
            }
47
48
            if (($redirect = config('streams::404.redirect')) && $request->path() !== $redirect) {
49
                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...
50
            }
51
52
            return $this->renderHttpException($e);
53
        } elseif (!config('app.debug')) {
54
            return response()->view("streams::errors.500", ['message' => $e->getMessage()], 500);
55
        } else {
56
            return parent::render($request, $e);
57
        }
58
    }
59
60
    /**
61
     * Render the given HttpException.
62
     *
63
     * @param  \Symfony\Component\HttpKernel\Exception\HttpException $e
64
     * @return \Symfony\Component\HttpFoundation\Response
65
     */
66
    protected function renderHttpException(HttpException $e)
67
    {
68
        $status = $e->getStatusCode();
69
70
        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...
71
            return response()->view("streams::errors.{$status}", ['message' => $e->getMessage()], $status);
72
        } else {
73
            return (new SymfonyDisplayer(config('app.debug')))->handle($e);
74
        }
75
    }
76
77
    /**
78
     * Convert an authentication exception into an unauthenticated response.
79
     *
80
     * @param  \Illuminate\Http\Request                 $request
81
     * @param  \Illuminate\Auth\AuthenticationException $exception
82
     * @return \Illuminate\Http\Response
83
     */
84
    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...
85
    {
86
        if ($request->expectsJson()) {
87
            return response()->json(['error' => 'Unauthenticated.'], 401);
88
        }
89
90
        if ($request->segment(1) === 'admin') {
91
            return redirect()->guest('admin/login');
92
        } else {
93
            return redirect()->guest('login');
94
        }
95
    }
96
}
97