PHP-Parser
PHP-Parser copied to clipboard
Adding item to Expr_Array
Is there a way to add an item to Expr_Array
? I have an existing file with the following ast and would need an item to the modules
array:
array(
0: Stmt_Namespace(
name: Name(
parts: array(
0: Wpify
1: Managers
)
)
stmts: array(
0: Stmt_Use(
type: TYPE_NORMAL (1)
uses: array(
0: Stmt_UseUse(
type: TYPE_UNKNOWN (0)
name: Name(
parts: array(
0: Wpify
1: Core
2: AbstractManager
)
)
alias: null
)
)
)
1: Stmt_Use(
type: TYPE_NORMAL (1)
uses: array(
0: Stmt_UseUse(
type: TYPE_UNKNOWN (0)
name: Name(
parts: array(
0: Wpify
1: Cpt
2: BookPostType
)
)
alias: null
)
)
)
2: Stmt_Class(
flags: 0
name: Identifier(
name: CptManager
)
extends: Name(
parts: array(
0: AbstractManager
)
)
implements: array(
)
stmts: array(
0: Stmt_Property(
flags: MODIFIER_PROTECTED (2)
type: null
props: array(
0: Stmt_PropertyProperty(
name: VarLikeIdentifier(
name: modules
)
default: Expr_Array(
items: array(
0: Expr_ArrayItem(
key: null
value: Expr_ClassConstFetch(
class: Name(
parts: array(
0: BookPostType
)
)
name: Identifier(
name: class
)
)
byRef: false
unpack: false
)
)
)
)
)
)
)
)
)
)
)
I feel like there should be an easier way to do this with the BuilderFactory, but here's what I ended up doing:
// Wrap the value as an AST node using the BuilderFactory, or get it from an AST
$valueNode= (new BuilderFactory)->val('some_value');
// For associative arrays
// Wrap the key as an AST node using the BuilderFactory, or get it from an AST
$keyNode = (new BuilderFactory)->val('the_key');
$array->items[] = new Expr\ArrayItem($valueNode, $keyNode);
// For lists
$array->items[] = new Expr\ArrayItem($valueNode, null);
This can be closed as answered :+1: