summaryrefslogtreecommitdiff
path: root/src/Exceptions/Handlers/Whoops.php
blob: 72e97776b8795e74bcb0a463d8b44a50c18da703 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php

namespace Engelsystem\Exceptions\Handlers;

use Engelsystem\Application;
use Engelsystem\Container\Container;
use Engelsystem\Helpers\Authenticator;
use Engelsystem\Http\Request;
use Throwable;
use Whoops\Handler\JsonResponseHandler;
use Whoops\Handler\PrettyPageHandler;
use Whoops\Run as WhoopsRunner;

class Whoops extends Legacy implements HandlerInterface
{
    /** @var Application */
    protected $app;

    /**
     * Whoops constructor.
     *
     * @param Container $app
     */
    public function __construct(Container $app)
    {
        $this->app = $app;
    }

    /**
     * @param Request   $request
     * @param Throwable $e
     */
    public function render($request, Throwable $e)
    {
        $whoops = $this->app->make(WhoopsRunner::class);
        $handler = $this->getPrettyPageHandler($e);
        $whoops->pushHandler($handler);
        $whoops->writeToOutput(false);
        $whoops->allowQuit(false);

        if ($request->isXmlHttpRequest()) {
            $handler = $this->getJsonResponseHandler();
            $whoops->pushHandler($handler);
        }

        echo $whoops->handleException($e);
    }

    /**
     * @param Throwable $e
     * @return PrettyPageHandler
     */
    protected function getPrettyPageHandler(Throwable $e)
    {
        $handler = $this->app->make(PrettyPageHandler::class);

        $handler->setPageTitle('Just another ' . get_class($e) . ' to fix :(');
        $handler->setApplicationPaths([realpath(__DIR__ . '/../..')]);

        $data = $this->getData();
        $handler->addDataTable('Application', $data);

        return $handler;
    }

    /**
     * @return JsonResponseHandler
     */
    protected function getJsonResponseHandler()
    {
        $handler = $this->app->make(JsonResponseHandler::class);
        $handler->setJsonApi(true);
        $handler->addTraceToOutput(true);

        return $handler;
    }

    /**
     * Aggregate application data
     *
     * @return array
     */
    protected function getData()
    {
        $data = [];
        $user = null;

        if ($this->app->has('authenticator')) {
            /** @var Authenticator $authenticator */
            $authenticator = $this->app->get('authenticator');
            $user = $authenticator->user();
        }

        $data['user'] = $user;
        $data['Booted'] = $this->app->isBooted();

        return $data;
    }
}