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; |
16
|
|
|
|
17
|
|
|
use Humbug\PhpScoper\NodeVisitor\Collection\NamespaceStmtCollection; |
18
|
|
|
use PhpParser\Node; |
19
|
|
|
use PhpParser\Node\Name; |
20
|
|
|
use PhpParser\Node\Stmt\Namespace_; |
21
|
|
|
use PhpParser\NodeVisitorAbstract; |
22
|
|
|
use function Humbug\PhpScoper\clone_node; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Prefixes the relevant namespaces. |
26
|
|
|
* |
27
|
|
|
* ``` |
28
|
|
|
* namespace Foo; |
29
|
|
|
* ``` |
30
|
|
|
* |
31
|
|
|
* => |
32
|
|
|
* |
33
|
|
|
* ``` |
34
|
|
|
* namespace Humbug\Foo; |
35
|
|
|
* ``` |
36
|
|
|
*/ |
37
|
|
|
final class NamespaceStmtPrefixer extends NodeVisitorAbstract |
38
|
|
|
{ |
39
|
|
|
private $prefix; |
40
|
|
|
private $namespaceStatements; |
41
|
|
|
private $whitelist; |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param string $prefix |
45
|
|
|
* @param NamespaceStmtCollection $namespaceStatements |
46
|
|
|
* @param string[] $whitelist |
47
|
|
|
*/ |
48
|
|
|
public function __construct(string $prefix, NamespaceStmtCollection $namespaceStatements, array $whitelist) |
49
|
|
|
{ |
50
|
|
|
$this->prefix = $prefix; |
51
|
|
|
$this->namespaceStatements = $namespaceStatements; |
52
|
|
|
$this->whitelist = $whitelist; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @inheritdoc |
57
|
|
|
*/ |
58
|
|
|
public function enterNode(Node $node): Node |
59
|
|
|
{ |
60
|
|
|
return ($node instanceof Namespace_) |
61
|
|
|
? $this->prefixNamespaceStmt($node) |
62
|
|
|
: $node; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
private function prefixNamespaceStmt(Namespace_ $namespace): Node |
66
|
|
|
{ |
67
|
|
|
$originalNamespace = $namespace; |
68
|
|
|
|
69
|
|
|
if ($this->shouldPrefixStmt($namespace)) { |
70
|
|
|
$originalNamespace = clone_node($namespace); |
71
|
|
|
|
72
|
|
|
$namespace->name = Name::concat($this->prefix, $namespace->name); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
$this->namespaceStatements->add($namespace, $originalNamespace); |
76
|
|
|
|
77
|
|
|
return $namespace; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
private function shouldPrefixStmt(Namespace_ $namespace): bool |
81
|
|
|
{ |
82
|
|
|
return null !== $namespace->name && $this->prefix !== $namespace->name->getFirst(); |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|