Completed
Push — master ( 90ed95...4bbc63 )
by Дмитрий
06:02
created

CheckCommand   C

Complexity

Total Complexity 35

Size/Duplication

Total Lines 240
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 22

Test Coverage

Coverage 6.99%

Importance

Changes 6
Bugs 0 Features 3
Metric Value
wmc 35
c 6
b 0
f 3
lcom 1
cbo 22
dl 0
loc 240
ccs 10
cts 143
cp 0.0699
rs 5.2105

6 Methods

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