Skip to content

Instantly share code, notes, and snippets.

@nawawi
Last active March 1, 2023 23:57
Show Gist options
  • Save nawawi/bc2ef521bebb2d6a83933cc30dd6be34 to your computer and use it in GitHub Desktop.
Save nawawi/bc2ef521bebb2d6a83933cc30dd6be34 to your computer and use it in GitHub Desktop.
<?php
function export_object($value, string $indent = '')
{
switch (true) {
case \is_int($value) || \is_float($value): return var_export($value, true);
case [] === $value: return '[]';
case false === $value: return 'false';
case true === $value: return 'true';
case null === $value: return 'null';
case '' === $value: return "''";
case $value instanceof \UnitEnum: return '\\'.ltrim(var_export($value, true), '\\');
}
$subIndent = $indent.' ';
if (\is_string($value)) {
$code = sprintf("'%s'", addcslashes($value, "'\\"));
$code = preg_replace_callback("/((?:[\\0\\r\\n]|\u{202A}|\u{202B}|\u{202D}|\u{202E}|\u{2066}|\u{2067}|\u{2068}|\u{202C}|\u{2069})++)(.)/", function ($m) use ($subIndent) {
$m[1] = sprintf('\'."%s".\'', str_replace(
["\0", "\r", "\n", "\u{202A}", "\u{202B}", "\u{202D}", "\u{202E}", "\u{2066}", "\u{2067}", "\u{2068}", "\u{202C}", "\u{2069}", '\n\\'],
['\0', '\r', '\n', '\u{202A}', '\u{202B}', '\u{202D}', '\u{202E}', '\u{2066}', '\u{2067}', '\u{2068}', '\u{202C}', '\u{2069}', '\n"'."\n".$subIndent.'."\\'],
$m[1]
));
if ("'" === $m[2]) {
return substr($m[1], 0, -2);
}
if ('n".\'' === substr($m[1], -4)) {
return substr_replace($m[1], "\n".$subIndent.".'".$m[2], -2);
}
return $m[1].$m[2];
}, $code, -1, $count);
if ($count && str_starts_with($code, "''.")) {
$code = substr($code, 3);
}
return $code;
}
if (\is_array($value) || ($value instanceof \stdClass)) {
$j = -1;
$code = '';
foreach ($value as $k => $v) {
$code .= $subIndent;
if (!\is_int($k) || 1 !== $k - $j) {
$code .= export_object($k, $subIndent).' => ';
}
if (\is_int($k) && $k > $j) {
$j = $k;
}
$code .= export_object($v, $subIndent).",\n";
}
$pref = '';
if ($value instanceof \stdClass) {
$pref = '(object) ';
}
return $pref."[\n".$code.$indent.']';
}
throw new \UnexpectedValueException('Type not supported');
}
@CodeByAidan
Copy link

I love this code a lot!!

Only one question, what's a good test example you would recommend?

@nawawi
Copy link
Author

nawawi commented Feb 28, 2023

I love this code a lot!!

Only one question, what's a good test example you would recommend?

The code is not mine, it's a part of Symfony/var-exporter code. It works the same as var_export with a short array syntax. This portion of this code is only for a variable type other than objects of a class instance.
https://www.php.net/manual/en/function.var-export.php
https://github.com/symfony/var-exporter/blob/6.2/Internal/Exporter.php#L194

@CodeByAidan
Copy link

Thank you so much mate!

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