1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Tomaj\NetteApi\Params; |
6
|
|
|
|
7
|
|
|
use Exception; |
8
|
|
|
use Nette\Application\UI\Form; |
9
|
|
|
use Nette\Forms\Controls\BaseControl; |
10
|
|
|
use Tomaj\NetteApi\Validation\JsonSchemaValidator; |
11
|
|
|
use Tomaj\NetteApi\ValidationResult\ValidationResult; |
12
|
|
|
use Tomaj\NetteApi\ValidationResult\ValidationResultInterface; |
13
|
|
|
|
14
|
|
|
class JsonInputParam extends InputParam |
15
|
|
|
{ |
16
|
|
|
protected $type = self::TYPE_POST_JSON; |
17
|
|
|
|
18
|
|
|
private $schema; |
19
|
|
|
|
20
|
9 |
|
public function __construct(string $key, string $schema) |
21
|
|
|
{ |
22
|
9 |
|
parent::__construct($key); |
23
|
9 |
|
$this->schema = $schema; |
24
|
9 |
|
} |
25
|
|
|
|
26
|
3 |
|
public function setMulti(): InputParam |
27
|
|
|
{ |
28
|
3 |
|
throw new Exception('Cannot use multi json input param'); |
29
|
|
|
} |
30
|
|
|
|
31
|
3 |
|
public function getValue() |
32
|
|
|
{ |
33
|
3 |
|
$input = file_get_contents("php://input") ?: $this->default; |
34
|
3 |
|
if ($input === null) { |
35
|
3 |
|
$input = ''; |
36
|
|
|
} |
37
|
3 |
|
return json_decode($input, true); |
38
|
|
|
} |
39
|
|
|
|
40
|
3 |
|
public function validate(): ValidationResultInterface |
41
|
|
|
{ |
42
|
3 |
|
$value = $this->getValue(); |
43
|
3 |
|
if (json_last_error()) { |
44
|
3 |
|
return new ValidationResult(ValidationResult::STATUS_ERROR, [json_last_error_msg()]); |
45
|
|
|
} |
46
|
|
|
|
47
|
3 |
|
if (!$value && $this->isRequired() === self::OPTIONAL) { |
48
|
3 |
|
return new ValidationResult(ValidationResult::STATUS_OK); |
49
|
|
|
} |
50
|
|
|
|
51
|
3 |
|
$value = json_decode(json_encode($value)); |
52
|
3 |
|
$schemaValidator = new JsonSchemaValidator(); |
53
|
3 |
|
return $schemaValidator->validate($value, $this->schema); |
54
|
|
|
} |
55
|
|
|
|
56
|
3 |
|
protected function addFormInput(Form $form, string $key): BaseControl |
57
|
|
|
{ |
58
|
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> |
59
|
|
|
<div id="json_schema" style="display: none;"> |
60
|
|
|
<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>' |
61
|
3 |
|
. nl2br(str_replace(' ', ' ', json_encode(json_decode($this->schema), JSON_PRETTY_PRINT))) . '</div>'; |
62
|
|
|
|
63
|
3 |
|
return $form->addTextArea('post_raw', $this->getParamLabel()) |
64
|
3 |
|
->setHtmlAttribute('rows', 10); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|