Completed
Push — master ( a4a865...ee8a3d )
by Joao
03:57
created

src/Whoops/JsonResponseHandler.php (1 issue)

super-globals are not used.

Coding Style Minor

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
 * Whoops - php errors for cool kids
4
 * @author Filipe Dobreira <http://github.com/filp>
5
 */
6
7
namespace ByJG\RestServer\Whoops;
8
9
use Whoops\Exception\Formatter;
10
use Whoops\Handler\Handler;
11
use Whoops\Handler\JsonResponseHandler as OriginalJsonHandler;
12
use Whoops\Util\Misc;
13
14
/**
15
 * Catches an exception and converts it to a JSON
16
 * response. Additionally can also return exception
17
 * frames for consumption by an API.
18
 */
19
class JsonResponseHandler extends OriginalJsonHandler
20
{
21
22
    use WhoopsDebugTrait;
23
    use WhoopsHeaderTrait;
24
25
    /**
26
     * @return int
27
     */
28
    public function handle()
29
    {
30
        if ($this->onlyForAjaxRequests() && !$this->isAjaxRequest()) {
31
            return Handler::DONE;
32
        }
33
34
        $response = array(
35
            'error' => Formatter::formatExceptionAsDataArray(
36
                $this->getInspector(),
37
                $this->addTraceToOutput()
38
            ),
39
        );
40
41
        $debug = $this->getDataTable();
42
        if (count($debug) > 0) {
43
            $response["debug"] = $debug;
44
        }
45
46
        if (Misc::canSendHeaders()) {
47
            header('Content-Type: application/json');
48
        }
49
50
        $this->setProperHeader($this->getException());
51
        echo json_encode($response);
52
        return Handler::QUIT;
53
    }
54
55
    public function isAjaxRequest() {
0 ignored issues
show
isAjaxRequest 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...
56
        return (
57
            !empty($_SERVER['HTTP_X_REQUESTED_WITH'])
58
            && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
59
60
    }
61
62
}
63