Completed
Push — master ( e221c0...5a5b2e )
by Matze
05:22
created

CatchUserException::processException()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 30
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 4.0218

Importance

Changes 7
Bugs 0 Features 2
Metric Value
c 7
b 0
f 2
dl 0
loc 30
ccs 16
cts 18
cp 0.8889
rs 8.5806
cc 4
eloc 21
nc 4
nop 2
crap 4.0218
1
<?php
2
3
namespace BrainExe\Core\Middleware;
4
5
use BrainExe\Core\Annotations\Middleware;
6
use BrainExe\Core\Application\UserException;
7
use BrainExe\Core\Traits\LoggerTrait;
8
use Throwable;
9
use Exception;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\HttpFoundation\Response;
12
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
13
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
14
15
/**
16
 * @Middleware("Middleware.CatchUserException")
17
 */
18
class CatchUserException extends AbstractMiddleware
19
{
20
21
    use LoggerTrait;
22
23
    /**
24
     * {@inheritdoc}
25
     */
26 7
    public function processException(Request $request, Throwable $exception)
27
    {
28 7
        if ($exception instanceof ResourceNotFoundException) {
29 2
            $exception = new UserException(sprintf('Page not found: %s', $request->getRequestUri()), 0, $exception);
30 2
            $response  = new Response('', 404);
31
        } elseif ($exception instanceof MethodNotAllowedException) {
32 1
            $exception = new UserException(
33
                sprintf(
34 1
                    'You are not allowed to access the page. Allowed methods: %s',
35 1
                    implode(',', $exception->getAllowedMethods())
36
                ),
37 1
                0,
38
                $exception
39
            );
40 1
            $response = new Response('', 405);
41
        } elseif ($exception instanceof UserException) {
42
            // just pass a UserException to Frontend
43 1
            $response  = new Response('', 200);
44
        } else {
45 3
            $exception = new UserException($exception->getMessage(), 0, $exception);
46 3
            $response  = new Response('', 500);
47
        }
48
49 7
        $this->error($exception->getMessage());
50 7
        $this->error($exception->getTraceAsString());
51
52 7
        $this->setMessage($exception, $response);
53
54 7
        return $response;
55
    }
56
57
    /**
58
     * @param Exception $exception
59
     * @param Response $response
60
     */
61 7
    protected function setMessage(Exception $exception, Response $response)
62
    {
63 7
        $message = $exception->getMessage() ?: _('An error occurred');
64 7
        $response->headers->set('X-Flash-Type', 'danger');
65 7
        $response->headers->set('X-Flash-Message', $message);
66 7
        $response->setContent($message);
67 7
    }
68
}
69