Completed
Pull Request — master (#61)
by Tomas
02:14
created

JsonOutput::validate()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 28

Duplication

Lines 8
Ratio 28.57 %

Code Coverage

Tests 17
CRAP Score 6

Importance

Changes 0
Metric Value
dl 8
loc 28
c 0
b 0
f 0
ccs 17
cts 17
cp 1
rs 8.8497
cc 6
nc 6
nop 1
crap 6
1
<?php
2
3
namespace Tomaj\NetteApi\Output;
4
5
use JsonSchema\Validator;
6
use Tomaj\NetteApi\Response\JsonApiResponse;
7
use Tomaj\NetteApi\Response\ResponseInterface;
8
use Tomaj\NetteApi\ValidationResult\ValidationResult;
9
use Tomaj\NetteApi\ValidationResult\ValidationResultInterface;
10
11
class JsonOutput implements OutputInterface
12
{
13
    private $schemaValidator;
14
15
    private $code;
16
17
    private $schema;
18
19 15
    public function __construct(int $code, $schema)
20
    {
21 15
        $this->schemaValidator = new Validator();
22 15
        $this->code = $code;
23 15
        $this->schema = $schema;
24 15
    }
25
26 15
    public function validate(ResponseInterface $response): ValidationResultInterface
27
    {
28 15
        if (!$response instanceof JsonApiResponse) {
29 3
            return new ValidationResult(ValidationResult::STATUS_ERROR);
30
        }
31 12
        if ($this->code !== $response->getCode()) {
32 3
            return new ValidationResult(ValidationResult::STATUS_ERROR, ['Response code doesn\'t match']);
33
        }
34
35 9
        $value = json_decode(json_encode($response->getPayload()));
36 9
        $this->schemaValidator->validate($value, json_decode($this->schema));
37
38 9
        if ($this->schemaValidator->isValid()) {
39 6
            return new ValidationResult(ValidationResult::STATUS_OK);
40
        }
41
42 3
        $errors = [];
43 3 View Code Duplication
        foreach ($this->schemaValidator->getErrors() as $error) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
44 3
            $errorMessage = '';
45 3
            if ($error['property']) {
46 3
                $errorMessage .= '[Property ' . $error['property'] . '] ';
47
            }
48 3
            $errorMessage .= $error['message'];
49 3
            $errors[] = $errorMessage;
50
        }
51
52 3
        return new ValidationResult(ValidationResult::STATUS_ERROR, $errors);
53
    }
54
}
55