Completed
Push — master ( f4606a...adf7a1 )
by Дмитрий
04:05
created

CheckCommand::execute()   F

Complexity

Conditions 17
Paths 480

Size

Total Lines 126
Code Lines 73

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 58
CRAP Score 26.9758

Importance

Changes 0
Metric Value
cc 17
eloc 73
nc 480
nop 2
dl 0
loc 126
ccs 58
cts 86
cp 0.6744
crap 26.9758
rs 3.221
c 0
b 0
f 0

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