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

CatchUserException::setMessage()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 7
ccs 6
cts 6
cp 1
rs 9.4286
cc 2
eloc 5
nc 2
nop 2
crap 2
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