Completed
Push — master ( 0f1317...e5807f )
by Дмитрий
05:32 queued 02:45
created

CheckCommand::parseTopDefinitions()   C

Complexity

Conditions 14
Paths 28

Size

Total Lines 46
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 210
Metric Value
dl 0
loc 46
ccs 0
cts 39
cp 0
rs 5.0744
cc 14
eloc 29
nc 28
nop 3
crap 210

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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