Completed
Pull Request — master (#235)
by Kévin
04:08 queued 20s
created

CheckCommand   B

Complexity

Total Complexity 18

Size/Duplication

Total Lines 183
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 17

Test Coverage

Coverage 13.83%

Importance

Changes 0
Metric Value
dl 0
loc 183
ccs 13
cts 94
cp 0.1383
rs 7.8571
c 0
b 0
f 0
wmc 18
lcom 1
cbo 17

6 Methods

Rating   Name   Duplication   Size   Complexity  
A configure() 0 15 1
C execute() 0 92 12
A getMemoryUsage() 0 4 1
A loadConfiguration() 0 12 1
A getParser() 0 12 1
A getIssuesReporter() 0 12 2
1
<?php
2
/**
3
 * @author Patsura Dmitry https://github.com/ovr <[email protected]>
4
 */
5
6
namespace PHPSA\Command;
7
8
use PhpParser\ParserFactory;
9
use PHPSA\Analyzer;
10
use PHPSA\Application;
11
use PHPSA\Compiler;
12
use PHPSA\Configuration;
13
use PHPSA\ConfigurationLoader;
14
use PHPSA\Context;
15
use PHPSA\Definition\FileParser;
16
use PHPSA\Report\ReporterFactory;
17
use RecursiveDirectoryIterator;
18
use RecursiveIteratorIterator;
19
use SplFileInfo;
20
use FilesystemIterator;
21
use Symfony\Component\Config\FileLocator;
22
use Symfony\Component\Console\Command\Command;
23
use Symfony\Component\Console\Input\InputArgument;
24
use Symfony\Component\Console\Input\InputInterface;
25
use Symfony\Component\Console\Input\InputOption;
26
use Symfony\Component\Console\Output\OutputInterface;
27
use Symfony\Component\Console\Output\StreamOutput;
28
use Webiny\Component\EventManager\EventManager;
29
use PHPSA\Analyzer\Pass as AnalyzerPass;
30
31
/**
32
 * Class CheckCommand
33
 * @package PHPSA\Command
34
 *
35
 * @method Application getApplication();
36
 */
37
class CheckCommand extends Command
38
{
39
40
    /**
41
     * Configures the command.
42
     */
43 868
    protected function configure()
44
    {
45 868
        $this
46 868
            ->setName('check')
47 868
            ->setDescription('SPA')
48 868
            ->addOption('blame', null, InputOption::VALUE_NONE, 'Git blame author for bad code ;)')
49 868
            ->addOption('config-file', null, InputOption::VALUE_REQUIRED, 'Path to the configuration file.')
50 868
            ->addArgument('path', InputArgument::OPTIONAL, 'Path to check file or directory', '.')
51 868
            ->addOption(
52 868
                'report-json',
53 868
                null,
54 868
                InputOption::VALUE_REQUIRED,
55
                'Path to save detailed report in JSON format. Example: /tmp/report.json'
56 868
            );
57 868
    }
58
59
    /**
60
     * Executes the command.
61
     *
62
     * @param InputInterface $input
63
     * @param OutputInterface $output
64
     */
65
    protected function execute(InputInterface $input, OutputInterface $output)
0 ignored issues
show
Complexity introduced by
This operation has 600 execution paths which exceeds the configured maximum of 200.

A high number of execution paths generally suggests many nested conditional statements and make the code less readible. This can usually be fixed by splitting the method into several smaller methods.

You can also find more information in the “Code” section of your repository.

Loading history...
66
    {
67
        $output->writeln('');
68
69
        if (extension_loaded('xdebug')) {
70
            /**
71
             * This will disable only showing stack traces on error conditions.
72
             */
73
            if (function_exists('xdebug_disable')) {
74
                xdebug_disable();
75
            }
76
77
            $output->writeln('<error>It is highly recommended to disable the XDebug extension before invoking this command.</error>');
78
        }
79
80
        /** @var Application $application */
81
        $application = $this->getApplication();
82
        $application->compiler = new Compiler();
83
84
        $configFile = $input->getOption('config-file') ?: '.phpsa.yml';
85
        $configDir = realpath($input->getArgument('path'));
86
        $application->configuration = $this->loadConfiguration($configFile, $configDir);
87
88
        $em = EventManager::getInstance();
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $em. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
89
        Analyzer\Factory::factory($em, $application->configuration);
90
        $context = new Context($output, $application, $em);
91
92
        /**
93
         * Store option's in application's configuration
94
         */
95
        if ($input->getOption('blame')) {
96
            $application->configuration->setValue('blame', true);
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
97
        }
98
99
        $fileParser = new FileParser(
100
            $this->getParser(),
101
            $application->compiler
102
        );
103
104
        $path = $input->getArgument('path');
105
        if (is_dir($path)) {
106
            $directoryIterator = new RecursiveIteratorIterator(
107
                new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)
108
            );
109
            $output->writeln('Scanning directory <info>' . $path . '</info>');
110
111
            $count = 0;
112
113
            /** @var SplFileInfo $file */
114
            foreach ($directoryIterator as $file) {
115
                if ($file->getExtension() !== 'php') {
116
                    continue;
117
                }
118
119
                $context->debug($file->getPathname());
120
                $count++;
121
            }
122
123
            $output->writeln("Found <info>{$count} files</info>");
124
125
            if ($count > 100) {
126
                $output->writeln('<comment>Caution: You are trying to scan a lot of files; this might be slow. For bigger libraries, consider setting up a dedicated platform or using ci.lowl.io.</comment>');
127
            }
128
129
            $output->writeln('');
130
131
            /** @var SplFileInfo $file */
132
            foreach ($directoryIterator as $file) {
133
                if ($file->getExtension() !== 'php') {
134
                    continue;
135
                }
136
137
                $fileParser->parserFile($file->getPathname(), $context);
138
            }
139
        } elseif (is_file($path)) {
140
            $fileParser->parserFile($path, $context);
141
        }
142
143
        /**
144
         * Step 2 Recursive check ...
145
         */
146
        $application->compiler->compile($context);
147
148
        /**
149
         * Step 3 Report!
150
         */
151
        $reporter = $this->getIssuesReporter($input, $output);
152
        $reporter->report($application->getIssuesCollector());
153
154
        $output->writeln('');
155
        $output->writeln('Memory usage: ' . $this->getMemoryUsage(false) . ' (peak: ' . $this->getMemoryUsage(true) . ') MB');
156
    }
157
158
    /**
159
     * @param boolean $type
160
     * @return float
161
     */
162
    protected function getMemoryUsage($type)
163
    {
164
        return round(memory_get_usage($type) / 1024 / 1024, 2);
165
    }
166
167
    /**
168
     * @param string $configFile
169
     * @param string $configurationDirectory
170
     *
171
     * @return Configuration
172
     */
173
    protected function loadConfiguration($configFile, $configurationDirectory)
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $configurationDirectory exceeds the maximum configured length of 20.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
174
    {
175
        $loader = new ConfigurationLoader(new FileLocator([
176
            getcwd(),
177
            $configurationDirectory
178
        ]));
179
180
        return new Configuration(
181
            $loader->load($configFile),
182
            Analyzer\Factory::getPassesConfigurations()
183
        );
184
    }
185
186
    /**
187
     * @return \PhpParser\Parser
188
     */
189
    protected function getParser()
190
    {
191
        return (new ParserFactory())->create(ParserFactory::PREFER_PHP7, new \PhpParser\Lexer\Emulative([
192
            'usedAttributes' => [
193
                'comments',
194
                'startLine',
195
                'endLine',
196
                'startTokenPos',
197
                'endTokenPos'
198
            ]
199
        ]));
200
    }
201
202
    /**
203
     * @param InputInterface $input
204
     * @param OutputInterface $output
205
     * @return \PHPSA\Report\Reporter
206
     */
207
    protected function getIssuesReporter(InputInterface $input, OutputInterface $output)
208
    {
209
        $jsonReport = $input->getOption('report-json');
210
        $reporterOutput = $output;
211
        $reportFormat = 'text';
212
213
        if ($jsonReport) {
214
            $reporterOutput = new StreamOutput($jsonReport);
215
        }
216
217
        return ReporterFactory::create()->getReporter($reportFormat, $reporterOutput);
218
    }
219
}
220