nette / php-generator

🐘 Generates neat PHP code for you. Supports new PHP 8.3 features.
https://doc.nette.org/php-generator
Other
2.11k stars 138 forks source link

Dump double quoted strings #46

Closed juniordias-planejar closed 5 years ago

juniordias-planejar commented 5 years ago

I want to do something like:

return "Something ${value}";

// so php can interpret the variable 'value' and return its value, not the string 'Something ${value}'

juniordias-planejar commented 5 years ago

Maybe something like:

} elseif (is_string($var) && preg_match('/\${(([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(->)*)*(\[[^\]]*\])*)}/', $var)) { return '"' . preg_replace('#\'|\\\\(?=[\'\\\\]|\z)#', '\\\\$0', $var) . '"';

at line 66 of Helpers (_dump)

dg commented 5 years ago

Are you talking about function/method body? Simply use $function->setBody('return "Something ${value}";');

juniordias-planejar commented 5 years ago

Actually the problem is in an array. One of the array values must be enclosed by double quotes. The example was too simple. The actual code is:

https://gist.github.com/juniordias-planejar/8efd3d66bee6140a990da84e686f4177

At line 24, the value is enclosed by the double quotes. I thought about using sprintf, but this {$primaryKey} can be used multiple times depending on the database table.

juniordias-planejar commented 5 years ago

The return comes from an array:

$methodRules->addBody('return ?;', [$requestRules]);

dg commented 5 years ago

You can also use Nette\PhpGenerator\PhpLiteral:

$methodRules->addBody('return ?;', [new Nette\PhpGenerator\PhpLiteral('"Something ${value}"')]);

juniordias-planejar commented 5 years ago

Thanks! Good suggestion!

If I meet that condition, I can set the array value accordingly:

$requestRules[$col->column_name] = $literal ? new PhpLiteral(sprintf('"%s"', $rules)) : $rules;

When I do $methodRules->addBody('return ?;', [$requestRules]);, the array value for that column_name is double quote escaped.