Passed
Push — master ( b89c29...458768 )
by Greg
05:54
created

HandleExceptions::process()   B

Complexity

Conditions 9
Paths 27

Size

Total Lines 53
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 9
eloc 25
c 1
b 0
f 1
nc 27
nop 2
dl 0
loc 53
rs 8.0555

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * webtrees: online genealogy
5
 * Copyright (C) 2019 webtrees development team
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
 * GNU General Public License for more details.
14
 * You should have received a copy of the GNU General Public License
15
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16
 */
17
18
declare(strict_types=1);
19
20
namespace Fisharebest\Webtrees\Http\Middleware;
21
22
use Fig\Http\Message\RequestMethodInterface;
23
use Fig\Http\Message\StatusCodeInterface;
24
use Fisharebest\Webtrees\Exceptions\HttpException;
25
use Fisharebest\Webtrees\Http\ViewResponseTrait;
26
use Fisharebest\Webtrees\Log;
27
use Fisharebest\Webtrees\Services\TreeService;
28
use Fisharebest\Webtrees\Site;
29
use League\Flysystem\NotSupportedException;
30
use Psr\Http\Message\ResponseInterface;
31
use Psr\Http\Message\ServerRequestInterface;
32
use Psr\Http\Server\MiddlewareInterface;
33
use Psr\Http\Server\RequestHandlerInterface;
34
use Throwable;
35
36
use function app;
37
use function dirname;
38
use function ob_end_clean;
39
use function ob_get_level;
40
use function response;
41
use function str_replace;
42
use function view;
43
44
use const PHP_EOL;
45
46
/**
47
 * Middleware to handle and render errors.
48
 */
