Passed
Pull Request — main (#20)
by Stéphane
02:17
created

ValidationExceptionMapper::mapGeneric()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 2
c 0
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 2
nc 1
nop 2
crap 2
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;
24 7
            $current = $current->getPrevious();
25
        }
26
27 7
        $lastError = end($chain);
28
29 7
        if ($lastError instanceof SchemaMismatch) {
30 1
            return $this->mapSchemaMismatch($lastError);
31 6
        } elseif ($lastError instanceof InvalidSchema) {
32 1
            return new ApiSchemaException($lastError);
33 5
        } elseif ($lastError instanceof ValidationFailed) {
34 2
            return $this->mapGeneric($chain, $lastError);
35
        }
36
37 3
        return null;
38
    }
39
40 2
    private function mapGeneric(array $chain, ValidationFailed $lastError): GenericException
41
    {
42 2
        $previousError = prev($chain);
43 2
        return new GenericException($previousError instanceof InvalidQueryArgs ? $previousError : $lastError);
44
    }
45
46 1
    private function mapSchemaMismatch(SchemaMismatch $lastError): DataSchemaException
47
    {
48 1
        $breadCrumb = $lastError->dataBreadCrumb();
49 1
        if ($breadCrumb instanceof BreadCrumb) {
0 ignored issues
show
introduced by
$breadCrumb is always a sub-type of League\OpenAPIValidation\Schema\BreadCrumb.
Loading history...
50 1
            $crumbs = implode('.', $breadCrumb->buildChain());
51
        }
52
53 1
        return new DataSchemaException($lastError->data(), $crumbs ?? '', $lastError);
54
    }
55
}
56