Completed
Push — master ( 9d14a0...ddbde7 )
by Дмитрий
02:59
created

CheckCommand   C

Complexity

Total Complexity 35

Size/Duplication

Total Lines 238
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 22

Test Coverage

Coverage 8.33%

Importance

Changes 7
Bugs 1 Features 1
Metric Value
c 7
b 1
f 1
dl 0
loc 238
ccs 12
cts 144
cp 0.0833
rs 5.2105
wmc 35
lcom 1
cbo 22

6 Methods

Rating   Name   Duplication   Size   Complexity  
A configure() 0 14 1
D execute() 0 97 10
A getMemoryUsage() 0 4 1
A getCompiler() 0 4 1
C parserFile() 0 47 8
C parseTopDefinitions() 0 46 14
1
<?php
2
/**
3
 * @author Patsura Dmitry https://github.com/ovr <[email protected]>
4
 */
5
6
namespace PHPSA\Command;
7
8
use PhpParser\NodeTraverser;
9
use PhpParser\ParserFactory;
10
use PHPSA\AliasManager;
11
use PHPSA\Analyzer\EventListener\ExpressionListener;
12
use PHPSA\Application;
13
use PHPSA\Compiler;
14
use PHPSA\Context;
15
use PHPSA\Definition\ClassDefinition;
16
use PHPSA\Definition\ClassMethod;
17
use PHPSA\Definition\FunctionDefinition;
18
use RecursiveDirectoryIterator;
19
use RecursiveIteratorIterator;
20
use RuntimeException;
21
use SplFileInfo;
22
use Exception;
23
use FilesystemIterator;
24
use PhpParser\Node;
25
use PhpParser\Parser;
26
use Symfony\Component\Console\Command\Command;
27
use Symfony\Component\Console\Input\InputArgument;
28
use Symfony\Component\Console\Input\InputInterface;
29
use Symfony\Component\Console\Input\InputOption;
30
use Symfony\Component\Console\Output\OutputInterface;
31
use Webiny\Component\EventManager\EventManager;
32
33
/**
34
 * Class CheckCommand
35
 * @package PHPSA\Command
36
 *
37
 * @method Application getApplication();
38
 */
39
class CheckCommand extends Command
40
{
41 1
    protected function configure()
42
    {
43 1
        $this
44 1
            ->setName('check')
45 1
            ->setDescription('SPA')
46 1
            ->addOption('blame', null, InputOption::VALUE_OPTIONAL, 'Git blame author for bad code ;)', false)
47 1
            ->addArgument('path', InputArgument::OPTIONAL, 'Path to check file or directory', '.')
48 1
            ->addOption(
49 1
                'report-json',
50 1
                null,
51 1
                InputOption::VALUE_REQUIRED,
52
                'Path to save detailed report in JSON format. Example: /tmp/report.json'
53 1
            );
54 1
    }
55
56
    protected function execute(InputInterface $input, OutputInterface $output)
57
    {
58
        $output->writeln('');
59
60
        if (extension_loaded('xdebug')) {
61
            $output->writeln('<error>It is highly recommended to disable the XDebug extension before invoking this command.</error>');
62
        }
63
64
        $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7, new \PhpParser\Lexer\Emulative(
65
            array(
66
                'usedAttributes' => array(
67
                    'comments',
68
                    'startLine',
69
                    'endLine',
70
                    'startTokenPos',
71
                    'endTokenPos'
72
                )
73
            )
74
        ));
75
76
        /** @var Application $application */
77
        $application = $this->getApplication();
78
        $application->compiler = new Compiler();
79
80
        $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...
81
        $em->listen(
82
            Compiler\Event\ExpressionBeforeCompile::EVENT_NAME
83
        )->handler(new ExpressionListener())->method('beforeCompile');
84
85
        $context = new Context($output, $application, $em);
86
87
        /**
88
         * Store option's in application's configuration
89
         */
90
        $application->getConfiguration()->setValue('blame', $input->getOption('blame'));
91
92
        $astTraverser = new \PhpParser\NodeTraverser();
93
        $astTraverser->addVisitor(new \PhpParser\NodeVisitor\NameResolver);
94
95
        $path = $input->getArgument('path');
96
        if (is_dir($path)) {
97
            $directoryIterator = new RecursiveIteratorIterator(
98
                new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)
99
            );
100
            $output->writeln('Scanning directory <info>' . $path . '</info>');
101
102
            $count = 0;
103
104
            /** @var SplFileInfo $file */
105
            foreach ($directoryIterator as $file) {
106
                if ($file->getExtension() != 'php') {
107
                    continue;
108
                }
109
110
                $context->debug($file->getPathname());
111
                $count++;
112
            }
113
114
            $output->writeln("Found <info>{$count} files</info>");
115
116
            if ($count > 100) {
117
                $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>');
118
            }
119
120
            $output->writeln('');
121
122
            /** @var SplFileInfo $file */
123
            foreach ($directoryIterator as $file) {
124
                if ($file->getExtension() != 'php') {
125
                    continue;
126
                }
127
128
                $this->parserFile($file->getPathname(), $parser, $astTraverser, $context);
129
            }
130
        } elseif (is_file($path)) {
131
            $this->parserFile($path, $parser, $astTraverser, $context);
132
        }
133
134
135
        /**
136
         * Step 2 Recursive check ...
137
         */
138
        $application->compiler->compile($context);
139
140
        $jsonReport = $input->getOption('report-json');
