Completed
Pull Request — master (#10)
by Matze
07:31
created

CatchUserException   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Test Coverage

Coverage 100%

Importance

Changes 6
Bugs 0 Features 1
Metric Value
wmc 6
c 6
b 0
f 1
lcom 0
cbo 5
dl 0
loc 51
ccs 28
cts 28
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A setMessage() 0 7 2
B processException() 0 30 4
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 Exception;
9
use Symfony\Component\HttpFoundation\Request;
10
use Symfony\Component\HttpFoundation\Response;
11
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
12
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
13
14
/**
15
 * @Middleware("Middleware.CatchUserException")
16
 */
17
class CatchUserException extends AbstractMiddleware
18
{
19
20
    use LoggerTrait;
21
22
    /**
23
     * {@inheritdoc}
24
     */
25 5
    public function processException(Request $request, Exception $exception)
26
    {
27 5
        if ($exception instanceof ResourceNotFoundException) {
28 2
            $exception = new UserException(sprintf('Page not found: %s', $request->getRequestUri()), 0, $exception);
29 2
            $response  = new Response('', 404);
30 5
        } elseif ($exception instanceof MethodNotAllowedException) {
31 1
            $exception = new UserException(
32 1
                sprintf(
33 1
                    'You are not allowed to access the page. Allowed methods: %s',
34 1
                    implode(',', $exception->getAllowedMethods())
35 1
                ),
36 1
                0,
37
                $exception
38 1
            );
39 1
            $response = new Response('', 405);
40 3
        } elseif ($exception instanceof UserException) {
41
            // just pass a UserException to Frontend
42 1
            $response  = new Response('', 500);
43 1
        } else {
44 1
            $exception = new UserException($exception->getMessage(), 0, $exception);
45 1
            $response  = new Response('', 500);
46
        }
47
48 5
        $this->error($exception->getMessage());
49 5
        $this->error($exception->getTraceAsString());
50
51 5
        $this->setMessage($exception, $response);
52
53 5
        return $response;
54
    }
55
56
    /**
57
     * @param Exception $exception
58
     * @param Response $response
59
     */
60 5
    protected function setMessage(Exception $exception, Response $response)
61
    {
62 5
        $message = $exception->getMessage() ?: _('An error occurred');
63 5
        $response->headers->set('X-Flash-Type', 'danger');
64 5
        $response->headers->set('X-Flash-Message', $message);
65 5
        $response->setContent($message);
66 5
    }
67
}
68