Completed
Push — master ( 74c262...0b4843 )
by Théo
03:38 queued 01:33
created

NamespaceStmtPrefixer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 2
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
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
42
    public function __construct(string $prefix, NamespaceStmtCollection $namespaceStatements)
43
    {
44
        $this->prefix = $prefix;
45
        $this->namespaceStatements = $namespaceStatements;
46
    }
47
48
    /**
49
     * @inheritdoc
50
     */
51
    public function enterNode(Node $node): Node
52
    {
53
        return ($node instanceof Namespace_)
54
            ? $this->prefixNamespaceStmt($node)
55
            : $node
56
        ;
57
    }
58
59
    private function prefixNamespaceStmt(Namespace_ $namespace): Node
60
    {
61
        $originalNamespace = $namespace;
62
63
        if (null !== $namespace->name && $this->prefix !== $namespace->name->getFirst()) {
64
            $originalNamespace = clone_node($namespace);
65
66
            $namespace->name = Name::concat($this->prefix, $namespace->name);
67
        }
68
69
        $this->namespaceStatements->add($namespace, $originalNamespace);
70
71
        return $namespace;
72
    }
73
}
74