141
        if ($jsonReport) {
142
            file_put_contents(
143
                $jsonReport,
144
                json_encode(
145
                    $this->getApplication()->getIssuesCollector()->getIssues()
146
                )
147
            );
148
        }
149
150
        $output->writeln('');
151
        $output->writeln('Memory usage: ' . $this->getMemoryUsage(false) . ' (peak: ' . $this->getMemoryUsage(true) . ') MB');
152
    }
153
154
    /**
155
     * @param boolean $type
156
     * @return float
157
     */
158
    protected function getMemoryUsage($type)
159
    {
160
        return round(memory_get_usage($type) / 1024 / 1024, 2);
161
    }
162
163
    /**
164
     * @return Compiler
165
     */
166
    protected function getCompiler()
167
    {
168
        return $this->getApplication()->compiler;
169
    }
170
171
    /**
172
     * @param string $filepath
173
     * @param Parser $parser
174
     * @param NodeTraverser $nodeTraverser
175
     * @param Context $context
176
     */
177
    protected function parserFile($filepath, Parser $parser, NodeTraverser $nodeTraverser, Context $context)
178
    {
179
        $context->setFilepath($filepath);
180
181
        try {
182
            if (!is_readable($filepath)) {
183
                throw new RuntimeException('File ' . $filepath . ' is not readable');
184
            }
185
186
            $context->debug('<comment>Precompile: ' . $filepath . '.</comment>');
187
188
            $code = file_get_contents($filepath);
189
            $astTree = $parser->parse($code);
190
191
            $nodeTraverser->traverse($astTree);
0 ignored issues
show
Bug introduced by
It seems like $astTree defined by $parser->parse($code) on line 189 can also be of type null; however, PhpParser\NodeTraverser::traverse() does only seem to accept array<integer,object<PhpParser\Node>>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
192
193
            $context->aliasManager = new AliasManager();
194
            $namespace = null;
195
196
            /**
197
             * Step 1 Precompile
198
             */
199
            foreach ($astTree as $topStatement) {
0 ignored issues
show
Bug introduced by
The expression $astTree of type array<integer,object<PhpParser\Node>>|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
200
                if ($topStatement instanceof Node\Stmt\Namespace_) {
201
                    /**
202
                     * Namespace block can be created without NS name
203
                     */
204
                    if ($topStatement->name) {
205
                        $namespace = $topStatement->name->toString();
206
                        $context->aliasManager->setNamespace($namespace);
207
                    }
208
209
                    if ($topStatement->stmts) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $topStatement->stmts of type PhpParser\Node[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
210
                        $this->parseTopDefinitions($topStatement->stmts, $context->aliasManager, $filepath);
0 ignored issues
show
Documentation introduced by
$topStatement->stmts is of type array<integer,object<PhpParser\Node>>, but the function expects a object<PhpParser\Node\Stmt>.

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...
211
                    }
212
                } else {
213
                    $this->parseTopDefinitions($topStatement, $context->aliasManager, $filepath);
214
                }
215
            }
216
            
217
            $context->clear();
218
        } catch (\PhpParser\Error $e) {
219
            $context->sytaxError($e, $filepath);
220
        } catch (Exception $e) {
221
            $context->output->writeln("<error>{$e->getMessage()}</error>");
222
        }
223
    }
224
225
    /**
226
     * @param Node\Stmt $topStatement
227
     * @param AliasManager $aliasManager
228
     * @param string $filepath
229
     */
230
    protected function parseTopDefinitions($topStatement, AliasManager $aliasManager, $filepath)
231
    {
232
        foreach ($topStatement as $statement) {
0 ignored issues
show
Bug introduced by
The expression $topStatement of type object<PhpParser\Node\Stmt> is not traversable.
Loading history...
233
            if ($statement instanceof Node\Stmt\Use_) {
234
                if (count($statement->uses) > 0) {
235
                    foreach ($statement->uses as $use) {
236
                        $aliasManager->add($use->name->parts);
237
                    }
238
                }
239
            } elseif ($statement instanceof Node\Stmt\Class_) {
240
                $definition = new ClassDefinition($statement->name, $statement->type);
241
                $definition->setFilepath($filepath);
242
                $definition->setNamespace($aliasManager->getNamespace());
243
244
                if ($statement->extends) {
245
                    $definition->setExtendsClass($statement->extends->toString());
246
                }
247
248
                if ($statement->implements) {
249
                    foreach ($statement->implements as $interface) {
250
                        $definition->addInterface($interface->toString());
251
                    }
252
                }
253
254
                foreach ($statement->stmts as $stmt) {
255
                    if ($stmt instanceof Node\Stmt\ClassMethod) {
256
                        $method = new ClassMethod($stmt->name, $stmt, $stmt->type);
257
258
                        $definition->addMethod($method);
259
                    } elseif ($stmt instanceof Node\Stmt\Property) {
260
                        $definition->addProperty($stmt);
261
                    } elseif ($stmt instanceof Node\Stmt\ClassConst) {
262
                        $definition->addConst($stmt);
263
                    }
264
                }
265
266
                $this->getCompiler()->addClass($definition);
267
            } elseif ($statement instanceof Node\Stmt\Function_) {
268
                $definition = new FunctionDefinition($statement->name, $statement);
269
                $definition->setFilepath($filepath);
270
                $definition->setNamespace($aliasManager->getNamespace());
271
272
                $this->getCompiler()->addFunction($definition);
273
            }
274
        }
275
    }
276
}
277