Completed
Push — master ( 961dba...77e9b9 )
by Tomas
05:52
created

ApiConsoleControl   B

Complexity

Total Complexity 31

Size/Duplication

Total Lines 151
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 15

Test Coverage

Coverage 0%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 31
c 4
b 0
f 0
lcom 1
cbo 15
dl 0
loc 151
ccs 0
cts 118
cp 0
rs 8.9833

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A render() 0 5 1
A getLabel() 0 4 1
A getParamLabel() 0 9 2
B formSucceeded() 0 24 4
F createComponentConsoleForm() 0 85 22
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();
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
        $jsonField = null;
80
        $jsonParams = [];
81
        foreach ($params as $param) {
82
            $count = $param->isMulti() ? 5 : 1;
83
            for ($i = 0; $i < $count; $i++) {
84
                $key = $param->getKey();
85
                if ($param->isMulti()) {
86
                    $key = $key . '___' . $i;
87
                }
88
89
                if ($param->getAvailableValues() && is_array($param->getAvailableValues())) {
90
                    $c = $form->addSelect($key, $this->getParamLabel($param), array_combine($param->getAvailableValues(), $param->getAvailableValues()));
91
                    if (!$param->isRequired()) {
92
                        $c->setPrompt('Select ' . $this->getLabel($param));
93
                    }
94
                } elseif ($param->getAvailableValues() && is_string($param->getAvailableValues())) {
95
                    $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...
96
                    $defaults[$key] = $param->getAvailableValues();
97
                } elseif ($param->getType() == InputParam::TYPE_FILE) {
98
                    $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...
99
                } elseif ($param->getType() == InputParam::TYPE_POST_RAW) {
100
                    $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...
101
                        ->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...
102
                } elseif ($param->getType() == InputParam::TYPE_POST_JSON_KEY) {
103
                    if ($jsonField === null) {
104
                        $jsonField = $form->addTextArea('post_raw', 'JSON')
105
                            ->setOption('description', 'Empty string means "key is required", null means "key is optional"');
106
                    }
107
                    $jsonParams[$key] = $param->isRequired() ? '' : null;
108
                } else {
109
                    $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...
110
                }
111
            }
112
        }
113
        if ($jsonField !== null && $jsonParams) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $jsonParams of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

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