Completed
Push — master ( 0728e2...7bf439 )
by Tomas
10:58 queued 10s
created

ApiConsoleControl::createComponentConsoleForm()   C

Complexity

Conditions 12
Paths 70

Size

Total Lines 75

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 156

Importance

Changes 0
Metric Value
dl 0
loc 75
ccs 0
cts 58
cp 0
rs 6.1186
c 0
b 0
f 0
cc 12
nc 70
nop 0
crap 156

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Tomaj\NetteApi\Component;
6
7
use Nette\Application\UI\Control;
8
use Nette\Application\UI\Form;
9
use Nette\Bridges\ApplicationLatte\Template;
10
use Nette\Http\IRequest;
11
use Nette\Utils\ArrayHash;
12
use Nette\Utils\Html;
13
use Tomaj\Form\Renderer\BootstrapRenderer;
14
use Tomaj\NetteApi\Authorization\ApiAuthorizationInterface;
15
use Tomaj\NetteApi\Authorization\BasicAuthentication;
16
use Tomaj\NetteApi\Authorization\BearerTokenAuthorization;
17
use Tomaj\NetteApi\Authorization\CookieApiKeyAuthentication;
18
use Tomaj\NetteApi\Authorization\HeaderApiKeyAuthentication;
19
use Tomaj\NetteApi\Authorization\NoAuthorization;
20
use Tomaj\NetteApi\Authorization\QueryApiKeyAuthentication;
21
use Tomaj\NetteApi\EndpointInterface;
22
use Tomaj\NetteApi\Handlers\ApiHandlerInterface;
23
use Tomaj\NetteApi\Link\ApiLink;
24
use Tomaj\NetteApi\Misc\ConsoleRequest;
25
26
class ApiConsoleControl extends Control
27
{
28
    private $request;
29
30
    private $endpoint;
31
32
    private $handler;
33
34
    private $authorization;
35
36
    private $apiLink;
37
38
    public function __construct(IRequest $request, EndpointInterface $endpoint, ApiHandlerInterface $handler, ApiAuthorizationInterface $authorization, ApiLink $apiLink = null)
39
    {
40
        $this->request = $request;
41
        $this->endpoint = $endpoint;
42
        $this->handler = $handler;
43
        $this->authorization = $authorization;
44
        $this->apiLink = $apiLink;
45
    }
46
47
    public function render(): void
48
    {
49
        /** @var Template $template */
50
        $template = $this->getTemplate();
51
        $template->setFile(__DIR__ . '/console.latte');
52
        $template->add('handler', $this->handler);
53
        $template->render();
54
    }
55
56
    protected function createComponentConsoleForm(): Form
57
    {
58
        $form = new Form();
59
60
        $defaults = [];
61
62
        $form->setRenderer(new BootstrapRenderer());
63
64
        if ($this->apiLink) {
65
            $url = $this->apiLink->link($this->endpoint);
66
        } else {
67
            $uri = $this->request->getUrl();
68
            $scheme = $uri->scheme;
69
            if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
70
                $scheme = $_SERVER['HTTP_X_FORWARDED_PROTO'];
71
            }
72
            $port = '';
73
            if ($uri->scheme === 'http' && $uri->port !== 80) {
74
                $port = ':' . $uri->port;
75
            }
76
            $url = $scheme . '://' . $uri->host . $port . '/api/' . $this->endpoint->getUrl();
77
        }
78
79
        $form->addText('api_url', 'Api Url');
80
        $defaults['api_url'] = $url;
81
82
        $form->addText('api_method', 'Method');
83
        $defaults['api_method'] = $this->endpoint->getMethod();
84
85
        if ($this->authorization instanceof BearerTokenAuthorization) {
86
            $form->addText('token', 'Token')
87
                ->setHtmlAttribute('placeholder', 'Enter token');
88
        } elseif ($this->authorization instanceof BasicAuthentication) {
89
            $form->addText('basic_authentication_username', 'Username')
90
                ->setHtmlAttribute('placeholder', 'Enter basic authentication username');
91
            $form->addText('basic_authentication_password', 'Password')
92
                ->setHtmlAttribute('placeholder', 'Enter basic authentication password');
93
        } elseif ($this->authorization instanceof QueryApiKeyAuthentication) {
94
            $form->addText($this->authorization->getQueryParamName(), 'API key')
95
                ->setHtmlAttribute('placeholder', 'Enter API key');
96
        } elseif ($this->authorization instanceof HeaderApiKeyAuthentication) {
97
            $form->addText('header_api_key', 'API key')
98
                ->setHtmlAttribute('placeholder', 'Enter API key');
99
        } elseif ($this->authorization instanceof CookieApiKeyAuthentication) {
100
            $form->addText('cookie_api_key', 'API key')
101
                ->setHtmlAttribute('placeholder', 'Enter API key');
102
        } elseif ($this->authorization instanceof NoAuthorization) {
103
            $form->addText('authorization', 'Authorization')
104
                ->setDisabled(true);
105
            $defaults['authorization'] = 'No authorization - global access';
106
        }
107
108
        $form->addCheckbox('send_session_id', 'Send session id cookie');
109
110
        $form->addTextArea('custom_headers', 'Custom headers')
111
            ->setOption('description', Html::el()->setHtml('Each header on new line. For example: <code>User-agent: Mozilla/5.0</code>'));
112
113
        $form->addText('timeout', 'Timeout')
114
            ->setDefaultValue(30);
115
116
        $params = $this->handler->params();
117
        foreach ($params as $param) {
118
            $param->updateConsoleForm($form);
119
        }
120
121
        $form->addSubmit('send', 'Try api')
122
            ->getControlPrototype()
123
            ->setName('button')
124
            ->setHtml('<i class="fa fa-cloud-upload"></i> Try api');
125
126
        $form->setDefaults($defaults);
127
128
        $form->onSuccess[] = array($this, 'formSucceeded');
129
        return $form;
130
    }
