Completed
Pull Request — master (#55)
by Michal
05:45
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 3
1
<?php
2
3
namespace Tomaj\NetteApi\Params;
4
5
use JsonSchema\Constraints\Constraint;
6
use JsonSchema\Exception\InvalidSchemaException;
7
use JsonSchema\Validator;
8
9
class JsonInputParam extends InputParam
10
{
11
    const TYPE_POST_JSON  = 'POST_JSON';
12
13
    private $schemaValidator;
14
15
    private $schema;
16
17
    public function __construct($key, string $schema, bool $required = self::OPTIONAL)
18
    {
19
        parent::__construct(self::TYPE_POST_JSON, $key, $required);
20
21
        $this->schemaValidator = new Validator();
22
        $this->schema = $schema;
23
    }
24
25
    public function getSchema()
26
    {
27
        return $this->schema;
28
    }
29
30
    public function getValue()
31
    {
32
        $input = file_get_contents("php://input");
33
        return json_decode($input, true);
34
    }
35
36
    public function isValid()
37
    {
38
        $value = $this->getValue();
39
        if (!$value && $this->isRequired() === self::OPTIONAL) {
40
            return true;
41
        }
42
        $value = json_decode(json_encode($value));
43
        $this->schemaValidator->validate($value, json_decode($this->schema));
44
        return $this->schemaValidator->isValid();
45
    }
46
}
47