Debian Codegraph @

vendor/wikimedia/shellbox/src/ShellParser/Node.php

raw
1 <?php
2
3 namespace Shellbox\ShellParser;
4
5 use Wikimedia\WikiPEG\InternalError;
6
7 class Node {
8 /** @var string The node type */
9 public $type;
10 /** @var array The node contents (children) */
11 public $contents;
12
13 /**
14 * @param string $type
15 * @param array|Node|string $contents
16 */
17 public function __construct( $type, $contents ) {
18 $this->type = $type;
19 if ( !is_array( $contents ) ) {
20 $contents = [ $contents ];
21 }
22 foreach ( $contents as $i => $node ) {
23 if ( !$node instanceof Node && !is_string( $node ) && !is_array( $node ) ) {
24 $type = gettype( $node );
25 throw new InternalError( 'ShellParser error: node contents validation failed. ' .
26 "Item $i is a $type." );
27 }
28 }
29 $this->contents = $contents;
30 }
31
32 /**
33 * Dump a string representation for testing or debugging
34 *
35 * @return string
36 */
37 public function dump() {
38 $inner = self::dumpArray( $this->contents );
39 return "<{$this->type}>$inner</{$this->type}>";
40 }
41
42 /**
43 * Dump a string representation of a node array for testing or debugging
44 *
45 * @param array $array
46 * @return string
47 */
48 public static function dumpArray( $array ) {
49 $inner = '';
50 foreach ( $array as $node ) {
51 if ( $node instanceof Node ) {
52 $inner .= $node->dump();
53 } elseif ( is_array( $node ) ) {
54 $inner .= self::dumpArray( $node );
55 } else {
56 $inner .= htmlspecialchars( $node, ENT_COMPAT );
57 }
58 }
59 return $inner;
60 }
61
62 public function traverse( callable $visitor, ...$args ) {
63 $visitor( $this, ...$args );
64 self::traverseArray( $visitor, $this->contents, ...$args );
65 }
66
67 public static function traverseArray( callable $visitor, $array, ...$args ) {
68 foreach ( $array as $node ) {
69 if ( $node instanceof Node ) {
70 $node->traverse( $visitor, ...$args );
71 } elseif ( is_array( $node ) ) {
72 self::traverseArray( $visitor, $node, ...$args );
73 } else {
74 $visitor( $node, ...$args );
75 }
76 }
77 }
78 }