Completed
Pull Request — master (#66)
by Jonas
02:55
created

Command::execute()   D

Complexity

Conditions 12
Paths 265

Size

Total Lines 55
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 0
loc 55
rs 4.9336
cc 12
eloc 34
nc 265
nop 2

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
namespace Povils\PHPMND\Console;
4
5
use Povils\PHPMND\Detector;
6
use Povils\PHPMND\ExtensionResolver;
7
use Povils\PHPMND\FileReportList;
8
use Povils\PHPMND\HintList;
9
use Povils\PHPMND\PHPFinder;
10
use Povils\PHPMND\Printer;
11
use SebastianBergmann\Timer\Timer;
12
use Symfony\Component\Console\Command\Command as BaseCommand;
13
use Symfony\Component\Console\Helper\ProgressBar;
14
use Symfony\Component\Console\Input\InputArgument;
15
use Symfony\Component\Console\Input\InputInterface;
16
use Symfony\Component\Console\Input\InputOption;
17
use Symfony\Component\Console\Output\OutputInterface;
18
19
/**
20
 * Class Command
21
 *
22
 * @package Povils\PHPMND\Console
23
 */
24
class Command extends BaseCommand
25
{
26
    const EXIT_CODE_SUCCESS = 0;
27
    const EXIT_CODE_FAILURE = 1;
28
29
    /**
30
     * @inheritdoc
31
     */
32
    protected function configure()
33
    {
34
        $this
35
            ->setName('phpmnd')
36
            ->setDefinition(
37
                [
38
                    new InputArgument(
39
                        'directory',
40
                        InputArgument::REQUIRED,
41
                        'Directory to analyze'
42
                    )
43
                ]
44
            )
45
            ->addOption(
46
                'extensions',
47
                null,
48
                InputOption::VALUE_REQUIRED,
49
                'A comma-separated list of extensions'
50
            )
51
            ->addOption(
52
                'ignore-numbers',
53
                null,
54
                InputOption::VALUE_REQUIRED,
55
                'A comma-separated list of numbers to ignore',
56
                '0, 1'
57
            )
58
            ->addOption(
59
                'ignore-funcs',
60
                null,
61
                InputOption::VALUE_REQUIRED,
62
                'A comma-separated list of functions to ignore when using "argument" extension'
63
            )
64
            ->addOption(
65
                'exclude',
66
                null,
67
                InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
68
                'Exclude a directory from code analysis (must be relative to source)'
69
            )
70
            ->addOption(
71
                'exclude-path',
72
                null,
73
                InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
74
                'Exclude a path from code analysis (must be relative to source)'
75
            )
76
            ->addOption(
77
                'exclude-file',
78
                null,
79
                InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
80
                'Exclude a file from code analysis (must be relative to source)'
81
            )
82
            ->addOption(
83
                'suffixes',
84
                null,
85
                InputOption::VALUE_REQUIRED,
86
                'Comma-separated string of valid source code filename extensions',
87
                'php'
88
            )
89
            ->addOption(
90
                'progress',
91
                null,
92
                InputOption::VALUE_NONE,
93
                'Show progress bar'
94
            )
95
            ->addOption(
96
                'hint',
97
                null,
98
                InputOption::VALUE_NONE,
99
                'Suggest replacements for magic numbers'
100
            )
101
            ->addOption(
102
                'non-zero-exit-on-violation',
103
                null,
104
                InputOption::VALUE_NONE,
105
                'Return a non zero exit code when there are magic numbers'
106
            )
107
            ->addOption(
108
                'strings',
109
                null,
110
                InputOption::VALUE_NONE,
111
                'Include strings literal search in code analysis'
112
            )
113
            ->addOption(
114
                'ignore-strings',
115
                null,
116
                InputOption::VALUE_REQUIRED,
117
                'A comma-separated list of strings to ignore when using "strings" option'
118
            );
119
    }
120
121
    /**
122
     * @inheritdoc
123
     */
124
    protected function execute(InputInterface $input, OutputInterface $output)
125
    {
126
        $finder = $this->createFinder($input);
127
128
        if (0 === $finder->count()) {
129
            $output->writeln('No files found to scan');
130
            return self::EXIT_CODE_SUCCESS;
131
        }
132
133
        $progressBar = null;
134
        if ($input->getOption('progress')) {
135
            $progressBar = new ProgressBar($output, $finder->count());
136
            $progressBar->start();
137
        }
138
139
        $hintList = new HintList;
140
        $detector = new Detector($this->createOption($input), $hintList);
141
142
        $fileReportList = new FileReportList();
143
        $printer = new Printer();
144
        foreach ($finder as $file) {
145
            try {
146
                $fileReport = $detector->detect($file);
147
                if ($fileReport->hasMagicNumbers()) {
148
                    $fileReportList->addFileReport($fileReport);
149
                }
150
            } catch (\Exception $e) {
151
                $output->writeln($e->getMessage());
152
            }
153
154
            if ($input->getOption('progress')) {
155
                $progressBar->advance();
156
            }
157
        }
158
159
        if ($input->getOption('progress')) {
160
            $progressBar->finish();
161
        }
162
163
        if ($output->getVerbosity() !== OutputInterface::VERBOSITY_QUIET) {
164
            $output->writeln('');
165
            $printer->printData($output, $fileReportList, $hintList);
166
167
            $resourceUsage = class_exists(Timer::class)
168
                ? Timer::resourceUsage()
169
                : \PHP_Timer::resourceUsage();
170
171
            $output->writeln('<info>' . $resourceUsage . '</info>');
172
        }
173
174
        if ($input->getOption('non-zero-exit-on-violation') && $fileReportList->hasMagicNumbers()) {
175
            return self::EXIT_CODE_FAILURE;
176
        }
177
        return self::EXIT_CODE_SUCCESS;
178
    }
179
180
    /**
181
     * @param InputInterface $input
182
     * @return Option
183
     * @throws \Exception
184
     */
185
    private function createOption(InputInterface $input)
186
    {
187
        $option = new Option;
188
        $option->setIgnoreNumbers(array_map([$this, 'castToNumber'], $this->getCSVOption($input, 'ignore-numbers')));
189
        $option->setIgnoreFuncs($this->getCSVOption($input, 'ignore-funcs'));
190
        $option->setIncludeStrings($input->getOption('strings'));
191
        $option->setIgnoreStrings($this->getCSVOption($input, 'ignore-strings'));
192
        $option->setGiveHint($input->getOption('hint'));
193
        $option->setExtensions(
194
            (new ExtensionResolver())->resolve($this->getCSVOption($input, 'extensions'))
195
        );
196
197
        return $option;
198
    }
199
200
    /**
201
     * @param InputInterface $input
202
     * @param string $option
203
     *
204
     * @return array
205
     */
206
    private function getCSVOption(InputInterface $input, $option)
207
    {
208
        $result = $input->getOption($option);
209
        if (false === is_array($result)) {
210
            return array_filter(
211
                explode(',', $result),
212
                function ($value) {
213
                    return false === empty($value);
214
                }
215
            );
216
        }
217
218
        if (null === $result) {
219
            return [];
220
        }
221
222
        return $result;
223
    }
224
225
    /**
226
     * @param InputInterface $input
227
     *
228
     * @return PHPFinder
229
     */
230
    protected function createFinder(InputInterface $input)
231
    {
232
        return new PHPFinder(
233
            $input->getArgument('directory'),
234
            $input->getOption('exclude'),
235
            $input->getOption('exclude-path'),
236
            $input->getOption('exclude-file'),
237
            $this->getCSVOption($input, 'suffixes')
238
        );
239
    }
240
241
    /**
242
     * @param string $value
243
     *
244
     * @return int|float|string
245
     */
246
    private function castToNumber($value)
247
    {
248
        if (is_numeric($value)) {
249
            $value += 0; // '2' -> (int) 2, '2.' -> (float) 2.0
250
        }
251
252
        return $value;
253
    }
254
}
255