Completed
Push — master ( 132a7c...1cf077 )
by Povilas
02:35 queued 01:04
created

Command   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 245
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 15

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 20
c 4
b 0
f 0
lcom 2
cbo 15
dl 0
loc 245
rs 9.1666

6 Methods

Rating   Name   Duplication   Size   Complexity  
B configure() 0 101 1
D execute() 0 55 12
A createOption() 0 15 1
A getCSVOption() 0 18 3
A createFinder() 0 10 1
A castToNumber() 0 8 2
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
            ->addOption(
120
                'include-numeric-string',
121
                null,
122
                InputOption::VALUE_NONE,
123
                'Include strings which are numeric'
124
            )
125
            ->addOption(
126
                'xml-output',
127
                null,
128
                InputOption::VALUE_REQUIRED,
129
                'Generate an XML output to the specified path'
130
            )
131
        ;
132
    }
133
134
    /**
135
     * @inheritdoc
136
     */
137
    protected function execute(InputInterface $input, OutputInterface $output)
138
    {
139
        $finder = $this->createFinder($input);
140
141
        if (0 === $finder->count()) {
142
            $output->writeln('No files found to scan');
143
            return self::EXIT_CODE_SUCCESS;
144
        }
145
146
        $progressBar = null;
147
        if ($input->getOption('progress')) {
148
            $progressBar = new ProgressBar($output, $finder->count());
149
            $progressBar->start();
150
        }
151
152
        $hintList = new HintList;
153
        $detector = new Detector($this->createOption($input), $hintList);
154
155
        $fileReportList = new FileReportList();
156
        $printer = new Printer\Console();
157
        foreach ($finder as $file) {
158
            try {
159
                $fileReport = $detector->detect($file);
160
                if ($fileReport->hasMagicNumbers()) {
161
                    $fileReportList->addFileReport($fileReport);
162
                }
163
            } catch (\Exception $e) {
164
                $output->writeln($e->getMessage());
165
            }
166
167
            if ($input->getOption('progress')) {
168
                $progressBar->advance();
169
            }
170
        }
171
172
        if ($input->getOption('progress')) {
173
            $progressBar->finish();
174
        }
175
176
        if ($input->getOption('xml-output')) {
177
            $xmlOutput = new Printer\Xml($input->getOption('xml-output'));
178
            $xmlOutput->printData($output, $fileReportList, $hintList);
179
        }
180
181
        if ($output->getVerbosity() !== OutputInterface::VERBOSITY_QUIET) {
182
            $output->writeln('');
183
            $printer->printData($output, $fileReportList, $hintList);
184
            $output->writeln('<info>' . Timer::resourceUsage() . '</info>');
185
        }
186
187
        if ($input->getOption('non-zero-exit-on-violation') && $fileReportList->hasMagicNumbers()) {
188
            return self::EXIT_CODE_FAILURE;
189
        }
190
        return self::EXIT_CODE_SUCCESS;
191
    }
192
193
    /**
194
     * @param InputInterface $input
195
     * @return Option
196
     * @throws \Exception
197
     */
198
    private function createOption(InputInterface $input)
199
    {
200
        $option = new Option;
201
        $option->setIgnoreNumbers(array_map([$this, 'castToNumber'], $this->getCSVOption($input, 'ignore-numbers')));
202
        $option->setIgnoreFuncs($this->getCSVOption($input, 'ignore-funcs'));
203
        $option->setIncludeStrings($input->getOption('strings'));
204
        $option->setIncludeNumericStrings($input->getOption('include-numeric-string'));
205
        $option->setIgnoreStrings($this->getCSVOption($input, 'ignore-strings'));
206
        $option->setGiveHint($input->getOption('hint'));
207
        $option->setExtensions(
208
            (new ExtensionResolver())->resolve($this->getCSVOption($input, 'extensions'))
209
        );
210
211
        return $option;
212
    }
213
214
    /**
215
     * @param InputInterface $input
216
     * @param string $option
217
     *
218
     * @return array
219
     */
220
    private function getCSVOption(InputInterface $input, $option)
221
    {
222
        $result = $input->getOption($option);
223
        if (false === is_array($result)) {
224
            return array_filter(
225
                explode(',', $result),
226
                function ($value) {
227
                    return false === empty($value);
228
                }
229
            );
230
        }
231
232
        if (null === $result) {
233
            return [];
234
        }
235
236
        return $result;
237
    }
238
239
    /**
240
     * @param InputInterface $input
241
     *
242
     * @return PHPFinder
243
     */
244
    protected function createFinder(InputInterface $input)
245
    {
246
        return new PHPFinder(
247
            $input->getArgument('directory'),
248
            $input->getOption('exclude'),
249
            $input->getOption('exclude-path'),
250
            $input->getOption('exclude-file'),
251
            $this->getCSVOption($input, 'suffixes')
252
        );
253
    }
254
255
    /**
256
     * @param string $value
257
     *
258
     * @return int|float|string
259
     */
260
    private function castToNumber($value)
261
    {
262
        if (is_numeric($value)) {
263
            $value += 0; // '2' -> (int) 2, '2.' -> (float) 2.0
264
        }
265
266
        return $value;
267
    }
268
}
269