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) { |
|
|
|
|
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
|
|
|
|
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.