Created
February 5, 2025 13:47
-
-
Save joelharkes/19415f8023bfae757c27598c5b62d3a4 to your computer and use it in GitHub Desktop.
Turn in memory PHP JSON like value into nikic/PHP-Parser statements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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)), | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 ;-)