Completed
Push — master ( de759d...63d2b1 )
by Дмитрий
03:30
created

NameResolveVisitor::resetState()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 1
dl 0
loc 9
ccs 7
cts 7
cp 1
crap 1
rs 9.6666
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author Nikita Popov @nikic
4
 * @link https://github.com/nikic/PHP-Parser/blob/master/lib/PhpParser/NodeVisitor/NameResolver.php
5
 *
6
 * @author Patsura Dmitry https://github.com/ovr <[email protected]>
7
 */
8
9
namespace PHPSA\Compiler;
10
11
use PhpParser\Error;
12
use PhpParser\ErrorHandler;
13
use PhpParser\Node;
14
use PhpParser\Node\Expr;
15
use PhpParser\Node\Name;
16
use PhpParser\Node\Name\FullyQualified;
17
use PhpParser\Node\Stmt;
18
use PhpParser\NodeVisitorAbstract;
19
20
class NameResolveVisitor extends NodeVisitorAbstract
0 ignored issues
show
Complexity introduced by
This class has a complexity of 64 which exceeds the configured maximum of 50.

The class complexity is the sum of the complexity of all methods. A very high value is usually an indication that your class does not follow the single reponsibility principle and does more than one job.

Some resources for further reading:

You can also find more detailed suggestions for refactoring in the “Code” section of your repository.

