Completed
Push — master ( ba270f...2f6c8f )
by Tomas
9s
created

ApiConsoleControl::formSucceeded()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 24
ccs 0
cts 19
cp 0
rs 8.6845
cc 4
eloc 15
nc 4
nop 2
crap 20
1
<?php
2
3
namespace Tomaj\NetteApi\Component;
4
5
use Nette\Application\UI\Control;
6
use Nette\Application\UI\Form;
7
use Nette\Http\Request;
8
use Tomaj\Form\Renderer\BootstrapRenderer;
9
use Tomaj\NetteApi\Authorization\ApiAuthorizationInterface;
10
use Tomaj\NetteApi\Authorization\BearerTokenAuthorization;
11
use Tomaj\NetteApi\Authorization\NoAuthorization;
12
use Tomaj\NetteApi\EndpointIdentifier;
13
use Tomaj\NetteApi\Handlers\ApiHandlerInterface;
14
use Tomaj\NetteApi\Misc\ConsoleRequest;
15
use Tomaj\NetteApi\Params\InputParam;
16
17
class ApiConsoleControl extends Control
18
{
19
    private $endpoint;
20
21
    private $handler;
22
23
    private $authorization;
24
25
    private $request;
26
27
    public function __construct(Request $request, EndpointIdentifier $endpoint, ApiHandlerInterface $handler, ApiAuthorizationInterface $authorization)
28
    {
29
        parent::__construct(null, 'apiconsolecontrol');
30
        $this->endpoint = $endpoint;
31
        $this->handler = $handler;
32
        $this->authorization = $authorization;
33
        $this->request = $request;
34
    }
35
36
    public function render()
37
    {
38
        $this->getTemplate()->setFile(__DIR__ . '/console.latte');
39
        $this->getTemplate()->render();
40
    }
41
42
    protected function createComponentConsoleForm()
0 ignored issues
show
Coding Style introduced by
createComponentConsoleForm uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
43
    {
44
        $form = new Form();
45
46
        $defaults = [];
47
48
        $form->setRenderer(new BootstrapRenderer());
49
50
        $uri = $this->request->getUrl();
51
        $scheme = $uri->scheme;
52
        if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
53
            $scheme = $_SERVER['HTTP_X_FORWARDED_PROTO'];
54
        }
55
        $port = '';
56
        if ($uri->scheme == 'http' && $uri->port != 80) {
57
            $port = ':' . $uri->port;
58
        }
59
        $url = $scheme . '://' . $uri->host . $port . '/api/' . $this->endpoint->getUrl();
60
61
        $form->addText('api_url', 'Api Url');
62
        $defaults['api_url'] = $url;
63
64
        $form->addText('method', 'Method');
65
        $defaults['method'] = $this->endpoint->getMethod();
66
67
        if ($this->authorization instanceof BearerTokenAuthorization) {
68
            $form->addText('token', 'Token')
69
                ->setAttribute('placeholder', 'Enter token');
0 ignored issues
show
Documentation introduced by
'Enter token' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
70
        } elseif ($this->authorization instanceof NoAuthorization) {
71
            $form->addText('authorization', 'Authorization')
72
                ->setDisabled(true);
73
            $defaults['authorization'] = 'No authorization - global access';
74
        }
75
76
        $form->addCheckbox('send_session_id', 'Send session id cookie');
77
78
        $params = $this->handler->params();
79
        foreach ($params as $param) {
80
            $count = $param->isMulti() ? 5 : 1;
81
            for ($i = 0; $i < $count; $i++) {
82
                $key = $param->getKey();
83
                if ($param->isMulti()) {
84
                    $key = $key . '___' . $i;
85
                }
86
87
                if ($param->getAvailableValues() && is_array($param->getAvailableValues())) {
88
                    $c = $form->addSelect($key, $this->getParamLabel($param), array_combine($param->getAvailableValues(), $param->getAvailableValues()));
89
                    if (!$param->isRequired()) {
90
                        $c->setPrompt('Select ' . $this->getLabel($param));
91
                    }
92
                } elseif ($param->getAvailableValues() && is_string($param->getAvailableValues())) {
93
                    $c = $form->addText($key, $this->getParamLabel($param))->setDisabled(true);
0 ignored issues
show
Unused Code introduced by
$c is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
94
                    $defaults[$key] = $param->getAvailableValues();
95
                } elseif ($param->getType() == InputParam::TYPE_FILE) {
96
                    $c = $form->addUpload($key, $this->getParamLabel($param));
0 ignored issues
show
Unused Code introduced by
$c is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
97
                } elseif ($param->getType() == InputParam::TYPE_POST_RAW) {
98
                    $c = $form->addTextArea('post_raw', $this->getParamLabel($param))
0 ignored issues
show
Unused Code introduced by
$c is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
99
                        ->setAttribute('rows', 10);
0 ignored issues
show
Documentation introduced by
10 is of type integer, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
100
                } else {
101
                    $c = $form->addText($key, $this->getParamLabel($param));
0 ignored issues
show
Unused Code introduced by
$c is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
102
                }
103
            }
104
        }
105
106
        $form->addSubmit('send', 'Otestuj')
107
            ->getControlPrototype()
108
            ->setName('button')
109
            ->setHtml('<i class="fa fa-cloud-upload"></i> Try api');
110
111
        $form->setDefaults($defaults);
112
113
        $form->onSuccess[] = array($this, 'formSucceeded');
114
        return $form;
115
    }
116
117
    private function getLabel(InputParam $param)
118
    {
119
        return ucfirst(str_replace('_', ' ', $param->getKey()));
120
    }
121
122
    private function getParamLabel(InputParam $param)
123
    {
124
        $title = $this->getLabel($param);
125
        if ($param->isRequired()) {
126
            $title .= ' *';
127
        }
128
        $title .= ' (' . $param->getType() . ')';
129
        return $title;
130
    }
131
132
    public function formSucceeded($form, $values)
133
    {
134
        $url = $values['api_url'];
135
136
        $token = false;
137
        if (isset($values['token'])) {
138
            $token = $values['token'];
139
            unset($values['token']);
140
        }
141
142
        $method = $values['method'];
143
        unset($values['method']);
144
145
        $additionalValues = [];
146
        if (isset($values['send_session_id']) && $values['send_session_id']) {
147
            $additionalValues['cookieFields'][session_name()] = session_id();
148
            session_write_close();
149
        }
150
151
        $consoleRequest = new ConsoleRequest($this->handler);
152
        $result = $consoleRequest->makeRequest($url, $method, (array) $values, $additionalValues, $token);
153
154
        $this->getTemplate()->add('response', $result);
155
    }
156
}
157