fox-1.1.2/src/Plugin/FoxCommand/FoxCommandSql.php
src/Plugin/FoxCommand/FoxCommandSql.php
<?php
namespace Drupal\fox\Plugin\FoxCommand;
use Drupal\Core\Database\Database;
use Drupal\fox\FoxCommandsHelper as Helper;
/**
* SQL fox command.
*
* @FoxCommand(
* id = "sql",
* label = @Translation("Execute SQL command. Usage: SQL expression1,expression2,... [INTO variable]")
* )
*/
class FoxCommandSql extends FoxCommandBaseClass {
/**
* {@inheritdoc}
*/
public function execute(array $params, array $variables, array $options): array {
if (empty($params)) {
return $this->errorReturn($this->t('Empty command parameters.'));
}
$special_words = ['select', 'show'];
$first_param = strtolower($params[0]);
if (!in_array($first_param, $special_words)) {
array_unshift($params, 'SELECT');
}
[$params, $into_params] = Helper::parseParameters('into', $params);
$input = implode(' ', $params);
$helper = $this->foxCommandsHelper();
$input = $helper->stringRender($input, $variables);
$connection = Database::getConnection();
try {
$query = $connection->query($input);
$result = $query->fetchAll(\PDO::FETCH_ASSOC);
}
catch (\Exception $e) {
return $this->errorReturn($e->getMessage());
}
$output = [];
foreach ($result as $row) {
$output[] = $row;
}
if (!empty($into_params)) {
// Save to the into variable.
$info = reset($into_params);
$return = [
'variables' => ['into' => [$info => $output]],
];
}
else {
// Print output.
$data = $header = [];
if (!empty($output)) {
foreach ($output as $item) {
if (empty($header)) {
$header = array_keys($item);
}
$data[] = array_values($item);
}
}
$return = [
'message' => [
'header' => $header,
'data' => $data,
],
];
}
return $return;
}
}
