Completed
Pull Request — master (#61)
by Michal
04:05
created

JsonInputParam::getValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 2
1
<?php
2
3
namespace Tomaj\NetteApi\Params;
4
5
use Exception;
6
use JsonSchema\Validator;
7
use Nette\Application\UI\Form;
8
use Nette\Forms\Controls\BaseControl;
9
10
class JsonInputParam extends InputParam
11
{
12
    protected $type = self::TYPE_POST_JSON;
13
14
    private $schemaValidator;
15
16
    private $schema;
17
18 9
    public function __construct(string $key, string $schema)
19
    {
20 9
        parent::__construct($key);
21 9
        $this->schemaValidator = new Validator();
22 9
        $this->schema = $schema;
23 9
    }
24
25 3
    public function setMulti(): InputParam
26
    {
27 3
        throw new Exception('Cannot use multi json input param');
28
    }
29
30 3
    public function getValue()
31
    {
32 3
        $input = file_get_contents("php://input") ?: $this->default;
33 3
        return json_decode($input, true);
34
    }
35
36 3
    public function isValid(): bool
37
    {
38 3
        $value = $this->getValue();
39 3
        if (json_last_error()) {
40 3
            $this->errors[] = json_last_error_msg();
41 3
            return false;
42
        }
43
44 3
        if (!$value && $this->isRequired() === self::OPTIONAL) {
45 3
            return true;
46
        }
47
48 3
        $value = json_decode(json_encode($value));
49 3
        $this->schemaValidator->validate($value, json_decode($this->schema));
50
51 3
        foreach ($this->schemaValidator->getErrors() as $error) {
52 3
            $this->errors[] = $error['message'];
53
        }
54
55 3
        return $this->schemaValidator->isValid();
56
    }
57
58 3
    protected function addFormInput(Form $form, string $key): BaseControl
59
    {
60 3
        $this->description .= '<div id="show_schema_link"><a href="#" onclick="document.getElementById(\'json_schema\').style.display = \'block\'; document.getElementById(\'show_schema_link\').style.display = \'none\'; return false;">Show schema</a></div>
61
                            <div id="json_schema" style="display: none;">
62
                            <div><a href="#" onclick="document.getElementById(\'show_schema_link\').style.display = \'block\'; document.getElementById(\'json_schema\').style.display = \'none\'; return false;">Hide schema</a></div>'
63 3
            . nl2br(str_replace(' ', '&nbsp;', json_encode(json_decode($this->schema), JSON_PRETTY_PRINT))) . '</div>';
64
65 3
        return $form->addTextArea('post_raw', $this->getParamLabel())
66 3
            ->setHtmlAttribute('rows', 10);
67
    }
68
}
69