131
132
    public function formSucceeded(Form $form, ArrayHash $values): void
133
    {
134
        $url = $values['api_url'];
135
136
        $token = null;
137
        if (isset($values['token'])) {
138
            $token = $values['token'];
139
            unset($values['token']);
140
        }
141
142
        $method = $values['api_method'];
143
        unset($values['api_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
        if (isset($values['custom_headers']) && $values['custom_headers']) {
152
            $additionalValues['headers'] = array_filter(array_map('trim', explode("\n", $values['custom_headers'])));
153
        }
154
155
        $additionalValues['timeout'] = $values['timeout'];
156
157
        if ($this->authorization instanceof QueryApiKeyAuthentication) {
158
            $queryParamName = $this->authorization->getQueryParamName();
159
            $additionalValues['getFields'][$queryParamName] = $values[$queryParamName] ?? null;
160
        } elseif ($this->authorization instanceof HeaderApiKeyAuthentication) {
161
            $headerName = $this->authorization->getHeaderName();
162
            $additionalValues['headers'][] = $headerName . ':' . $values['header_api_key'] ?? null;
163
        } elseif ($this->authorization instanceof CookieApiKeyAuthentication) {
164
            $cookieName = $this->authorization->getCookieName();
165
            $additionalValues['cookieFields'][$cookieName] = $values['cookie_api_key'] ?? null;
166
        }
167
168
        $consoleRequest = new ConsoleRequest($this->handler, $this->endpoint, $this->apiLink);
169
        $result = $consoleRequest->makeRequest($url, $method, (array) $values, $additionalValues, $token);
170
171
        /** @var Template $template */
172
        $template = $this->getTemplate();
173
        $template->add('response', $result);
174
175
        if ($this->getPresenter()->isAjax()) {
176
            $this->getPresenter()->redrawControl();
177
        }
178
    }
179
}
180