NamespaceWrapper   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 3
dl 0
loc 44
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A beforeTraverse() 0 22 5
1
<?php
2
/**
3
 * This program is free software. It comes without any warranty, to
4
 * the extent permitted by applicable law. You can redistribute it
5
 * and/or modify it under the terms of the Do What The Fuck You Want
6
 * To Public License, Version 2, as published by Sam Hocevar. See
7
 * http://www.wtfpl.net/ for more details.
8
 */
9
10
declare(strict_types = 1);
11
12
namespace hanneskod\classtools\Transformer\Action;
13
14
use PhpParser\NodeVisitorAbstract;
15
use PhpParser\Node\Stmt\Namespace_;
16
use PhpParser\Node\Name;
17
18
/**
19
 * Wrap code in namespace
20
 *
21
 * @author Hannes Forsgård <[email protected]>
22
 */
23
class NamespaceWrapper extends NodeVisitorAbstract
24
{
25
    /**
26
     * @var string Name of namespace
27
     */
28
    private $namespaceName;
29
30
    /**
31
     * Wrap code in namespace
32
     */
33
    public function __construct(string $namespaceName)
34
    {
35
        $this->namespaceName = $namespaceName;
36
    }
37
38
    /**
39
     * {inheritdoc}
40
     *
41
     * @param  array $nodes
42
     * @return Namespace_[]
43
     */
44
    public function beforeTraverse(array $nodes): array
45
    {
46
        // Merge if code is namespaced
47
        if (isset($nodes[0]) && $nodes[0] instanceof Namespace_) {
48
            if ($this->namespaceName) {
49
                if ((string)$nodes[0]->name == '') {
50
                    $nodes[0]->name = new Name($this->namespaceName);
51
                } else {
52
                    $nodes[0]->name = Name::concat($this->namespaceName, $nodes[0]->name);
53
                }
54
            }
55
            return $nodes;
56
        }
57
58
        // Else create new node
59
        return [
60
            new Namespace_(
61
                new Name($this->namespaceName),
62
                $nodes
63
            )
64
        ];
65
    }
66
}
67