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

AppendParentNode::enterNode()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 10
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 PhpParser\Node;
18
use PhpParser\NodeVisitorAbstract;
19
20
/**
21
 * Appends the parent node as an attribute to each node. This allows to have more context in the other visitors when
22
 * inspecting a node.
23
 */
24
final class AppendParentNode extends NodeVisitorAbstract
25
{
26
    /** @private */
27
    const PARENT_ATTRIBUTE = 'parent';
28
29
    private $stack;
30
31
    public static function hasParent(Node $node): bool
32
    {
33
        return $node->hasAttribute(self::PARENT_ATTRIBUTE);
34
    }
35
36
    public static function getParent(Node $node): Node
37
    {
38
        return $node->getAttribute(self::PARENT_ATTRIBUTE);
39
    }
40
41
    /**
42
     * @inheritdoc
43
     */
44
    public function beforeTraverse(array $nodes)
45
    {
46
        $this->stack = [];
47
    }
48
49
    /**
50
     * @inheritdoc
51
     */
52
    public function enterNode(Node $node): Node
53
    {
54
        if (!empty($this->stack)) {
55
            $node->setAttribute(self::PARENT_ATTRIBUTE, $this->stack[count($this->stack) - 1]);
56
        }
57
58
        $this->stack[] = $node;
59
60
        return $node;
61
    }
62
63
    /**
64
     * @inheritdoc
65
     */
66
    public function leaveNode(Node $node)
67
    {
68
        array_pop($this->stack);
69
    }
70
}
71