Completed
Pull Request — master (#61)
by Tomas
02:27
created

JsonInputParam   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 68
Duplicated Lines 11.76 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 94.29%

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 2
dl 8
loc 68
ccs 33
cts 35
cp 0.9429
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A setMulti() 0 4 1
A __construct() 0 5 1
A getValue() 0 8 3
B validate() 8 30 7
A addFormInput() 0 10 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Tomaj\NetteApi\Params;
6
7
use Exception;
8
use JsonSchema\Validator;
9
use Nette\Application\UI\Form;
10
use Nette\Forms\Controls\BaseControl;
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
        $schemaValidator = new Validator();
43 3
        $value = $this->getValue();
44 3
        if (json_last_error()) {
45 3
            return new ValidationResult(ValidationResult::STATUS_ERROR, [json_last_error_msg()]);
46
        }
47
48 3
        if (!$value && $this->isRequired() === self::OPTIONAL) {
49 3
            return new ValidationResult(ValidationResult::STATUS_OK);
50
        }
51
52 3
        $value = json_decode(json_encode($value));
53 3
        $schemaValidator->validate($value, json_decode($this->schema));
54
55 3
        if ($schemaValidator->isValid()) {
56
            return new ValidationResult(ValidationResult::STATUS_OK);
57
        }
58
59 3
        $errors = [];
60 3 View Code Duplication
        foreach ($schemaValidator->getErrors() as $error) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
61 3
            $errorMessage = '';
62 3
            if ($error['property']) {
63
                $errorMessage .= '[Property ' . $error['property'] . '] ';
64
            }
65 3
            $errorMessage .= $error['message'];
66 3
            $errors[] = $errorMessage;
67
        }
68 3
        return new ValidationResult(ValidationResult::STATUS_ERROR, $errors);
69
    }
70
71 3
    protected function addFormInput(Form $form, string $key): BaseControl
72
    {
73 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>
74
                            <div id="json_schema" style="display: none;">
75
                            <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>'
76 3
            . nl2br(str_replace(' ', '&nbsp;', json_encode(json_decode($this->schema), JSON_PRETTY_PRINT))) . '</div>';
77
78 3
        return $form->addTextArea('post_raw', $this->getParamLabel())
79 3
            ->setHtmlAttribute('rows', 10);
80
    }
81
}
82