Completed
Pull Request — master (#81)
by Michal
01:58
created

JsonOutput::getSchema()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
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