Completed
Pull Request — master (#83)
by Michal
01:41
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 extends AbstractOutput
14
{
15
    private $schema;
16
17 15
    public function __construct(int $code, string $schema, string $description = '')
18
    {
19 15
        parent::__construct($code, $description);
20 15
        $this->schema = $schema;
21 15
    }
22
23 15
    public function validate(ResponseInterface $response): ValidationResultInterface
24
    {
25 15
        if (!$response instanceof JsonApiResponse) {
26 3
            return new ValidationResult(ValidationResult::STATUS_ERROR);
27
        }
28 12
        if ($this->code !== $response->getCode()) {
29 3
            return new ValidationResult(ValidationResult::STATUS_ERROR, ['Response code doesn\'t match']);
30
        }
31
32 9
        $value = json_decode(json_encode($response->getPayload()));
33
34 9
        $schemaValidator = new JsonSchemaValidator();
35 9
        return $schemaValidator->validate($value, $this->schema);
36
    }
37
38
    public function getSchema(): string
39
    {
40
        return $this->schema;
41
    }
42
}
43