49
class HandleExceptions implements MiddlewareInterface, StatusCodeInterface
50
{
51
    use ViewResponseTrait;
52
53
    /** @var TreeService */
54
    private $tree_service;
55
56
    /**
57
     * HandleExceptions constructor.
58
     *
59
     * @param TreeService $tree_service
60
     */
61
    public function __construct(TreeService $tree_service)
62
    {
63
        $this->tree_service = $tree_service;
64
    }
65
66
    /**
67
     * @param ServerRequestInterface  $request
68
     * @param RequestHandlerInterface $handler
69
     *
70
     * @return ResponseInterface
71
     * @throws Throwable
72
     */
73
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
74
    {
75
        try {
76
            return $handler->handle($request);
77
        } catch (HttpException $exception) {
78
            // The router added the tree attribute to the request, and we need it for the error response.
79
            $request = app(ServerRequestInterface::class) ?? $request;
80
81
            return $this->httpExceptionResponse($request, $exception);
82
        } catch (NotSupportedException $exception) {
83
            // The router added the tree attribute to the request, and we need it for the error response.
84
            $request = app(ServerRequestInterface::class) ?? $request;
85
86
            return $this->thirdPartyExceptionResponse($request, $exception);
87
        } catch (Throwable $exception) {
88
            // Exception thrown while buffering output?
89
            while (ob_get_level() > 0) {
90
                ob_end_clean();
91
            }
92
93
            // The Router middleware may have added a tree attribute to the request.
94
            // This might be usable in the error page.
95
            if (app()->has(ServerRequestInterface::class)) {
96
                $request = app(ServerRequestInterface::class) ?? $request;
97
            }
98
99
            // Show the exception in a standard webtrees page (if we can).
100
            try {
101
                return $this->unhandledExceptionResponse($request, $exception);
102
            } catch (Throwable $e) {
103
                // That didn't work.  Try something else.
104
            }
105
106
            // Show the exception in a tree-less webtrees page (if we can).
107
            try {
108
                $request = $request->withAttribute('tree', null);
109
110
                return $this->unhandledExceptionResponse($request, $exception);
111
            } catch (Throwable $e) {
112
                // That didn't work.  Try something else.
113
            }
114
115
            // Show the exception in an error page (if we can).
116
            try {
117
                $this->layout = 'layouts/error';
118
119
                return $this->unhandledExceptionResponse($request, $exception);
120
            } catch (Throwable $e) {
121
                // That didn't work.  Try something else.
122
            }
123
124
            // Show a stack dump.
125
            return response((string) $exception, StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR);
126
        }
127
    }
128
129
    /**
130
     * @param ServerRequestInterface $request
131
     * @param HttpException          $exception
132
     *
133
     * @return ResponseInterface
134
     */
135
    private function httpExceptionResponse(ServerRequestInterface $request, HttpException $exception): ResponseInterface
136
    {
137
        $tree = $request->getAttribute('tree');
138
139
        $default = Site::getPreference('DEFAULT_GEDCOM');
140
        $tree = $tree ?? $this->tree_service->all()[$default] ?? $this->tree_service->all()->first();
141
142
        if ($request->getHeaderLine('X-Requested-With') !== '') {
143
            $this->layout = 'layouts/ajax';
144
        }
145
146
        return $this->viewResponse('components/alert-danger', [
147
            'alert' => $exception->getMessage(),
148
            'title' => $exception->getMessage(),
149
            'tree'  => $tree,
150
        ], $exception->getCode());
151
    }
152
153
    /**
154
     * @param ServerRequestInterface $request
155
     * @param Throwable              $exception
156
     *
157
     * @return ResponseInterface
158
     */
159
    private function thirdPartyExceptionResponse(ServerRequestInterface $request, Throwable $exception): ResponseInterface
160
    {
161
        $tree = $request->getAttribute('tree');
162
163
        $default = Site::getPreference('DEFAULT_GEDCOM');
164
        $tree = $tree ?? $this->tree_service->all()[$default] ?? $this->tree_service->all()->first();
165
166
        if ($request->getHeaderLine('X-Requested-With') !== '') {
167
            $this->layout = 'layouts/ajax';
168
        }
169
170
        return $this->viewResponse('components/alert-danger', [
171
            'alert' => $exception->getMessage(),
172
            'title' => $exception->getMessage(),
173
            'tree'  => $tree,
174
        ], StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR);
175
    }
176
177
    /**
178
     * @param ServerRequestInterface $request
179
     * @param Throwable              $exception
180
     *
181
     * @return ResponseInterface
182
     */
183
    private function unhandledExceptionResponse(ServerRequestInterface $request, Throwable $exception): ResponseInterface
184
    {
185
        $this->layout = 'layouts/default';
186
187
        // Create a stack dump for the exception
188
        $base_path = dirname(__DIR__, 3);
189
        $trace     = $exception->getMessage() . ' ' . $exception->getFile() . ':' . $exception->getLine() . PHP_EOL . $exception->getTraceAsString();
190
        $trace     = str_replace($base_path, '…', $trace);
191
        $trace     = e($trace);
192
        $trace     = preg_replace('/^.*modules_v4.*$/m', '<b>$0</b>', $trace);
193
194
        try {
195
            Log::addErrorLog($trace);
196
        } catch (Throwable $exception) {
197
            // Must have been a problem with the database.  Nothing we can do here.
198
        }
199
200
        if ($request->getHeaderLine('X-Requested-With') !== '') {
201
            // If this was a GET request, then we were probably fetching HTML to display, for
202
            // example a chart or tab.
203
            if ($request->getMethod() === RequestMethodInterface::METHOD_GET) {
204
                $status_code = StatusCodeInterface::STATUS_OK;
205
            } else {
206
                $status_code = StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR;
207
            }
208
209
            return response(view('components/alert-danger', ['alert' => $trace]), $status_code);
210
        }
211
212
        try {
213
            // Try with a full header/menu
214
            return $this->viewResponse('errors/unhandled-exception', [
215
                'title'   => 'Error',
216
                'error'   => $trace,
217
                'request' => $request,
218
                'tree'    => $request->getAttribute('tree'),
219
            ], StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR);
220
        } catch (Throwable $ex) {
221
            // Try with a minimal header/menu
222
            return $this->viewResponse('errors/unhandled-exception', [
223
                'title'   => 'Error',
224
                'error'   => $trace,
225
                'request' => $request,
226
                'tree'    => null,
227
            ], StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR);
228
        }
229
    }
230
}
231