GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

DialogProvider   B
last analyzed

Complexity

Total Complexity 42

Size/Duplication

Total Lines 296
Duplicated Lines 10.81 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 0
Metric Value
wmc 42
lcom 1
cbo 12
dl 32
loc 296
rs 8.295
c 0
b 0
f 0

19 Methods

Rating   Name   Duplication   Size   Complexity  
A register() 0 8 1
B askFor() 12 25 5
A askHiddenResponse() 0 11 1
A askConfirmation() 0 5 1
A logStep() 0 5 1
A logTask() 0 11 2
A logCommand() 0 6 2
A logCommandTime() 0 10 3
B logOutput() 0 14 5
A logQuery() 0 19 4
A logConfig() 10 10 3
A logNotice() 10 10 3
A logError() 0 9 2
A logException() 0 18 2
A logWarning() 0 4 1
A renderTable() 0 6 1
A logo() 0 7 2
A logStatistics() 0 6 2
A clearLine() 0 7 1

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like DialogProvider often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DialogProvider, and based on these observations, apply Extract Interface, too.

1
<?php
2
namespace Kunstmaan\Skylab\Provider;
3
4
use Cilex\Application;
5
use Kunstmaan\Skylab\Application as Skylab;
6
use Kunstmaan\Skylab\Exceptions\SkylabException;
7
use Symfony\Component\Console\Helper\QuestionHelper;
8
use Symfony\Component\Console\Question\Question;
9
use Symfony\Component\Console\Question\ConfirmationQuestion;
10
use Symfony\Component\Console\Helper\ProgressBar;
11
use Symfony\Component\Console\Helper\Table;
12
use Symfony\Component\Console\Output\OutputInterface;
13
14
/**
15
 * DialogProvider
16
 */
17
class DialogProvider extends AbstractProvider
18
{
19
20
    /**
21
     * @var QuestionHelper
22
     */
23
    private $dialog;
24
25
    /**
26
     * @var ProgressBar
27
     */
28
    private $progress;
29
30
    /**
31
     * Registers services on the given app.
32
     *
33
     * @param Application $app An Application instance
34
     */
35
    public function register(Application $app)
36
    {
37
        $app['dialog'] = $this;
38
        $this->app = $app;
39
        /** @var Skylab $consoleApp */
40
        $consoleApp = $this->app['console'];
41
        $this->dialog = $consoleApp->getHelperSet()->get('question');
42
    }
43
44
    /**
45
     * @param string $message
46
     * @param  string|null              $argumentname
47
     * @param  null              $default
48
     * @return string
49
     * @throws \RuntimeException
50
     */
51
    public function askFor($message, $argumentname = null, $default = null)
52
    {
53
        $this->clearLine();
54
        $this->output->writeln("\n");
55
        if ($argumentname) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $argumentname of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
56
            $var = $this->input->getArgument($argumentname);
57 View Code Duplication
            if (!$var) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
58
                $question = new Question('<question>' . $message . '</question> ');
59
                $var = $this->dialog->ask($this->input, $this->output, $question);
60
            }
61
        } elseif ($default) {
62
            if ($this->noInteraction) {
63
                $this->dialogProvider->logNotice("--no-interaction selected, using " . $default);
64
                $var = $default;
65 View Code Duplication
            } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
66
                $question = new Question('<question>' . $message . ':  [' . $default . ']</question> ', $default);
67
                $var = $this->dialog->ask($this->input, $this->output, $question);
68
            }
69 View Code Duplication
        } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
70
            $question = new Question('<question>' . $message . '</question> ');
71
            $var = $this->dialog->ask($this->input, $this->output, $question);
72
        }
73
74
        return $var;
75
    }
76
77
    /**
78
     * @param $message
79
     * @return string
80
     */
81
    public function askHiddenResponse($message)
