Skip to content

Instantly share code, notes, and snippets.

@SerafimArts
Last active April 17, 2022 10:47
Show Gist options
  • Save SerafimArts/2e7702620480fbce6c24bc87bfb9cb0e to your computer and use it in GitHub Desktop.
Save SerafimArts/2e7702620480fbce6c24bc87bfb9cb0e to your computer and use it in GitHub Desktop.
phpwtf-1
<?php
$variable = 23;
[$query, $params] = sql(fn() => <<<SQL
SELECT * FROM users WHERE id = ${yield $variable} OR id = ${yield 42}
SQL);
var_dump($query, $params);
//
// string(42) "SELECT * FROM users WHERE id = ? OR id = ?"
// array(2) {
// [0] => int(23)
// [1] => int(42)
// }
//
<?php
class QueryBuilder
{
private int $variable = 23;
public function build(int $param): array
{
return sql(fn() => <<<SQL
SELECT * FROM users WHERE id = ${yield $this->variable} OR id = ${yield $param}
SQL);
}
}
$builder = new QueryBuilder();
[$sql, $params] = $builder->build(23);
var_dump($sql, $params);
//
// string(42) "SELECT * FROM users WHERE id = ? OR id = ?"
// array(2) {
// [0] => int(23)
// [1] => int(42)
// }
//
<?php
final class Context
{
public function sql(\Closure $query): array
{
if ($ctx = (new \ReflectionFunction($query))->getClosureThis()) {
foreach ((new \ReflectionObject($ctx))->getProperties() as $prop) {
$this->{$prop->getName()} = $prop->getValue($ctx);
}
}
$params = [];
/** @var \Generator|string $result */
$result = $query->call($this);
if (\is_string($result)) {
return [$result, []];
}
while ($result->valid()) {
$params[] = $result->current();
$result->send('this');
}
return [\trim($result->getReturn()), $params];
}
public function __toString(): string
{
return '?';
}
}
function sql(\Closure $ctx): array
{
return (new Context())->sql($ctx);
}
@SerafimArts
Copy link
Author

simplified: https://3v4l.org/8lPf3

with proxy support: https://3v4l.org/h00Uq

wow!

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