ValidationExceptionMapper::map()   A
last analyzed

Complexity

Conditions 5
Paths 8

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 20
ccs 14
cts 14
cp 1
rs 9.5222
cc 5
nc 8
nop 1
crap 5
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) {
0 ignored issues
show
introduced by
$breadCrumb is always a sub-type of League\OpenAPIValidation\Schema\BreadCrumb.
Loading history...
53 1
            $crumbs = implode('.', $breadCrumb->buildChain());
54
        }
55
56 1
        return new DataSchemaException($lastError->data(), $crumbs ?? '', $lastError);
57
    }
58
}
59