82
    {
83
        $this->clearLine();
84
        $this->output->writeln("\n");
85
        $question = new Question('<question>' . $message . '</question> ');
86
        $question->setHidden(true);
87
        $question->setHiddenFallback(false);
88
        $var = $this->dialog->ask($this->input, $this->output, $question);
89
90
        return $var;
91
    }
92
93
    /**
94
     * @param  string $question The question text
95
     * @param  bool   $default  The default action
96
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
97
     */
98
    public function askConfirmation($question, $default = true)
99
    {
100
        $question = new ConfirmationQuestion($question, $default);
101
        return $this->dialog->ask($this->input, $this->output, $question);
102
    }
103
104
    /**
105
     * @param string $message
106
     */
107
    public function logStep($message)
108
    {
109
        $this->clearLine();
110
        $this->output->writeln("<fg=green;options=bold>-  " . $message . '</fg=green;options=bold>');
111
    }
112
113
    /**
114
     * @param string $message
115
     */
116
    public function logTask($message)
117
    {
118
        $this->clearLine();
119
        $this->output->writeln('<fg=blue;options=bold>   > ' . $message . " </fg=blue;options=bold>");
120
        if ($this->output->getVerbosity() <= OutputInterface::VERBOSITY_NORMAL) {
121
            $this->progress = new ProgressBar($this->output);
122
            $this->progress->setEmptyBarCharacter(' ');
123
            $this->progress->setBarCharacter('-');
124
            $this->progress->start();
125
        }
126
    }
127
128
    /**
129
     * @param string $message
130
     */
131
    public function logCommand($message)
132
    {
133
        if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
134
            $this->output->write('<info>   $</info> <comment>' . $message . '</comment> ');
135
        }
136
    }
137
138
    /**
139
     * @param string $message
0 ignored issues
show
Bug introduced by
There is no parameter named $message. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
140
     */
141
    public function logCommandTime($startTime)
142
    {
143
        if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
144
            $this->output->writeln(' <fg=yellow;options=bold>' . round(microtime(true) - $startTime, 2) . 's</fg=yellow;options=bold>');
145
        } else {
146
            if($this->progress != null) {
147
                $this->progress->advance();
148
            }
149
        }
150
    }
151
152
    /**
153
     * @param string $message
154
     */
155
    public function logOutput($message, $error=false, $silent=false)
156
    {
157
        if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE || !$silent) {
158
            if ($error){
159
                $this->output->write("<error>" . $message . '</error>');
160
            } else {
161
                $this->output->write($message);
162
            }
163
        } else {
164
            if($this->progress != null) {
165
                $this->progress->advance();
166
            }
167
        }
168
    }
169
170
    /**
171
     * @param  string   $message
172
     * @param  string[] $extra
0 ignored issues
show
Documentation introduced by
Should the type for parameter $extra not be string[]|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
173
     * @return string
174
     */
175
    public function logQuery($message, $extra=null)
176
    {
177
        if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
178
            $this->output->writeln('<info>   ~</info> <comment>' .
179
                $message .
180
                ($extra ?
181
                    ' (' .
182
                    implode(', ',
183
                        array_map(function ($v, $k) { return $k . '=' . $v; }, $extra, array_keys($extra))
184
                    ) .
185
                    ')' : '') .
186
                '</comment> ');
187
        } else {
188
            if ($this->progress != null) {
189
                $this->progress->advance();
190
            }
191
        }
192
        return $message;
193
    }
194
195
    /**
196
     * @param string $message
197
     */
198 View Code Duplication
    public function logConfig($message)
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...
199
    {
200
        if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
201
            $this->output->writeln('<info>   %</info> <comment>' . $message . '</comment> ');
202
        } else {
203
            if($this->progress != null) {
204
                $this->progress->advance();
205
            }
206
        }
207
    }
208
209
    /**
210
     * @param string $message
211
     */
