Completed
Push — master ( 060c67...cb2641 )
by Tomas
02:33
created

ApiConsoleControl::formSucceeded()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 0
loc 18
ccs 0
cts 14
cp 0
rs 9.4285
cc 2
eloc 11
nc 2
nop 2
crap 6
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
        $url = $scheme . '://' . $uri->host . '/api/' . $this->endpoint->getUrl();
56
57
        $form->addText('api_url', 'Api Url');
58
        $defaults['api_url'] = $url;
59
60
        $form->addText('method', 'Method');
61
        $defaults['method'] = $this->endpoint->getMethod();
62
63
        if ($this->authorization instanceof BearerTokenAuthorization) {
64
            $form->addText('token', 'Token')
65
                ->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...
66
        } elseif ($this->authorization instanceof NoAuthorization) {
67
            $form->addText('authorization', 'Authorization')
68
                ->setDisabled(true);
69
            $defaults['authorization'] = 'No authorization - global access';
70
        }
71
72
        $params = $this->handler->params();
73
        foreach ($params as $param) {
74
            $count = $param->isMulti() ? 5 : 1;
75
            for ($i = 0; $i < $count; $i++) {
76
                $key = $param->getKey();
77
                if ($param->isMulti()) {
78
                    $key = $key . '___' . $i;
79
                }
80
81
                if ($param->getType() == InputParam::TYPE_FILE) {
82
                    $c = $form->addUpload($key, $this->getParamLabel($param));
83
                } else {
84
                    $c = $form->addText($key, $this->getParamLabel($param));
85
                }
86
87
                if ($param->getAvailableValues()) {
88
                    $c->setOption('description', 'available values: ' . implode(' | ', $param->getAvailableValues()));
89
                }
90
            }
91
        }
92
93
        $form->addSubmit('send', 'Otestuj')
94
            ->getControlPrototype()
95
            ->setName('button')
96
            ->setHtml('<i class="fa fa-cloud-upload"></i> Try api');
97
98
        $form->setDefaults($defaults);
99
100
        $form->onSuccess[] = array($this, 'formSucceeded');
101
        return $form;
102
    }
103
104
    private function getParamLabel(InputParam $param)
105
    {
106
        $title = ucfirst(str_replace('_', ' ', $param->getKey()));
107
        if ($param->isRequired()) {
108
            $title .= ' *';
109
        }
110
        return $title;
111
    }
112
113
    public function formSucceeded($form, $values)
114
    {
115
        $url = $values['api_url'];
116
117
        $token = false;
118
        if (isset($values['token'])) {
119
            $token = $values['token'];
120
            unset($values['token']);
121
        }
122
123
        $method = $values['method'];
124
        unset($values['method']);
125
126
        $consoleRequest = new ConsoleRequest($this->handler);
127
        $result = $consoleRequest->makeRequest($url, $method, (array) $values, $token);
128
129
        $this->getTemplate()->add('response', $result);
130
    }
131
}
132