Completed
Pull Request — master (#56)
by Michal
12:52
created

JsonInputParam::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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