Completed
Push — master ( 0ef30a...eb3939 )
by Kevin
03:35
created

ApiListCommand   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 163
Duplicated Lines 17.18 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 13
c 1
b 0
f 0
lcom 1
cbo 5
dl 28
loc 163
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A configure() 0 6 1
A execute() 0 23 1
A askUrlApi() 0 9 1
A askApiKey() 14 14 2
A askSecretKey() 14 14 2
B processList() 0 48 6

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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 null|int
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
        $this->processList($input, $output, $list);
0 ignored issues
show
Bug introduced by
It seems like $list defined by $client->getResponse($request) on line 53 can also be of type null or string; however, PCextreme\Cloudstack\Con...tCommand::processList() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
55
    }
56
57
    /**
58
     * Ask for URL API.
59
     *
60
     * @param  InputInterface   $input
61
     * @param  OutputInterface  $output
62
     * @return string
63
     */
64
    protected function askUrlApi(InputInterface $input, OutputInterface $output)
65
    {
66
        $question = new Question(
67
            'Enter target API url [default: https://api.auroracompute.eu/ams]: ',
68
            'https://api.auroracompute.eu/ams'
69
        );
70
71
        return $this->getHelper('question')->ask($input, $output, $question);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Console\Helper\HelperInterface as the method ask() does only exist in the following implementations of said interface: Symfony\Component\Console\Helper\QuestionHelper, Symfony\Component\Consol...r\SymfonyQuestionHelper.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
72
    }
73
74
    /**
75
     * Ask for API key.
76
     *
77
     * @param  InputInterface   $input
78
     * @param  OutputInterface  $output
79
     * @return string
80
     */
81 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...
82
    {
83
        $question = (new Question('Enter API key: '))
84
            ->setValidator(function ($answer) {
85
                if (is_null($answer)) {
86
                    throw new \InvalidArgumentException("API key can't be null.");
87
                }
88
89
                return $answer;
90
            })
91
            ->setMaxAttempts(2);
92
93
        return $this->getHelper('question')->ask($input, $output, $question);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Console\Helper\HelperInterface as the method ask() does only exist in the following implementations of said interface: Symfony\Component\Console\Helper\QuestionHelper, Symfony\Component\Consol...r\SymfonyQuestionHelper.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
94
    }
95
96
    /**
97
     * Ask for secret key.
98
     *
99
     * @param  InputInterface   $input
100
     * @param  OutputInterface  $output
101
     * @return string
102
     */
103 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...
104
    {
105
        $question = (new Question('Enter secret key: '))
106
            ->setValidator(function ($answer) {
107
                if (is_null($answer)) {
108
                    throw new \InvalidArgumentException("Secret key can't be null.");
109
                }
110
111
                return $answer;
112
            })
113
            ->setMaxAttempts(2);
114
115
        return $this->getHelper('question')->ask($input, $output, $question);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Console\Helper\HelperInterface as the method ask() does only exist in the following implementations of said interface: Symfony\Component\Console\Helper\QuestionHelper, Symfony\Component\Consol...r\SymfonyQuestionHelper.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
116
    }
117
118
    /**
119
     * Dump cache file of APIs list.
120
     *
121
     * @param  InputInterface   $input
122
     * @param  OutputInterface  $output
123
     * @param  array            $list
124
     * @return void
125
     */
126
    protected function processList(InputInterface $input, OutputInterface $output, array $list = [])
0 ignored issues
show
Unused Code introduced by
The parameter $input is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
127
    {
128
        if (empty($list)) {
129
            throw new \RuntimeException("API list is empty.");
130
        }
131
132
        $progress = new ProgressBar($output, $list['listapisresponse']['count']);
133
        $progress->start();
134
135
        $listFile = "<?php\n\n";
136
        $listFile .= "// api_list.php @generated by api:list command\n\n";
137
        $listFile .= "return array(\n";
138
139
        foreach ($list['listapisresponse']['api'] as $api) {
140
            $name        = $api['name'];
141
            $description = addslashes($api['description']);
142
            $isAsync     = $api['isasync'];
143
144
            $listFile .= "    '$name' => array(\n";
145
            $listFile .= "        'description' => '$description',\n";
146
            $listFile .= "        'isasync'     => " . ($isAsync ? "true" : "false") . ",\n";
147
            $listFile .= "        'params'      => array(\n";
148
149
            foreach ($api['params'] as $param) {
150
                $paramName        = $param['name'];
151
                $paramDescription = addslashes($param['description']);
152
                $paramType        = $param['type'];
153
                $paramRequired    = $param['required'];
154
155
                $listFile .= "            '$paramName' => array(\n";
156
                $listFile .= "                'description' => '$paramDescription',\n";
157
                $listFile .= "                'type'        => '$paramType',\n";
158
                $listFile .= "                'required'    => " . ($paramRequired ? "true" : "false") . ",\n";
159
                $listFile .= "            ),\n";
160
            }
161
162
            $listFile .= "        ),\n";
163
            $listFile .= "    ),\n";
164
165
            $progress->advance();
166
        }
167
168
        $listFile .= ");\n";
169
170
        file_put_contents(__DIR__ . '/../../cache/api_list.php', $listFile);
171
172
        $progress->finish();
173
    }
174
}
175