Passed
Pull Request — main (#20)
by Stéphane
12:21
created

ValidationExceptionMapper::map()   B

Complexity

Conditions 7
Paths 10

Size

Total Lines 26
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 7

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 26
ccs 18
cts 18
cp 1
rs 8.8333
cc 7
nc 10
nop 1
crap 7
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 7
    public function map(Throwable $error): ?ValidationException
19
    {
20 7
        $chain = [];
21 7
        $current = $error;
22 7
        while ($current) {
23 7
            $chain[$current::class] = $current;
24 7
            $current = $current->getPrevious();
25
        }
26
27 7
        $lastError = end($chain);
28
29 7
        if ($lastError instanceof SchemaMismatch) {
30 1
            $breadCrumb = $lastError->dataBreadCrumb();
31 1
            if ($breadCrumb instanceof BreadCrumb) {
0 ignored issues
show
introduced by
$breadCrumb is always a sub-type of League\OpenAPIValidation\Schema\BreadCrumb.
Loading history...
32 1
                $crumbs = implode('.', $breadCrumb->buildChain());
33
            }
34
35 1
            return new DataSchemaException($lastError->data(), $crumbs ?? '', $lastError);
36 6
        } elseif ($lastError instanceof InvalidSchema) {
37 1
            return new ApiSchemaException($lastError);
38 5
        } elseif ($lastError instanceof ValidationFailed) {
39 2
            $previousError = prev($chain);
40 2
            return new GenericException($previousError instanceof InvalidQueryArgs ? $previousError : $lastError);
41
        }
42
43 3
        return null;
44
    }
45
}
46