Completed
Pull Request — master (#283)
by Enrico
04:27
created

CheckCommand::getMemoryUsage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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 886
    protected function configure()
41
    {
42 886
        $this
43 886
            ->setName('check')
44 886
            ->setDescription('Runs compiler and analyzers on all files in path')
45 886
            ->addOption('blame', null, InputOption::VALUE_NONE, 'Git blame author for bad code ;)')
46 886
            ->addOption('config-file', null, InputOption::VALUE_REQUIRED, 'Path to the configuration file.')
47 886
            ->addArgument('path', InputArgument::OPTIONAL, 'Path to check file or directory', '.')
48 886
            ->addOption(
49 886
                'report-json',
50 886
                null,
51 886
                InputOption::VALUE_REQUIRED,
52
                'Path to save detailed report in JSON format. Example: /tmp/report.json'
53 886
            );
54 886
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59 1
    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...
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 1
        $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7, new \PhpParser\Lexer\Emulative([
75
            'usedAttributes' => [
76 1
                'comments',
77 1
                'startLine',
78 1
                'endLine',
79 1
                'startTokenPos',
80
                'endTokenPos'
81 1
            ]
82 1
        ]));
83
84
        /** @var Application $application */
85 1
        $application = $this->getApplication();
86 1
        $application->compiler = new Compiler();
87
88 1
        $configFile = $input->getOption('config-file') ?: '.phpsa.yml';
89 1
        $configDir = realpath($input->getArgument('path'));
90 1
        $application->configuration = $this->loadConfiguration($configFile, $configDir);
91
92 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...
93 1
        Analyzer\Factory::factory($em, $application->configuration);
94 1
        $context = new Context($output, $application, $em);
95
96
        /**
97
         * Store option's in application's configuration
98
         */
99 1
        if ($input->getOption('blame')) {
100
            $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...
101
        }
102
103 1
        $fileParser = new FileParser(
104 1
            $parser,
105 1
            $this->getCompiler()
106 1
        );
107
108 1
        $path = $input->getArgument('path');
109 1
        if (is_dir($path)) {
110 1
            $directoryIterator = new RecursiveIteratorIterator(
111 1
                new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)
112 1
            );
113 1
            $output->writeln('Scanning directory <info>' . $path . '</info>');
114
115 1
            $count = 0;
116
117
            /** @var SplFileInfo $file */
118 1
            foreach ($directoryIterator as $file) {
119 1
                if ($file->getExtension() !== 'php') {
120
                    continue;
121
                }
122
123 1
                $context->debug($file->getPathname());
124 1
                $count++;
125 1
            }
126
127 1
            $output->writeln("Found <info>{$count} files</info>");
128
129 1
            if ($count > 100) {
130
                $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>');
131
            }
132
133 1
            $output->writeln('');
134
135
            /** @var SplFileInfo $file */
136 1
            foreach ($directoryIterator as $file) {
137 1
                if ($file->getExtension() !== 'php') {
138
                    continue;
139
                }
140
141 1
                $fileParser->parserFile($file->getPathname(), $context);
142 1
            }
143 1
        } elseif (is_file($path)) {
144
            $fileParser->parserFile($path, $context);
145
        }
146
147
148
        /**
149
         * Step 2 Recursive check ...
150
         */
151 1
        $application->compiler->compile($context);
152
153 1
        $jsonReport = $input->getOption('report-json');
154 1
        if ($jsonReport) {
155
            file_put_contents(
156
                $jsonReport,
157
                json_encode(
158
                    $this->getApplication()->getIssuesCollector()->getIssues()
159
                )
160
            );
161
        }
162
163 1
        $output->writeln('');
164 1
        $output->writeln('Memory usage: ' . $this->getMemoryUsage(false) . ' (peak: ' . $this->getMemoryUsage(true) . ') MB');
165 1
    }
166
167
    /**
168
     * @param boolean $type
169
     * @return float
170
     */
171 1
    protected function getMemoryUsage($type)
172
    {
173 1
        return round(memory_get_usage($type) / 1024 / 1024, 2);
174
    }
175
176
    /**
177
     * @return Compiler
178
     */
179 1
    protected function getCompiler()
180
    {
181 1
        return $this->getApplication()->compiler;
182
    }
183
184
    /**
185
     * @param string $configFile
186
     * @param string $configurationDirectory
187
     *
188
     * @return Configuration
189
     */
190 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...
191
    {
192 1
        $loader = new ConfigurationLoader(new FileLocator([
193 1
            getcwd(),
194
            $configurationDirectory
195 1
        ]));
196
197 1
        return new Configuration(
198 1
            $loader->load($configFile),
199 1
            Analyzer\Factory::getPassesConfigurations()
200 1
        );
201
    }
202
}
203