Completed
Pull Request — master (#193)
by Enrico
06:57 queued 02:48
created

FileParser   C

Complexity

Total Complexity 31

Size/Duplication

Total Lines 159
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 21

Test Coverage

Coverage 68.75%

Importance

Changes 0
Metric Value
dl 0
loc 159
ccs 66
cts 96
cp 0.6875
rs 5.9888
c 0
b 0
f 0
wmc 31
lcom 1
cbo 21

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
C parserFile() 0 51 9
C parseTopDefinitions() 0 66 21
1
<?php
2
/**
3
 * @author Patsura Dmitry https://github.com/ovr <[email protected]>
4
 */
5
6
namespace PHPSA\Definition;
7
8
use Exception;
9
use PHPSA\AliasManager;
10
use PHPSA\Compiler;
11
use PHPSA\Context;
12
use PhpParser\Node;
13
use RuntimeException;
14
15
class FileParser
16
{
17
    /**
18
     * @var \PhpParser\Parser
19
     */
20
    protected $parser;
21
22
    /**
23
     * @var \PhpParser\NodeTraverser
24
     */
25
    protected $nodeTraverser;
26
27
    /**
28
     * @var Compiler
29
     */
30
    protected $compiler;
31
32
    /**
33
     * @param \PhpParser\Parser $parser
34
     * @param Compiler $compiler
35
     */
36 30
    public function __construct(\PhpParser\Parser $parser, Compiler $compiler)
37
    {
38 30
        $this->nodeTraverser = new \PhpParser\NodeTraverser();
39 30
        $this->nodeTraverser->addVisitor(new \PhpParser\NodeVisitor\NameResolver);
40
41 30
        $this->parser = $parser;
42 30
        $this->compiler = $compiler;
43 30
    }
44
45
    /**
46
     * @param string $filepath
47
     * @param Context $context
48
     * @throws RuntimeException when filepath is not readable
49
     */
50 30
    public function parserFile($filepath, Context $context)
51
    {
52 30
        $context->setFilepath($filepath);
53
54
        try {
55 30
            if (!is_readable($filepath)) {
56
                throw new RuntimeException('File ' . $filepath . ' is not readable');
57
            }
58
59 30
            $context->debug('<comment>Precompile: ' . $filepath . '.</comment>');
60
61 30
            $code = file_get_contents($filepath);
62 30
            $astTree = $this->parser->parse($code);
63
64 30
            $this->nodeTraverser->traverse($astTree);
0 ignored issues
show
Bug introduced by
It seems like $astTree defined by $this->parser->parse($code) on line 62 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...
65
66 30
            $context->aliasManager = new AliasManager();
67 30
            $namespace = null;
68
69
            /**
70
             * Step 1 Precompile
71
             */
72 30
            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...
73 30
                if ($topStatement instanceof Node\Stmt\Namespace_) {
74
                    /**
75
                     * Namespace block can be created without NS name
76
                     */
77 30
                    if ($topStatement->name) {
78 30
                        $namespace = $topStatement->name->toString();
79 30
                        $context->aliasManager->setNamespace($namespace);
80 30
                    }
81
82 30
                    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...
83 30
                        $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\St...t<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...
84 30
                    }
85 30
                } else {
86
                    if (is_array($topStatement)) {
87
                        $this->parseTopDefinitions($topStatement, $context->aliasManager, $filepath);
88
                    } else {
89
                        $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\St...t<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...
90
                    }
91
                }
92 30
            }
93
94 30
            $context->clear();
95 30
        } catch (\PhpParser\Error $e) {
96
            $context->syntaxError($e, $filepath);
97
        } catch (Exception $e) {
98
            $context->output->writeln("<error>{$e->getMessage()}</error>");
99
        }
100 30
    }
101
102
    /**
103
     * @param Node\Stmt|Node\Stmt[] $topStatement
104
     * @param AliasManager $aliasManager
105
     * @param string $filepath
106
     */
107 30
    protected function parseTopDefinitions($topStatement, AliasManager $aliasManager, $filepath)
108
    {
109 30
        foreach ($topStatement as $statement) {
0 ignored issues
show
Bug introduced by
The expression $topStatement of type object<PhpParser\Node\St...t<PhpParser\Node\Stmt>> 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...
110 30
            if ($statement instanceof Node\Stmt\Use_) {
111
                if (count($statement->uses) > 0) {
112
                    foreach ($statement->uses as $use) {
113
                        $aliasManager->add($use->name->parts);
114
                    }
115
                }
116 30
            } elseif ($statement instanceof Node\Stmt\GroupUse) {
117
                if (count($statement->uses) > 0) {
118
                    foreach ($statement->uses as $use) {
119
                        $aliasManager->add($statement->prefix . $use->name->parts);
120
                    }
121
                }
122 30
            } elseif ($statement instanceof Node\Stmt\Trait_) {
123 1
                $definition = new TraitDefinition($statement->name, $statement);
124 1
                $definition->setFilepath($filepath);
125 1
                $definition->setNamespace($aliasManager->getNamespace());
126 1
                $definition->precompile();
127
128 1
                $this->compiler->addTrait($definition);
129 30
            } elseif ($statement instanceof Node\Stmt\Class_) {
130 30
                $definition = new ClassDefinition($statement->name, $statement, $statement->type);
131 30
                $definition->setFilepath($filepath);
132 30
                $definition->setNamespace($aliasManager->getNamespace());
133
134 30
                if ($statement->extends) {
135
                    $definition->setExtendsClass($statement->extends->toString());
136
                }
137
138 30
                if ($statement->implements) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $statement->implements of type PhpParser\Node\Name[] 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...
139
                    foreach ($statement->implements as $interface) {
140
                        $definition->addInterface($interface->toString());
141
                    }
142
                }
143
144 30
                foreach ($statement->stmts as $stmt) {
145 30
                    if ($stmt instanceof Node\Stmt\ClassMethod) {
146 28
                        $definition->addMethod(
147 28
                            new ClassMethod($stmt->name, $stmt, $stmt->type)
148 28
                        );
149 30
                    } elseif ($stmt instanceof Node\Stmt\Property) {
150 5
                        $definition->addProperty($stmt);
151 6
                    } elseif ($stmt instanceof Node\Stmt\TraitUse) {
152
                        foreach ($stmt->traits as $traitPart) {
153
                            $traitDefinition = $this->compiler->getTrait($traitPart->toString());
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $traitDefinition is correct as $this->compiler->getTrait($traitPart->toString()) (which targets PHPSA\Compiler::getTrait()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
154
                            if ($traitDefinition) {
155
                                $definition->mergeTrait($traitDefinition, $stmt->adaptations);
0 ignored issues
show
Documentation introduced by
$stmt->adaptations is of type array<integer,object<Php...mt\TraitUseAdaptation>>, but the function expects a array<integer,object<Php...itUseAdaptation\Alias>>.

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...
156
                            }
157
                        }
158 2
                    } elseif ($stmt instanceof Node\Stmt\ClassConst) {
159 2
                        $definition->addConst($stmt);
160 2
                    }
161 30
                }
162
163 30
                $this->compiler->addClass($definition);
164 30
            } elseif ($statement instanceof Node\Stmt\Function_) {
165 2
                $definition = new FunctionDefinition($statement->name, $statement);
166 2
                $definition->setFilepath($filepath);
167 2
                $definition->setNamespace($aliasManager->getNamespace());
168
169 2
                $this->compiler->addFunction($definition);
170 2
            }
171 30
        }
172 30
    }
173
}
174