Skip to content

Instantly share code, notes, and snippets.

@joelharkes
Created February 5, 2025 13:47
Show Gist options
  • Save joelharkes/19415f8023bfae757c27598c5b62d3a4 to your computer and use it in GitHub Desktop.
Save joelharkes/19415f8023bfae757c27598c5b62d3a4 to your computer and use it in GitHub Desktop.
Turn in memory PHP JSON like value into nikic/PHP-Parser statements
<?php
class ValueToStatement
public function valueToStatement(mixed $value): Node\Expr
{
return match (gettype($value)) {
'boolean' => new Node\Expr\ConstFetch(new Node\Name($value ? 'true' : 'false')),
'integer' => new Node\Scalar\Int_($value),
'double' => new Node\Scalar\Float_($value),
'string' => new Node\Scalar\String_($value),
'array' => new Node\Expr\Array_(
array_map(
fn($key, $item) => new Node\Expr\ArrayItem(
$this->valueToStatement($item),
array_is_list($value) ? null : $this->valueToStatement($key),
),
array_keys($value),
$value,
),
),
default => throw new \InvalidArgumentException('Unsupported type: ' . gettype($value)),
};
}
}
@joelharkes
Copy link
Author

I couldn't find this anywhere quickly myself so I made it and I hope this helps you as well :)

array_is_list is not super efficienet as it is called on each array item but afin it works ;-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment