Completed
Push — master ( 6ab7bd...834806 )
by Дмитрий
05:03
created

FileParser::parseTopDefinitions()   C

Complexity

Conditions 14
Paths 28

Size

Total Lines 46
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 21.257

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 14
eloc 29
c 1
b 0
f 0
nc 28
nop 3
dl 0
loc 46
ccs 26
cts 39
cp 0.6667
crap 21.257
rs 5.0744

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\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 12
    public function __construct(\PhpParser\Parser $parser, Compiler $compiler)
33
    {
34 12
        $this->nodeTraverser = new \PhpParser\NodeTraverser();
35 12
        $this->nodeTraverser->addVisitor(new \PhpParser\NodeVisitor\NameResolver);
36
37 12
        $this->parser = $parser;
38 12
        $this->compiler = $compiler;
39 12
    }
40
41
    /**
42
     * @param string $filepath
43
     * @param Context $context
44
     */
45 12
    public function parserFile($filepath, Context $context)
46
    {
47 12
        $context->setFilepath($filepath);
48
49
        try {
50 12
            if (!is_readable($filepath)) {
51
                throw new RuntimeException('File ' . $filepath . ' is not readable');
52
            }
53
54 12
            $context->debug('<comment>Precompile: ' . $filepath . '.</comment>');
55
56 12
            $code = file_get_contents($filepath);
57 12
            $astTree = $this->parser->parse($code);
58
59 12
            $this->nodeTraverser->traverse($astTree);
0 ignored issues
show
Bug introduced by
It seems like $astTree defined by $this->parser->parse($code) on line 57 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...
60
61 12
            $context->aliasManager = new AliasManager();
62 12
            $namespace = null;
63
64
            /**
65
             * Step 1 Precompile
66
             */
67 12
            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...
68 12
                if ($topStatement instanceof Node\Stmt\Namespace_) {
69
                    /**
70
                     * Namespace block can be created without NS name
71
                     */
72 12
                    if ($topStatement->name) {
73 12
                        $namespace = $topStatement->name->toString();
74 12
                        $context->aliasManager->setNamespace($namespace);
75 12
                    }
76
77 12
                    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...
78 12
                        $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...
79 12
                    }
80 12
                } else {
81
                    if (is_array($topStatement)) {
82
                        $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...
83
                    } else {
84
                        $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...
85
                    }
86
                }
87 12
            }
88
89 12
            $context->clear();
90 12
        } catch (\PhpParser\Error $e) {
91
            $context->sytaxError($e, $filepath);
92
        } catch (Exception $e) {
93
            $context->output->writeln("<error>{$e->getMessage()}</error>");
94
        }
95 12
    }
96
97
    /**
98
     * @param Node\Stmt $topStatement
99
     * @param AliasManager $aliasManager
100
     * @param string $filepath
101
     */
102 12
    protected function parseTopDefinitions($topStatement, AliasManager $aliasManager, $filepath)
103
    {
104 12
        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...
105 12
            if ($statement instanceof Node\Stmt\Use_) {
106
                if (count($statement->uses) > 0) {
107
                    foreach ($statement->uses as $use) {
108
                        $aliasManager->add($use->name->parts);
109
                    }
110
                }
111 12
            } elseif ($statement instanceof Node\Stmt\Class_) {
112 12
                $definition = new ClassDefinition($statement->name, $statement->type);
113 12
                $definition->setFilepath($filepath);
114 12
                $definition->setNamespace($aliasManager->getNamespace());
115
116 12
                if ($statement->extends) {
117
                    $definition->setExtendsClass($statement->extends->toString());
118
                }
119
120 12
                if ($statement->implements) {
121
                    foreach ($statement->implements as $interface) {
122
                        $definition->addInterface($interface->toString());
123
                    }
124
                }
125
126 12
                foreach ($statement->stmts as $stmt) {
127 12
                    if ($stmt instanceof Node\Stmt\ClassMethod) {
128 12
                        $method = new ClassMethod($stmt->name, $stmt, $stmt->type);
129
130 12
                        $definition->addMethod($method);
131 12
                    } elseif ($stmt instanceof Node\Stmt\Property) {
132 1
                        $definition->addProperty($stmt);
133 1
                    } elseif ($stmt instanceof Node\Stmt\ClassConst) {
134
                        $definition->addConst($stmt);
135
                    }
136 12
                }
137
138 12
                $this->compiler->addClass($definition);
139 12
            } elseif ($statement instanceof Node\Stmt\Function_) {
140 1
                $definition = new FunctionDefinition($statement->name, $statement);
141 1
                $definition->setFilepath($filepath);
142 1
                $definition->setNamespace($aliasManager->getNamespace());
143
144 1
                $this->compiler->addFunction($definition);
145 1
            }
146 12
        }
147 12
    }
148
}
149