Completed
Pull Request — master (#55)
by Michal
06:55
created

JsonInputParam::getValue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 0
cts 5
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
namespace Tomaj\NetteApi\Params;
4
5
6
use JsonSchema\Constraints\Constraint;
7
use JsonSchema\Exception\InvalidSchemaException;
8
use JsonSchema\Validator;
9
10
class JsonInputParam extends InputParam
11
{
12
    const TYPE_POST_JSON  = 'POST_JSON';
13
14
    private $schemaValidator;
15
16
    private $schema;
17
18
    public function __construct($key, bool $required = self::OPTIONAL, string $schema)
19
    {
20
        parent::__construct(self::TYPE_POST_JSON, $key, $required);
21
22
        $this->schemaValidator = new Validator();
23
        $this->schema = $schema;
24
    }
25
26
    public function getSchema()
27
    {
28
        return $this->schema;
29
    }
30
31
    public function getValue()
32
    {
33
        $input = file_get_contents("php://input");
34
        return json_decode($input, true);
35
    }
36
37
    public function isValid()
38
    {
39
        $value = $this->getValue();
40
        if (!$value && $this->isRequired() === self::OPTIONAL) {
41
            return true;
42
        }
43
        $value = json_decode(json_encode($value));
44
        $this->schemaValidator->validate($value, json_decode($this->schema));
45
        return $this->schemaValidator->isValid();
46
    }
47
}
48