Completed
Branch master (4275a9)
by Kevin
02:08
created

ApiListCommand::processList()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 46

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 46
rs 9.1781
c 0
b 0
f 0
cc 4
nc 4
nop 2
1
<?php
2
3
namespace PCextreme\Cloudstack\Console;
4
5
use PCextreme\Cloudstack\Client;
6
use Symfony\Component\Console\Command\Command;
7
use Symfony\Component\Console\Helper\ProgressBar;
8
use Symfony\Component\Console\Input\InputInterface;
9
use Symfony\Component\Console\Output\OutputInterface;
10
use Symfony\Component\Console\Question\Question;
11
12
class ApiListCommand extends Command
13
{
14
    /**
15
     * Configures the current command.
16
     *
17
     * @return void
18
     */
19
    protected function configure()
20
    {
21
        $this->setName('api:list')
22
            ->setDescription('Generate API list cache.')
23
            ->setHelp("This will generate the API list cache file usign the 'listApis' command.");
24
    }
25
26
    /**
27
     * Executes the current command.
28
     *
29
     * @param  InputInterface  $input
30
     * @param  OutputInterface $output
31
     * @return void
32
     */
33
    protected function execute(InputInterface $input, OutputInterface $output)
34
    {
35
        $urlApi    = $this->askUrlApi($input, $output);
36
        $apiKey    = $this->askApiKey($input, $output);
37
        $secretKey = $this->askSecretKey($input, $output);
38
39
        $output->writeLn('');
40
        $output->writeLn("<info>Processing API list. Please Wait...</info>");
41
42
        $client = new Client([
43
            'urlApi'    => $urlApi,
44
            'apiKey'    => $apiKey,
45
            'secretKey' => $secretKey,
46
        ]);
47
48
        $command = 'listApis';
49
        $method  = $client->getCommandMethod($command);
50
        $url     = $client->getCommandUrl($command, []);
51
        $request = $client->getRequest($method, $url, []);
52
53
        $list = $client->getResponse($request);
54
55
        // We expect an array from the getResponse method, when this returns
56
        // with a string we most likely got a server error.
57
        if (is_string($list)) {
58
            throw new \RuntimeException(sprintf(
59
                "Invalid API response, received: %s",
60
                $list
61
            ));
62
        }
63
64
        $this->processList($output, $list);
65
    }
66
67
    /**
68
     * Ask for URL API.
69
     *
70
     * @param  InputInterface  $input
71
     * @param  OutputInterface $output
72
     * @return string
73
     */
74
    protected function askUrlApi(InputInterface $input, OutputInterface $output)
75
    {
76
        $question = new Question(
77
            'Enter target API url [default: https://api.auroracompute.eu/ams]: ',
78
            'https://api.auroracompute.eu/ams'
79
        );
80
81
        return $this->getHelper('question')->ask($input, $output, $question);
82
    }
83
84
    /**
85
     * Ask for API key.
86
     *
87
     * @param  InputInterface  $input
88
     * @param  OutputInterface $output
89
     * @return string
90
     */
91 View Code Duplication
    protected function askApiKey(InputInterface $input, OutputInterface $output)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
92
    {
93
        $question = (new Question('Enter API key: '))
94
            ->setValidator(function ($answer) {
95
                if (is_null($answer)) {
96
                    throw new \InvalidArgumentException("API key can't be null.");
97
                }
98
99
                return $answer;
100
            })
101
            ->setMaxAttempts(2);
102
103
        return $this->getHelper('question')->ask($input, $output, $question);
104
    }
105
106
    /**
107
     * Ask for secret key.
108
     *
109
     * @param  InputInterface  $input
110
     * @param  OutputInterface $output
111
     * @return string
112
     */
113 View Code Duplication
    protected function askSecretKey(InputInterface $input, OutputInterface $output)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
114
    {
115
        $question = (new Question('Enter secret key: '))
116
            ->setValidator(function ($answer) {
117
                if (is_null($answer)) {
118
                    throw new \InvalidArgumentException("Secret key can't be null.");
119
                }
120
121
                return $answer;
122
            })
123
            ->setMaxAttempts(2);
124
125
        return $this->getHelper('question')->ask($input, $output, $question);
126
    }
127
128
    /**
129
     * Dump cache file of APIs list.
130
     *
131
     * @param  OutputInterface $output
132
     * @param  array           $list
133
     * @return void
134
     */
135
    protected function processList(OutputInterface $output, array $list = [])
136
    {
137
        if (empty($list)) {
138
            throw new \RuntimeException("API list is empty.");
139
        }
140
141
        $progress = new ProgressBar($output, $list['listapisresponse']['count']);
142
        $progress->start();
143
144
        $commands = [];
145
146
        foreach ($list['listapisresponse']['api'] as $api) {
147
            $commandName = $api['name'];
148
            $command = [
149
                'description' => $api['description'],
150
                'isasync'     => $api['isasync'],
151
            ];
152
153
            $commandParams = [];
154
155
            foreach ($api['params'] as $apiParam) {
156
                $paramName = $apiParam['name'];
157
                $param = [
158
                    'description' => $apiParam['description'],
159
                    'required' => $apiParam['required'],
160
                    'type' => $apiParam['type'],
161
                ];
162
163
                $commandParams[$paramName] = $param;
164
            }
165
166
            $command['params'] = $commandParams;
167
168
            $commands[$commandName] = $command;
169
170
            $progress->advance();
171
        }
172
173
        $listFile = "<?php\n\n";
174
        $listFile .= "// api_list.php @generated by api:list command\n\n";
175
        $listFile .= "return ".var_export($commands, true).";\n";
176
177
        file_put_contents(__DIR__ . '/../../cache/api_list.php', $listFile);
178
179
        $progress->finish();
180
    }
181
}
182