Completed
Push — master ( cc5436...181e05 )
by Дмитрий
03:10 queued 36s
created

CheckCommand::configure()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 1

Importance

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