Passed
Push — master ( 6c036d...1275a4 )
by Théo
01:42
created

NamespaceStmtPrefixer::prefixNamespaceStmt()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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