Completed
Pull Request — master (#139)
by Kévin
39:24 queued 35:07
created

CheckCommand   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 172
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 15

Test Coverage

Coverage 13.83%

Importance

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

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