Skip to content

Instantly share code, notes, and snippets.

@slifin
Created May 6, 2019 11:38
Show Gist options
  • Select an option

  • Save slifin/89debe6867ba2ab77c0d0783d48fe74e to your computer and use it in GitHub Desktop.

Select an option

Save slifin/89debe6867ba2ab77c0d0783d48fe74e to your computer and use it in GitHub Desktop.
honeysql part 2
<?php
$data =
[':select' => [':a', ':b', [':select' => ':c']],
':from' => [':foo']];
function recur(array $map) : object {
return new \RecursiveIteratorIterator(
new \RecursiveArrayIterator($map),
\RecursiveIteratorIterator::CHILD_FIRST
);
}
function map_to_sql(array &$sql, object $map) : array {
// $map = recur($map);
foreach ($map as $key => $result) {
switch (TRUE) {
case has_key($map, ':select'):
has_key($result, ':select')
? $sql[] = '(' . map_to_sql($sql, $result) . ')';
: $sql[] = 'SELECT ' . implode(', ', $result);
break;
case $key === ':from':
$sql[] = 'FROM ' . implode(' ', $result);
break;
}
}
return $sql;
}
function has_key(object $map, string $key) : bool {
return isset($map->{$key});
}
$sql = [];
$out = map_to_sql($sql, recur($data));
$out = implode("\n", $out);
var_dump($out);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment