Completed
Push — master ( 196386...55f8b4 )
by Дмитрий
05:49
created

CheckCommand::parserFile()   C

Complexity

Conditions 8
Paths 47

Size

Total Lines 47
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 8
eloc 25
c 3
b 0
f 0
nc 47
nop 4
dl 0
loc 47
ccs 0
cts 28
cp 0
crap 72
rs 5.7377
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\AstTraverser;
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
32
/**
33
 * Class CheckCommand
34
 * @package PHPSA\Command
35
 *
36
 * @method Application getApplication();
37
 */
38
class CheckCommand extends Command
39
{
40 366
    protected function configure()
41
    {
42 366
        $this
43 366
            ->setName('check')
44 366
            ->setDescription('SPA')
45 366
            ->addOption('blame', null, InputOption::VALUE_OPTIONAL, 'Git blame author for bad code ;)', false)
46 366
            ->addArgument('path', InputArgument::OPTIONAL, 'Path to check file or directory', '.')
47 366
            ->addOption(
48 366
                'report-json',
49 366
                null,
50 366
                InputOption::VALUE_REQUIRED,
51
                'Path to save detailed report in JSON format. Example: /tmp/report.json'
52 366
            );
53 366
    }
54
55
    protected function execute(InputInterface $input, OutputInterface $output)
56
    {
57
        $output->writeln('');
58
59
        if (extension_loaded('xdebug')) {
60
            $output->writeln('<error>It is highly recommended to disable the XDebug extension before invoking this command.</error>');
61
        }
62
63
        $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7, new \PhpParser\Lexer\Emulative(
64
            array(
65
                'usedAttributes' => array(
66
                    'comments',
67
                    'startLine',
68
                    'endLine',
69
                    'startTokenPos',
70
                    'endTokenPos'
71
                )
72
            )
73
        ));
74
75
        /** @var Application $application */
76
        $application = $this->getApplication();
77
        $application->compiler = new Compiler();
78
79
        $context = new Context($output, $application);
80
81
        /**
82
         * Store option's in application's configuration
83
         */
84
        $application->getConfiguration()->setValue('blame', $input->getOption('blame'));
85
86
        $astTraverser = new \PhpParser\NodeTraverser();
87
        $astTraverser->addVisitor(new \PhpParser\NodeVisitor\NameResolver);
88
89
        $path = $input->getArgument('path');
90
        if (is_dir($path)) {
91
            $directoryIterator = new RecursiveIteratorIterator(
92
                new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)
93
            );
94
            $output->writeln('Scanning directory <info>' . $path . '</info>');
95
96
            $count = 0;
97
98
            /** @var SplFileInfo $file */
99
            foreach ($directoryIterator as $file) {
100
                if ($file->getExtension() != 'php') {
101
                    continue;
102
                }
103
104
                $context->debug($file->getPathname());
105
                $count++;
106
            }
107
108
            $output->writeln("Found <info>{$count} files</info>");
109
110
            if ($count > 100) {
111
                $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>');
112
            }
113
114
            $output->writeln('');
115
116
            /** @var SplFileInfo $file */
117
            foreach ($directoryIterator as $file) {
118
                if ($file->getExtension() != 'php') {
119
                    continue;
120
                }
121
122
                $this->parserFile($file->getPathname(), $parser, $astTraverser, $context);
123
            }
124
        } elseif (is_file($path)) {
125
            $this->parserFile($path, $parser, $astTraverser, $context);
126
        }
127
128
129
        /**
130
         * Step 2 Recursive check ...
131
         */
132
        $application->compiler->compile($context);
133
134
        $jsonReport = $input->getOption('report-json');
135
        if ($jsonReport) {
136
            file_put_contents(
137
                $jsonReport,
138
                json_encode(
139
                    $this->getApplication()->getIssuesCollector()->getIssues()
140
                )
141
            );
142
        }
143
144
        $output->writeln('');
145
        $output->writeln('Memory usage: ' . $this->getMemoryUsage(false) . ' (peak: ' . $this->getMemoryUsage(true) . ') MB');
146
    }
147
148
    /**
149
     * @param boolean $type
150
     * @return float
151
     */
