1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of the humbug/php-scoper package. |
7
|
|
|
* |
8
|
|
|
* Copyright (c) 2017 Théo FIDRY <[email protected]>, |
9
|
|
|
* Pádraic Brady <[email protected]> |
10
|
|
|
* |
11
|
|
|
* For the full copyright and license information, please view the LICENSE |
12
|
|
|
* file that was distributed with this source code. |
13
|
|
|
*/ |
14
|
|
|
|
15
|
|
|
namespace Humbug\PhpScoper\NodeVisitor\Resolver; |
16
|
|
|
|
17
|
|
|
use Humbug\PhpScoper\NodeVisitor\AppendParentNode; |
18
|
|
|
use Humbug\PhpScoper\NodeVisitor\Collection\NamespaceStmtCollection; |
19
|
|
|
use Humbug\PhpScoper\NodeVisitor\Collection\UseStmtCollection; |
20
|
|
|
use PhpParser\Node\Expr\ConstFetch; |
21
|
|
|
use PhpParser\Node\Expr\FuncCall; |
22
|
|
|
use PhpParser\Node\Name; |
23
|
|
|
use PhpParser\Node\Name\FullyQualified; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Attempts to resolve the node name into a fully qualified node. Returns a valid (non fully-qualified) name node on |
27
|
|
|
* failure. |
28
|
|
|
*/ |
29
|
|
|
final class FullyQualifiedNameResolver |
30
|
|
|
{ |
31
|
|
|
private $namespaceStatements; |
32
|
|
|
private $useStatements; |
33
|
|
|
|
34
|
|
|
public function __construct(NamespaceStmtCollection $namespaceStatements, UseStmtCollection $useStatements) |
35
|
|
|
{ |
36
|
|
|
$this->namespaceStatements = $namespaceStatements; |
37
|
|
|
$this->useStatements = $useStatements; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
public function resolveName(Name $node): ResolvedValue |
41
|
|
|
{ |
42
|
|
|
if ($node instanceof FullyQualified) { |
43
|
|
|
return new ResolvedValue($node, null, null); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
$namespaceName = $this->namespaceStatements->findNamespaceForNode($node); |
47
|
|
|
|
48
|
|
|
$useName = $this->useStatements->findStatementForNode($namespaceName, $node); |
49
|
|
|
|
50
|
|
|
return new ResolvedValue( |
51
|
|
|
$this->resolveNodeName($node, $namespaceName, $useName), |
52
|
|
|
$namespaceName, |
53
|
|
|
$useName |
54
|
|
|
); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
private function resolveNodeName(Name $name, ?Name $namespace, ?Name $use): Name |
58
|
|
|
{ |
59
|
|
|
if (null !== $use) { |
60
|
|
|
return FullyQualified::concat($use, $name->slice(1), $name->getAttributes()); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
if (null === $namespace) { |
64
|
|
|
return new FullyQualified($name, $name->getAttributes()); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
$parentNode = AppendParentNode::getParent($name); |
68
|
|
|
|
69
|
|
|
if ( |
70
|
|
|
($parentNode instanceof ConstFetch || $parentNode instanceof FuncCall) |
71
|
|
|
&& count($name->parts) === 1 |
72
|
|
|
) { |
73
|
|
|
// Ambiguous name, cannot determine the FQ name |
74
|
|
|
return $name; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
return FullyQualified::concat($namespace, $name, $name->getAttributes()); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|