212 View Code Duplication
    public function logNotice($message)
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...
213
    {
214
        if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
215
            $this->output->writeln('<info>   !</info> <comment>' . $message . '</comment> ');
216
        } else {
217
            if($this->progress != null) {
218
                $this->progress->advance();
219
            }
220
        }
221
    }
222
223
    /**
224
     * @param $message
225
     * @param bool|true $report
226
     * @throws SkylabException
227
     */
228
    public function logError($message, $report=true)
229
    {
230
        if ($report) {
231
            throw new SkylabException($message);
232
        } else {
233
            $this->output->writeln("\n\n<error>  " . $message . "</error>\n\n");
234
            exit(1);
0 ignored issues
show
Coding Style Compatibility introduced by
The method logError() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
235
        }
236
    }
237
238
    /**
239
     * @param \Exception $ex
240
     * @param array $extra
241
     */
242
    public function logException(\Exception $ex, $tags=array(), $extra = array())
243
    {
244
        $ravenClient = new \Raven_Client('https://da7e699379b84d8588b837bd518a2a84:[email protected]/49959');
245
        $tags['php_version'] = phpversion();
246
        $tags['skylab_version'] = \Kunstmaan\Skylab\Application::VERSION;
247
        $tags['user'] = posix_getpwuid(posix_geteuid())['name'];
248
        $extra = array_merge($extra,$this->app["config"]);
249
        if (\Kunstmaan\Skylab\Application::VERSION !== "@package_version@") {
250
            $event_id = $ravenClient->getIdent($ravenClient->captureException($ex, array(
251
                'extra' => $extra,
252
                'tags' => $tags
253
            )));
254
            $this->output->writeln("\n\n<error>  " . $ex->getMessage() . "\n  This exception has been reported with id $event_id. Please log a github issue at https://github.com/Kunstmaan/skylab/issues and mention this id.</error>\n\n");
255
        }
256
257
        echo $ex->getTraceAsString();
258
        throw $ex;
259
    }
260
261
    /**
262
     * @param string $message
263
     */
264
    public function logWarning($message)
265
    {
266
        $this->output->writeln("<fg=black;bg=yellow;options=bold>\n\n" . $message . "\n</fg=black;bg=yellow;options=bold>\n\n");
267
    }
268
269
    /**
270
     * @param $rows
271
     */
272
    public function renderTable($headers, $rows)
273
    {
274
        $table = new Table($this->output);
275
        $table->setHeaders($headers)->setRows($rows);
276
        $table->render($this->output);
0 ignored issues
show
Unused Code introduced by
The call to Table::render() has too many arguments starting with $this->output.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
277
    }
278
279
    /**
280
     * @param string $txt
281
     */
282
    public static function logo(OutputInterface $output, $verbosity, $txt)
283
    {
284
        if ($output->getVerbosity() >= $verbosity) {
285
            $output->write(Skylab::$logo);
286
            $output->writeln("<fg=yellow;options=bold>$txt</fg=yellow;options=bold>\n");
287
        }
288
    }
289
290
    /**
291
     * @param OutputInterface $output
292
     * @param $verbosity
293
     * @param $startTime
294
     */
295
    public static function logStatistics(OutputInterface $output, $verbosity, $startTime)
296
    {
297
        if ($output->getVerbosity() >= $verbosity) {
298
            $output->writeln("\n<fg=yellow;options=bold>Memory usage: " . round(memory_get_usage() / 1024 / 1024, 2) . 'MB (peak: ' . round(memory_get_peak_usage() / 1024 / 1024, 2) . 'MB), time: ' . round(microtime(true) - $startTime, 2) . "s</fg=yellow;options=bold>\n");
299
        }
300
    }
301
302
    /**
303
     *
304
     */
305
    public function clearLine()
306
    {
307
        $message = str_pad("", 100, "\x20", STR_PAD_RIGHT);
308
        $this->output->write("\x0D");
309
        $this->output->write($message);
310
        $this->output->write("\x0D");
311
    }
312
}
313