Completed
Push — master ( ad24bf...d452c0 )
by Ricardo
168:19 queued 133:59
created

ValidationResponseFactory::create()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 11
cts 11
cp 1
rs 9.7333
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php declare(strict_types=1);
2
3
namespace RicardoFiorani\Validator\Response;
4
5
use Psr\Http\Message\ResponseInterface;
6
use RicardoFiorani\Validator\Response\Error\Collection\ErrorCollection;
7
use RicardoFiorani\Validator\Response\Error\ValidationError;
8
9
class ValidationResponseFactory
10
{
11 6
    public function create(ResponseInterface $response): ValidationResponseInterface
12
    {
13 6
        $jsonResponse = (string)$response->getBody();
14 6
        $jsonResponseObject = json_decode($jsonResponse);
15
16 6
        $errorCollection = $jsonResponseObject->valid ?
17 3
            new ErrorCollection() :
18 6
            $this->createErrorCollectionFromJsonResponseObject($jsonResponseObject);
19
20 6
        return new ValidationResponse(
21 6
            $jsonResponseObject->source,
22 6
            $jsonResponseObject->version,
23 6
            $jsonResponseObject->valid,
24 6
            $errorCollection
25
        );
26
    }
27
28 3
    private function createErrorCollectionFromJsonResponseObject(\stdClass $jsonResponseObject): ErrorCollection
29
    {
30 3
        $collection = new ErrorCollection();
31
32 3
        foreach ($jsonResponseObject->errors as $error) {
33 3
            $collection->add(
34 3
                new ValidationError(
35 3
                    $error->code,
36 3
                    $error->error,
37 3
                    $error->help,
38 3
                    $error->line,
39 3
                    $error->col
40
                )
41
            );
42
        }
43
44 3
        return $collection;
45
    }
46
}
47