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\NormalizerInterface; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @author Christian Flothmann <[email protected]> |
21
|
|
|
* |
22
|
|
|
* @internal |
23
|
|
|
*/ |
24
|
|
|
final class FlattenExceptionNormalizer implements NormalizerInterface |
25
|
|
|
{ |
26
|
|
|
private $messagesMap; |
27
|
|
|
private $debug; |
28
|
|
|
private $rfc7807; |
29
|
|
|
|
30
|
29 |
|
public function __construct(ExceptionValueMap $messagesMap, bool $debug, bool $rfc7807) |
31
|
|
|
{ |
32
|
29 |
|
$this->messagesMap = $messagesMap; |
33
|
29 |
|
$this->debug = $debug; |
34
|
29 |
|
$this->rfc7807 = $rfc7807; |
35
|
29 |
|
} |
36
|
|
|
|
37
|
11 |
|
public function normalize($exception, $format = null, array $context = []) |
38
|
|
|
{ |
39
|
11 |
|
if (isset($context['status_code'])) { |
40
|
|
|
$statusCode = $context['status_code']; |
41
|
|
|
} else { |
42
|
11 |
|
$statusCode = $exception->getStatusCode(); |
43
|
|
|
} |
44
|
|
|
|
45
|
11 |
|
$showMessage = $this->messagesMap->resolveFromClassName($exception->getClass()); |
46
|
|
|
|
47
|
11 |
View Code Duplication |
if ($showMessage || $this->debug) { |
48
|
10 |
|
$message = $exception->getMessage(); |
49
|
|
|
} else { |
50
|
1 |
|
$message = Response::$statusTexts[$statusCode] ?? 'error'; |
51
|
|
|
} |
52
|
|
|
|
53
|
11 |
|
if ($this->rfc7807) { |
54
|
2 |
|
if ('json' === $format) { |
55
|
1 |
|
$exception->setHeaders($exception->getHeaders() + ['Content-Type' => 'application/problem+json']); |
56
|
1 |
|
} elseif ('xml' === $format) { |
57
|
1 |
|
$exception->setHeaders($exception->getHeaders() + ['Content-Type' => 'application/problem+xml']); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
return [ |
61
|
2 |
|
'type' => $context['type'] ?? 'https://tools.ietf.org/html/rfc2616#section-10', |
62
|
2 |
|
'title' => $context['title'] ?? 'An error occurred', |
63
|
2 |
|
'status' => $statusCode, |
64
|
2 |
|
'detail' => $message, |
65
|
|
|
]; |
66
|
|
|
} else { |
67
|
|
|
return [ |
68
|
9 |
|
'code' => $statusCode, |
69
|
9 |
|
'message' => $message, |
70
|
|
|
]; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|
74
|
18 |
|
public function supportsNormalization($data, $format = null) |
75
|
|
|
{ |
76
|
18 |
|
return $data instanceof FlattenException; |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|