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

JsonInputParam   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 65
Duplicated Lines 12.31 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 93.94%

Importance

Changes 0
Metric Value
dl 8
loc 65
c 0
b 0
f 0
wmc 12
lcom 1
cbo 2
ccs 31
cts 33
cp 0.9394
rs 10

5 Methods

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

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