Mercurial > hg > isophonics-drupal-site
comparison vendor/nikic/php-parser/doc/component/FAQ.markdown @ 13:5fb285c0d0e3
Update Drupal core to 8.4.7 via Composer. Security update; I *think* we've
been lucky to get away with this so far, as we don't support self-registration
which seems to be used by the so-called "drupalgeddon 2" attack that 8.4.5
was vulnerable to.
author | Chris Cannam |
---|---|
date | Mon, 23 Apr 2018 09:33:26 +0100 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
12:7a779792577d | 13:5fb285c0d0e3 |
---|---|
1 Frequently Asked Questions | |
2 ========================== | |
3 | |
4 * [How can the parent of a node be obtained?](#how-can-the-parent-of-a-node-be-obtained) | |
5 * [How can the next/previous sibling of a node be obtained?](#how-can-the-nextprevious-sibling-of-a-node-be-obtained) | |
6 | |
7 How can the parent of a node be obtained? | |
8 ----- | |
9 | |
10 The AST does not store parent nodes by default. However, it is easy to add a custom parent node | |
11 attribute using a custom node visitor: | |
12 | |
13 ```php | |
14 use PhpParser\Node; | |
15 use PhpParser\NodeVisitorAbstract; | |
16 | |
17 class ParentConnector extends NodeVisitorAbstract { | |
18 private $stack; | |
19 public function beforeTraverse(array $nodes) { | |
20 $this->stack = []; | |
21 } | |
22 public function enterNode(Node $node) { | |
23 if (!empty($this->stack)) { | |
24 $node->setAttribute('parent', $this->stack[count($this->stack)-1]); | |
25 } | |
26 $this->stack[] = $node; | |
27 } | |
28 public function leaveNode(Node $node) { | |
29 array_pop($this->stack); | |
30 } | |
31 } | |
32 ``` | |
33 | |
34 After running this visitor, the parent node can be obtained through `$node->getAttribute('parent')`. | |
35 | |
36 How can the next/previous sibling of a node be obtained? | |
37 ----- | |
38 | |
39 Again, siblings are not stored by default, but the visitor from the previous entry can be easily | |
40 extended to store the previous / next node with a common parent as well: | |
41 | |
42 ```php | |
43 use PhpParser\Node; | |
44 use PhpParser\NodeVisitorAbstract; | |
45 | |
46 class NodeConnector extends NodeVisitorAbstract { | |
47 private $stack; | |
48 private $prev; | |
49 public function beforeTraverse(array $nodes) { | |
50 $this->stack = []; | |
51 $this->prev = null; | |
52 } | |
53 public function enterNode(Node $node) { | |
54 if (!empty($this->stack)) { | |
55 $node->setAttribute('parent', $this->stack[count($this->stack)-1]); | |
56 } | |
57 if ($this->prev && $this->prev->getAttribute('parent') == $node->getAttribute('parent')) { | |
58 $node->setAttribute('prev', $this->prev); | |
59 $this->prev->setAttribute('next', $node); | |
60 } | |
61 $this->stack[] = $node; | |
62 } | |
63 public function leaveNode(Node $node) { | |
64 $this->prev = $node; | |
65 array_pop($this->stack); | |
66 } | |
67 } | |
68 ``` |