1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Overblog\GraphQLBundle\Error; |
6
|
|
|
|
7
|
|
|
use GraphQL\Error\ClientAware as ClientAwareInterface; |
8
|
|
|
|
9
|
|
|
final class ExceptionConverter implements ExceptionConverterInterface |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @var array<string, string> |
13
|
|
|
*/ |
14
|
|
|
private $exceptionMap; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @var bool |
18
|
|
|
*/ |
19
|
|
|
private $mapExceptionsToParent; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @param array<string, string> $exceptionMap |
23
|
|
|
*/ |
24
|
112 |
|
public function __construct(array $exceptionMap, bool $mapExceptionsToParent = false) |
25
|
|
|
{ |
26
|
112 |
|
$this->exceptionMap = $exceptionMap; |
27
|
112 |
|
$this->mapExceptionsToParent = $mapExceptionsToParent; |
28
|
112 |
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* {@inheritdoc} |
32
|
|
|
*/ |
33
|
33 |
|
public function convertException(\Throwable $exception): \Throwable |
34
|
|
|
{ |
35
|
33 |
|
if ($exception instanceof ClientAwareInterface) { |
36
|
13 |
|
return $exception; |
37
|
|
|
} |
38
|
|
|
|
39
|
20 |
|
$errorClass = $this->findErrorClass($exception); |
40
|
|
|
|
41
|
20 |
|
if (null !== $errorClass) { |
42
|
10 |
|
return new $errorClass($exception->getMessage(), $exception->getCode(), $exception); |
43
|
|
|
} |
44
|
|
|
|
45
|
10 |
|
return $exception; |
46
|
|
|
} |
47
|
|
|
|
48
|
20 |
|
private function findErrorClass(\Throwable $exception): ?string |
49
|
|
|
{ |
50
|
20 |
|
$exceptionClass = \get_class($exception); |
51
|
|
|
|
52
|
20 |
|
if (isset($this->exceptionMap[$exceptionClass])) { |
53
|
8 |
|
return $this->exceptionMap[$exceptionClass]; |
54
|
|
|
} |
55
|
|
|
|
56
|
12 |
|
if ($this->mapExceptionsToParent) { |
57
|
4 |
|
return $this->findErrorClassUsingParentException($exception); |
58
|
|
|
} |
59
|
|
|
|
60
|
8 |
|
return null; |
61
|
|
|
} |
62
|
|
|
|
63
|
4 |
|
private function findErrorClassUsingParentException(\Throwable $exception): ?string |
64
|
|
|
{ |
65
|
4 |
|
foreach ($this->exceptionMap as $exceptionClass => $errorExceptionClass) { |
66
|
2 |
|
if ($exception instanceof $exceptionClass) { |
67
|
2 |
|
return $errorExceptionClass; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
71
|
2 |
|
return null; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|