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\Collection; |
16
|
|
|
|
17
|
|
|
use ArrayIterator; |
18
|
|
|
use IteratorAggregate; |
19
|
|
|
use PhpParser\Node\Name; |
20
|
|
|
use PhpParser\Node\Stmt\Use_; |
21
|
|
|
use PhpParser\Node\Stmt\UseUse; |
22
|
|
|
use function Humbug\PhpScoper\clone_node; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Utility class collecting all the use statements for the scoped files allowing to easily find the use which a node |
26
|
|
|
* may use. |
27
|
|
|
*/ |
28
|
|
|
final class UseStmtCollection implements IteratorAggregate |
29
|
|
|
{ |
30
|
|
|
/** |
31
|
|
|
* @var Use_[][] |
32
|
|
|
*/ |
33
|
|
|
private $nodes = [ |
34
|
|
|
null => [], |
35
|
|
|
]; |
36
|
|
|
|
37
|
|
|
public function add(?Name $namespaceName, Use_ $node): void |
38
|
|
|
{ |
39
|
|
|
$this->nodes[(string) $namespaceName][] = clone_node($node); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Finds the statements matching the given name. |
44
|
|
|
* |
45
|
|
|
* $name = 'Foo'; |
46
|
|
|
* |
47
|
|
|
* use X; |
48
|
|
|
* use Bar\Foo; |
49
|
|
|
* use Y; |
50
|
|
|
* |
51
|
|
|
* will return the use statement for `Bar\Foo`. |
52
|
|
|
* |
53
|
|
|
* @param Name|null $namespaceName |
54
|
|
|
* @param Name $node |
55
|
|
|
* |
56
|
|
|
* @return null|Name |
57
|
|
|
*/ |
58
|
|
|
public function findStatementForNode(?Name $namespaceName, Name $node): ?Name |
59
|
|
|
{ |
60
|
|
|
$name = $node->getFirst(); |
61
|
|
|
|
62
|
|
|
$useStatements = $this->nodes[(string) $namespaceName] ?? []; |
63
|
|
|
|
64
|
|
|
foreach ($useStatements as $use_) { |
65
|
|
|
foreach ($use_->uses as $useStatement) { |
66
|
|
|
if ($useStatement instanceof UseUse) { |
67
|
|
|
if ($name === $useStatement->alias) { |
68
|
|
|
// Match the alias |
69
|
|
|
return $useStatement->name; |
70
|
|
|
} elseif (null !== $useStatement->alias) { |
71
|
|
|
continue; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
if ($name === $useStatement->name->getLast() && $useStatement->alias === null) { |
75
|
|
|
// Match a simple use statement |
76
|
|
|
return $useStatement->name; |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
return null; |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
/** |
86
|
|
|
* @inheritdoc |
87
|
|
|
*/ |
88
|
|
|
public function getIterator(): iterable |
89
|
|
|
{ |
90
|
|
|
return new ArrayIterator($this->nodes); |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|