Loading history...
21
{
22
    /** @var null|Name Current namespace */
23
    protected $namespace;
24
25
    /** @var array Map of format [aliasType => [aliasName => originalName]] */
26
    protected $aliases;
27
28
    /** @var ErrorHandler Error handler */
29
    protected $errorHandler;
30
31
    /**
32
     * Constructs a name resolution visitor.
33
     *
34
     * @param ErrorHandler|null $errorHandler Error handler
35
     */
36 52
    public function __construct(ErrorHandler $errorHandler = null)
37
    {
38 52
        $this->errorHandler = $errorHandler ?: new ErrorHandler\Throwing;
39 52
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44 52
    public function beforeTraverse(array $nodes)
45
    {
46 52
        $this->resetState();
47 52
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52 52
    public function enterNode(Node $node)
53
    {
54 52
        if ($node instanceof Stmt\Namespace_) {
55 52
            $this->resetState($node->name);
0 ignored issues
show
Bug introduced by
It seems like $node->name can also be of type string; however, PHPSA\Compiler\NameResolveVisitor::resetState() does only seem to accept null|object<PhpParser\Node\Name>, 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...
56 52
        } elseif ($node instanceof Stmt\Use_) {
57 2
            foreach ($node->uses as $use) {
58 2
                $this->addAlias($use, $node->type, null);
59 2
            }
60 52
        } elseif ($node instanceof Stmt\GroupUse) {
61
            foreach ($node->uses as $use) {
62
                $this->addAlias($use, $node->type, $node->prefix);
63
            }
64 52
        } elseif ($node instanceof Stmt\Class_) {
65 52
            if (null !== $node->extends) {
66 2
                $node->extends = $this->resolveClassName($node->extends);
67 2
            }
68
69 52
            foreach ($node->implements as &$interface) {
70
                $interface = $this->resolveClassName($interface);
71 52
            }
72
73 52
            if (null !== $node->name) {
74 52
                $this->addNamespacedName($node);
75 52
            }
76 52
        } elseif ($node instanceof Stmt\Interface_) {
77
            foreach ($node->extends as &$interface) {
0 ignored issues
show
Bug introduced by
The expression $node->extends of type null|object<PhpParser\Node\Name> 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...
78
                $interface = $this->resolveClassName($interface);
79
            }
80
81
            $this->addNamespacedName($node);
82 52
        } elseif ($node instanceof Stmt\Trait_) {
83 1
            $this->addNamespacedName($node);
84 52
        } elseif ($node instanceof Stmt\Function_) {
85 6
            $this->addNamespacedName($node);
86 6
            $this->resolveSignature($node);
87 6
        } elseif ($node instanceof Stmt\ClassMethod
88 52
            || $node instanceof Expr\Closure
89 52
        ) {
90 49
            $this->resolveSignature($node);
91 52
        } elseif ($node instanceof Stmt\Const_) {
92
            foreach ($node->consts as $const) {
93
                $this->addNamespacedName($const);
94
            }
95
        } elseif ($node instanceof Expr\StaticCall
96 52
            || $node instanceof Expr\StaticPropertyFetch
97 52
            || $node instanceof Expr\ClassConstFetch
98 52
            || $node instanceof Expr\New_
99 52
            || $node instanceof Expr\Instanceof_
100 52
        ) {
101 8
            if ($node->class instanceof Name) {
102 8
                $node->class = $this->resolveClassName($node->class);
103 8
            }
104 52
        } elseif ($node instanceof Stmt\Catch_) {
105 2
            foreach ($node->types as &$type) {
106 2
                $type = $this->resolveClassName($type);
107 2
            }
108 52
        } elseif ($node instanceof Expr\FuncCall) {
109 13
            if ($node->name instanceof Name) {
110 13
                $node->name = $this->resolveOtherName($node->name, Stmt\Use_::TYPE_FUNCTION);
111 13
            }
112 52
        } elseif ($node instanceof Expr\ConstFetch) {
113 15
            $node->name = $this->resolveOtherName($node->name, Stmt\Use_::TYPE_CONSTANT);
0 ignored issues
show
Documentation introduced by
$node->name is of type string|null, but the function expects a object<PhpParser\Node\Name>.

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...
114 52
        } elseif ($node instanceof Stmt\TraitUse) {
115
            foreach ($node->traits as &$trait) {
116
                $trait = $this->resolveClassName($trait);
117
            }
118
119
            foreach ($node->adaptations as $adaptation) {
120
                if (null !== $adaptation->trait) {
121
                    $adaptation->trait = $this->resolveClassName($adaptation->trait);
122
                }
123
124
                if ($adaptation instanceof Stmt\TraitUseAdaptation\Precedence) {
125
                    foreach ($adaptation->insteadof as &$insteadof) {
126
                        $insteadof = $this->resolveClassName($insteadof);
127
                    }
128
                }
129
            }
130 52
        } elseif ($node instanceof Node\NullableType) {
131
            if ($node->type instanceof Name) {
132
                $node->type = $this->resolveClassName($node->type);
133
            }
134
        }
135 52
    }
136
137 52
    protected function resetState(Name $namespace = null)
138
    {
139 52
        $this->namespace = $namespace;
140 52
        $this->aliases   = array(
141 52
            Stmt\Use_::TYPE_NORMAL   => array(),
142 52
            Stmt\Use_::TYPE_FUNCTION => array(),
143 52
            Stmt\Use_::TYPE_CONSTANT => array(),
144
        );
145 52
    }
146
147 2
    protected function addAlias(Stmt\UseUse $use, $type, Name $prefix = null)
148
    {
149
        // Add prefix for group uses
150 2
        $name = $prefix ? Name::concat($prefix, $use->name) : $use->name;
151
        // Type is determined either by individual element or whole use declaration
152 2
        $type |= $use->type;
153
154
        // Constant names are case sensitive, everything else case insensitive
155 2
        if ($type === Stmt\Use_::TYPE_CONSTANT) {
156
            $aliasName = $use->alias;
157
        } else {
158 2
            $aliasName = strtolower($use->alias);
159
        }
160
161 2
        if (isset($this->aliases[$type][$aliasName])) {
162
            $typeStringMap = array(
163
                Stmt\Use_::TYPE_NORMAL   => '',
164
                Stmt\Use_::TYPE_FUNCTION => 'function ',
165
                Stmt\Use_::TYPE_CONSTANT => 'const ',
166
            );
167
168
            $this->errorHandler->handleError(new Error(
169
                sprintf(
170
                    'Cannot use %s%s as %s because the name is already in use',
171
                    $typeStringMap[$type],
172
                    $name,
173
                    $use->alias
174
                ),
175
                $use->getAttributes()
176
            ));
177
            return;
178
        }
179
180 2
        $this->aliases[$type][$aliasName] = $name;
181 2
    }
182
183
    /** @param Stmt\Function_|Stmt\ClassMethod|Expr\Closure $node */
184 49
    private function resolveSignature($node)
185
    {
186 49
        foreach ($node->params as $param) {
187 7
            if ($param->type instanceof Name) {
188
                $param->type = $this->resolveClassName($param->type);
189
            }
190 49
        }
191 49
        if ($node->returnType instanceof Name) {
192
            $node->returnType = $this->resolveClassName($node->returnType);
193
        }
194 49
    }
195
196 9
    protected function resolveClassName(Name $name)
197
    {
198
        // don't resolve special class names
199 9
        if (in_array(strtolower($name->toString()), array('self', 'parent', 'static'))) {
200 2
            if (!$name->isUnqualified()) {
201
                $this->errorHandler->handleError(new Error(
202
                    sprintf("'\\%s' is an invalid class name", $name->toString()),
203
                    $name->getAttributes()
204
                ));
205
            }
206
207 2
            return $name;
208
        }
209
210
        // fully qualified names are already resolved
211 7
        if ($name->isFullyQualified()) {
212 4
            return $name;
213
        }
214
215 3
        $aliasName = strtolower($name->getFirst());
216 3
        if (!$name->isRelative() && isset($this->aliases[Stmt\Use_::TYPE_NORMAL][$aliasName])) {
217
            // resolve aliases (for non-relative names)
218 2
            $alias = $this->aliases[Stmt\Use_::TYPE_NORMAL][$aliasName];
219 2
            return FullyQualified::concat($alias, $name->slice(1), $name->getAttributes());
220
        }
221
222
        // if no alias exists prepend current namespace
223 1
        return FullyQualified::concat($this->namespace, $name, $name->getAttributes());
224
    }
225
226 24
    protected function resolveOtherName(Name $name, $type)
227
    {
228
        // fully qualified names are already resolved
229 24
        if ($name->isFullyQualified()) {
230
            return $name;
231
        }
232
233
        // resolve aliases for qualified names
234 24
        $aliasName = strtolower($name->getFirst());
235 24
        if ($name->isQualified() && isset($this->aliases[Stmt\Use_::TYPE_NORMAL][$aliasName])) {
236
            $alias = $this->aliases[Stmt\Use_::TYPE_NORMAL][$aliasName];
237
            return FullyQualified::concat($alias, $name->slice(1), $name->getAttributes());
238
        }
239
240 24
        if ($name->isUnqualified()) {
241 24
            if ($type === Stmt\Use_::TYPE_CONSTANT) {
242
                // constant aliases are case-sensitive, function aliases case-insensitive
243 15
                $aliasName = $name->getFirst();
244 15
            }
245
246 24
            if (isset($this->aliases[$type][$aliasName])) {
247
                // resolve unqualified aliases
248
                return new FullyQualified($this->aliases[$type][$aliasName], $name->getAttributes());
249
            }
250
251 24
            if (null === $this->namespace) {
252
                // outside of a namespace unaliased unqualified is same as fully qualified
253
                return new FullyQualified($name, $name->getAttributes());
254
            }
255
256
            // unqualified names inside a namespace cannot be resolved at compile-time
257
            // add the namespaced version of the name as an attribute
258 24
            $name->setAttribute(
259 24
                'namespacedName',
260 24
                FullyQualified::concat($this->namespace, $name, $name->getAttributes())
261 24
            );
262
263 24
            return $name;
264
        }
265
266
        // if no alias exists prepend current namespace
267
        return FullyQualified::concat($this->namespace, $name, $name->getAttributes());
268
    }
269
270 52
    protected function addNamespacedName(Node $node)
271
    {
272 52
        $node->namespacedName = Name::concat($this->namespace, $node->name);
0 ignored issues
show
Bug introduced by
Accessing namespacedName on the interface PhpParser\Node suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
Bug introduced by
Accessing name on the interface PhpParser\Node suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
273 52
        $node->namespace = $this->namespace;
0 ignored issues
show
Bug introduced by
Accessing namespace on the interface PhpParser\Node suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
274 52
    }
275
}
276