152
    protected function getMemoryUsage($type)
153
    {
154
        return round(memory_get_usage($type) / 1024 / 1024, 2);
155
    }
156
157
    /**
158
     * @return Compiler
159
     */
160
    protected function getCompiler()
161
    {
162
        return $this->getApplication()->compiler;
163
    }
164
165
    /**
166
     * @param string $filepath
167
     * @param Parser $parser
168
     * @param NodeTraverser $nodeTraverser
169
     * @param Context $context
170
     */
171
    protected function parserFile($filepath, Parser $parser, NodeTraverser $nodeTraverser, Context $context)
172
    {
173
        $context->setFilepath($filepath);
174
175
        try {
176
            if (!is_readable($filepath)) {
177
                throw new RuntimeException('File ' . $filepath . ' is not readable');
178
            }
179
180
            $context->debug('<comment>Precompile: ' . $filepath . '.</comment>');
181
182
            $code = file_get_contents($filepath);
183
            $astTree = $parser->parse($code);
184
185
            $nodeTraverser->traverse($astTree);
0 ignored issues
show
Bug introduced by
It seems like $astTree defined by $parser->parse($code) on line 183 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...
186
187
            $context->aliasManager = new AliasManager();
188
            $namespace = null;
189
190
            /**
191
             * Step 1 Precompile
192
             */
193
            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...
194
                if ($topStatement instanceof Node\Stmt\Namespace_) {
195
                    /**
196
                     * Namespace block can be created without NS name
197
                     */
198
                    if ($topStatement->name) {
199
                        $namespace = $topStatement->name->toString();
200
                        $context->aliasManager->setNamespace($namespace);
201
                    }
202
203
                    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...
204
                        $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...
205
                    }
206
                } else {
207
                    $this->parseTopDefinitions($topStatement, $context->aliasManager, $filepath);
208
                }
209
            }
210
            
211
            $context->clear();
212
        } catch (\PhpParser\Error $e) {
213
            $context->sytaxError($e, $filepath);
214
        } catch (Exception $e) {
215
            $context->output->writeln("<error>{$e->getMessage()}</error>");
216
        }
217
    }
218
219
    /**
220
     * @param Node\Stmt $topStatement
221
     * @param AliasManager $aliasManager
222
     * @param string $filepath
223
     */
224
    protected function parseTopDefinitions($topStatement, AliasManager $aliasManager, $filepath)
225
    {
226
        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...
227
            if ($statement instanceof Node\Stmt\Use_) {
228
                if (count($statement->uses) > 0) {
229
                    foreach ($statement->uses as $use) {
230
                        $aliasManager->add($use->name->parts);
231
                    }
232
                }
233
            } elseif ($statement instanceof Node\Stmt\Class_) {
234
                $definition = new ClassDefinition($statement->name, $statement->type);
235
                $definition->setFilepath($filepath);
236
                $definition->setNamespace($aliasManager->getNamespace());
237
238
                if ($statement->extends) {
239
                    $definition->setExtendsClass($statement->extends->toString());
240
                }
241
242
                if ($statement->implements) {
243
                    foreach ($statement->implements as $interface) {
244
                        $definition->addInterface($interface->toString());
245
                    }
246
                }
247
248
                foreach ($statement->stmts as $stmt) {
249
                    if ($stmt instanceof Node\Stmt\ClassMethod) {
250
                        $method = new ClassMethod($stmt->name, $stmt, $stmt->type);
251
252
                        $definition->addMethod($method);
253
                    } elseif ($stmt instanceof Node\Stmt\Property) {
254
                        $definition->addProperty($stmt);
255
                    } elseif ($stmt instanceof Node\Stmt\ClassConst) {
256
                        $definition->addConst($stmt);
257
                    }
258
                }
259
260
                $this->getCompiler()->addClass($definition);
261
            } elseif ($statement instanceof Node\Stmt\Function_) {
262
                $definition = new FunctionDefinition($statement->name, $statement);
263
                $definition->setFilepath($filepath);
264
                $definition->setNamespace($aliasManager->getNamespace());
265
266
                $this->getCompiler()->addFunction($definition);
267
            }
268
        }
269
    }
270
}
271