1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace CHStudio\Raven\Bridge\LeagueOpenAPIValidation\Exception; |
4
|
|
|
|
5
|
|
|
use CHStudio\Raven\Validator\Exception\ApiSchemaException; |
6
|
|
|
use CHStudio\Raven\Validator\Exception\DataSchemaException; |
7
|
|
|
use CHStudio\Raven\Validator\Exception\GenericException; |
8
|
|
|
use CHStudio\Raven\Validator\Exception\ValidationException; |
9
|
|
|
use League\OpenAPIValidation\PSR7\Exception\Validation\InvalidQueryArgs; |
10
|
|
|
use League\OpenAPIValidation\PSR7\Exception\ValidationFailed; |
11
|
|
|
use League\OpenAPIValidation\Schema\BreadCrumb; |
12
|
|
|
use League\OpenAPIValidation\Schema\Exception\InvalidSchema; |
13
|
|
|
use League\OpenAPIValidation\Schema\Exception\SchemaMismatch; |
14
|
|
|
use Throwable; |
15
|
|
|
|
16
|
|
|
class ValidationExceptionMapper |
17
|
|
|
{ |
18
|
8 |
|
public function map(Throwable $error): ?ValidationException |
19
|
|
|
{ |
20
|
8 |
|
$chain = []; |
21
|
8 |
|
$current = $error; |
22
|
8 |
|
while ($current) { |
23
|
8 |
|
$chain[] = $current; |
24
|
8 |
|
$current = $current->getPrevious(); |
25
|
|
|
} |
26
|
|
|
|
27
|
8 |
|
$lastError = end($chain); |
28
|
|
|
|
29
|
8 |
|
if ($lastError instanceof SchemaMismatch) { |
30
|
1 |
|
return $this->mapSchemaMismatch($lastError); |
31
|
7 |
|
} elseif ($lastError instanceof InvalidSchema) { |
32
|
1 |
|
return new ApiSchemaException($lastError); |
33
|
6 |
|
} elseif ($lastError instanceof ValidationFailed) { |
34
|
2 |
|
return $this->mapGeneric($chain, $lastError); |
35
|
|
|
} |
36
|
|
|
|
37
|
4 |
|
return null; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param array<Throwable> $chain |
42
|
|
|
*/ |
43
|
2 |
|
private function mapGeneric(array $chain, ValidationFailed $lastError): GenericException |
44
|
|
|
{ |
45
|
2 |
|
$previousError = prev($chain); |
46
|
2 |
|
return new GenericException($previousError instanceof InvalidQueryArgs ? $previousError : $lastError); |
47
|
|
|
} |
48
|
|
|
|
49
|
1 |
|
private function mapSchemaMismatch(SchemaMismatch $lastError): DataSchemaException |
50
|
|
|
{ |
51
|
1 |
|
$breadCrumb = $lastError->dataBreadCrumb(); |
52
|
1 |
|
if ($breadCrumb instanceof BreadCrumb) { |
|
|
|
|
53
|
1 |
|
$crumbs = implode('.', $breadCrumb->buildChain()); |
54
|
|
|
} |
55
|
|
|
|
56
|
1 |
|
return new DataSchemaException($lastError->data(), $crumbs ?? '', $lastError); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|