|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the API Platform project. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Kévin Dunglas <[email protected]> |
|
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 ApiPlatform\Core\Hal\Action; |
|
13
|
|
|
|
|
14
|
|
|
use ApiPlatform\Core\Exception\InvalidArgumentException; |
|
15
|
|
|
use Symfony\Component\Debug\Exception\FlattenException; |
|
16
|
|
|
use Symfony\Component\HttpFoundation\JsonResponse; |
|
17
|
|
|
use Symfony\Component\Serializer\Exception\ExceptionInterface; |
|
18
|
|
|
use Symfony\Component\Serializer\Normalizer\NormalizerInterface; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* Renders a normalized exception for a given {@see \Symfony\Component\Debug\Exception\FlattenException}. |
|
22
|
|
|
* |
|
23
|
|
|
* @author Baptiste Meyer <[email protected]> |
|
24
|
|
|
* @author Armouche Hamza <[email protected]> |
|
25
|
|
|
*/ |
|
26
|
|
View Code Duplication |
final class ExceptionAction |
|
|
|
|
|
|
27
|
|
|
{ |
|
28
|
|
|
private $normalizer; |
|
29
|
|
|
|
|
30
|
|
|
public function __construct(NormalizerInterface $normalizer) |
|
31
|
|
|
{ |
|
32
|
|
|
$this->normalizer = $normalizer; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* Converts a an exception to a JSON response. |
|
37
|
|
|
*/ |
|
38
|
|
|
public function __invoke(FlattenException $exception) : JsonResponse |
|
39
|
|
|
{ |
|
40
|
|
|
$exceptionClass = $exception->getClass(); |
|
41
|
|
|
if ( |
|
42
|
|
|
is_a($exceptionClass, ExceptionInterface::class, true) || |
|
43
|
|
|
is_a($exceptionClass, InvalidArgumentException::class, true) |
|
44
|
|
|
) { |
|
45
|
|
|
$exception->setStatusCode(JsonResponse::HTTP_BAD_REQUEST); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
$headers = $exception->getHeaders(); |
|
49
|
|
|
$headers['Content-Type'] = 'application/hal+json'; |
|
50
|
|
|
|
|
51
|
|
|
return new JsonResponse($this->normalizer->normalize($exception, 'hal-error'), $exception->getStatusCode(), $headers); |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.