Completed
Pull Request — master (#235)
by Kévin
03:45
created

CheckCommand   B

Complexity

Total Complexity 17

Size/Duplication

Total Lines 172
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 16

Test Coverage

Coverage 13.83%

Importance

Changes 0
Metric Value
dl 0
loc 172
ccs 13
cts 94
cp 0.1383
rs 8.4614
c 0
b 0
f 0
wmc 17
lcom 1
cbo 16

5 Methods

Rating   Name   Duplication   Size   Complexity  
A configure() 0 15 1
D execute() 0 107 13
A getMemoryUsage() 0 4 1
A getCompiler() 0 4 1
A loadConfiguration() 0 12 1
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 Webiny\Component\EventManager\EventManager;
28
use PHPSA\Analyzer\Pass as AnalyzerPass;
29
30
/**
31
 * Class CheckCommand
32
 * @package PHPSA\Command
33
 *
34
 * @method Application getApplication();
35
 */
36
class CheckCommand extends Command
37
{
38
39
    /**
40
     * Configures the command.
41 868
     */
42
    protected function configure()
43 868
    {
44 868
        $this
45 868
            ->setName('check')
46 868
            ->setDescription('SPA')
47 868
            ->addOption('blame', null, InputOption::VALUE_NONE, 'Git blame author for bad code ;)')
48 868
            ->addOption('config-file', null, InputOption::VALUE_REQUIRED, 'Path to the configuration file.')
49 868
            ->addArgument('path', InputArgument::OPTIONAL, 'Path to check file or directory', '.')
50 868
            ->addOption(
51 868
                'report-json',
52 868
                null,
53
                InputOption::VALUE_REQUIRED,
54 868
                'Path to save detailed report in JSON format. Example: /tmp/report.json'
55 868
            );
56
    }
57
58
    /**
59
     * Executes the command.
60
     *
61
     * @param InputInterface $input
62
     * @param OutputInterface $output
63
     */
64
    protected function execute(InputInterface $input, OutputInterface $output)
0 ignored issues
show
Complexity introduced by
This operation has 1200 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...
65
    {
66
        $output->writeln('');
67
68
        if (extension_loaded('xdebug')) {
69
            /**
70
             * This will disable only showing stack traces on error conditions.
71
             */
72
            if (function_exists('xdebug_disable')) {
73
                xdebug_disable();
74
            }
75
76
            $output->writeln('<error>It is highly recommended to disable the XDebug extension before invoking this command.</error>');
77
        }
78
79
        $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7, new \PhpParser\Lexer\Emulative([
80
            'usedAttributes' => [
81
                'comments',
82
                'startLine',
83
                'endLine',
84
                'startTokenPos',
85
                'endTokenPos'
86
            ]
87
        ]));
88
89
        /** @var Application $application */
90
        $application = $this->getApplication();
91
        $application->compiler = new Compiler();
92
93
        $configFile = $input->getOption('config-file') ?: '.phpsa.yml';
94
        $configDir = realpath($input->getArgument('path'));
95
        $application->configuration = $this->loadConfiguration($configFile, $configDir);
96
97
        $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...
98
        Analyzer\Factory::factory($em, $application->configuration);
99
        $context = new Context($output, $application, $em);
100
101
        /**
102
         * Store option's in application's configuration
103
         */
104
        if ($input->getOption('blame')) {
105
            $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...
106
        }
107
108
        $fileParser = new FileParser(
109
            $parser,
110
            $this->getCompiler()
111
        );
112
113
        $path = $input->getArgument('path');
114
        if (is_dir($path)) {
115
            $directoryIterator = new RecursiveIteratorIterator(
116
                new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)
117
            );
118
            $output->writeln('Scanning directory <info>' . $path . '</info>');
119
120
            $count = 0;
121
122
            /** @var SplFileInfo $file */
123
            foreach ($directoryIterator as $file) {
124
                if ($file->getExtension() !== 'php') {
125
                    continue;
126
                }
127
128
                $context->debug($file->getPathname());
129
                $count++;
130
            }
131
132
            $output->writeln("Found <info>{$count} files</info>");
133
134
            if ($count > 100) {
135
                $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>');
136
            }
137
138
            $output->writeln('');
139
140
            /** @var SplFileInfo $file */
141
            foreach ($directoryIterator as $file) {
142
                if ($file->getExtension() !== 'php') {
143
                    continue;
144
                }
145
146
                $fileParser->parserFile($file->getPathname(), $context);
147
            }
148
        } elseif (is_file($path)) {
149
            $fileParser->parserFile($path, $context);
150
        }
151
152
153
        /**
154
         * Step 2 Recursive check ...
155
         */
156
        $application->compiler->compile($context);
157
158
        $jsonReport = $input->getOption('report-json');
159
        if ($jsonReport) {
160
            $reporter = ReporterFactory::create()->getReporter('json');
161
162
            file_put_contents(
163
                $jsonReport,
164
                $reporter->report($this->getApplication()->getIssuesCollector())
165
            );
166
        }
167
168
        $output->writeln('');
169
        $output->writeln('Memory usage: ' . $this->getMemoryUsage(false) . ' (peak: ' . $this->getMemoryUsage(true) . ') MB');
170
    }
171
172
    /**
173
     * @param boolean $type
174
     * @return float
175
     */
176
    protected function getMemoryUsage($type)
177
    {
178
        return round(memory_get_usage($type) / 1024 / 1024, 2);
179
    }
180
181
    /**
182
     * @return Compiler
183
     */
184
    protected function getCompiler()
185
    {
186
        return $this->getApplication()->compiler;
187
    }
188
189
    /**
190
     * @param string $configFile
191
     * @param string $configurationDirectory
192
     *
193
     * @return Configuration
194
     */
195
    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...
196
    {
197
        $loader = new ConfigurationLoader(new FileLocator([
198
            getcwd(),
199
            $configurationDirectory
200
        ]));
201
202
        return new Configuration(
203
            $loader->load($configFile),
204
            Analyzer\Factory::getPassesConfigurations()
205
        );
206
    }
207
}
208