Completed
Pull Request — 2.x (#2161)
by Christian
03:47
created

supportsNormalization()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
1
<?php
2
3
/*
4
 * This file is part of the FOSRestBundle package.
5
 *
6
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace FOS\RestBundle\Serializer\Normalizer;
13
14
use FOS\RestBundle\Util\ExceptionValueMap;
15
use Symfony\Component\ErrorHandler\Exception\FlattenException;
16
use Symfony\Component\HttpFoundation\Response;
17
use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
18
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
19
20
/**
21
 * @author Christian Flothmann <[email protected]>
22
 *
23
 * @internal
24
 */
25
final class FlattenExceptionNormalizer implements CacheableSupportsMethodInterface, NormalizerInterface
26
{
27
    private $messagesMap;
28
    private $debug;
29
    private $rfc7807;
30
31 26
    public function __construct(ExceptionValueMap $messagesMap, bool $debug, bool $rfc7807)
32
    {
33 26
        $this->messagesMap = $messagesMap;
34 26
        $this->debug = $debug;
35 26
        $this->rfc7807 = $rfc7807;
36 26
    }
37
38 7
    public function normalize($exception, $format = null, array $context = [])
39
    {
40 7
        if (isset($context['status_code'])) {
41
            $statusCode = $context['status_code'];
42
        } else {
43 7
            $statusCode = $exception->getStatusCode();
44
        }
45
46 7
        $showMessage = $this->messagesMap->resolveFromClassName($exception->getClass());
47
48 7 View Code Duplication
        if ($showMessage || $this->debug) {
49 6
            $message = $exception->getMessage();
50
        } else {
51 1
            $message = Response::$statusTexts[$statusCode] ?? 'error';
52
        }
53
54 7
        if ($this->rfc7807) {
55
            return [
56 2
                'type' => $context['type'] ?? 'https://tools.ietf.org/html/rfc2616#section-10',
57 2
                'title' => $context['title'] ?? 'An error occurred',
58 2
                'status' => $statusCode,
59 2
                'detail' => $message,
60
            ];
61
        } else {
62
            return [
63 5
                'code' => $statusCode,
64 5
                'message' => $message,
65
            ];
66
        }
67
    }
68
69 20
    public function supportsNormalization($data, $format = null)
70
    {
71 20
        return $data instanceof FlattenException;
72
    }
73
74 20
    public function hasCacheableSupportsMethod(): bool
75
    {
76 20
        return true;
77
    }
78
}
79