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