Completed
Pull Request — master (#61)
by Michal
02:15
created

JsonOutput::validate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 8
cts 8
cp 1
rs 9.7998
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Tomaj\NetteApi\Output;
6
7
use Tomaj\NetteApi\Response\JsonApiResponse;
8
use Tomaj\NetteApi\Response\ResponseInterface;
9
use Tomaj\NetteApi\Validation\JsonSchemaValidator;
10
use Tomaj\NetteApi\ValidationResult\ValidationResult;
11
use Tomaj\NetteApi\ValidationResult\ValidationResultInterface;
12
13
class JsonOutput implements OutputInterface
14
{
15
    private $code;
16
17
    private $schema;
18
19 15
    public function __construct(int $code, $schema)
20
    {
21 15
        $this->code = $code;
22 15
        $this->schema = $schema;
23 15
    }
24
25 15
    public function validate(ResponseInterface $response): ValidationResultInterface
26
    {
27 15
        if (!$response instanceof JsonApiResponse) {
28 3
            return new ValidationResult(ValidationResult::STATUS_ERROR);
29
        }
30 12
        if ($this->code !== $response->getCode()) {
31 3
            return new ValidationResult(ValidationResult::STATUS_ERROR, ['Response code doesn\'t match']);
32
        }
33
34 9
        $value = json_decode(json_encode($response->getPayload()));
35
36 9
        $schemaValidator = new JsonSchemaValidator();
37 9
        return $schemaValidator->validate($value, $this->schema);
38
    }
39
}
40