php-spark/plugins/com.noccy.pdo/Commands/PdoStoreCommand.php

85 lines
3.0 KiB
PHP
Raw Normal View History

<?php
namespace SparkPlug\Com\Noccy\Pdo\Commands;
use Spark\Commands\Command;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Helper\TableSeparator;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class PdoStoreCommand extends Command {
protected function execute(InputInterface $input, OutputInterface $output)
{
$source = $input->getOption("res");
$sourcePdo = get_resource($source)->getPDO();
if (!$sourcePdo) {
$output->writeln("<error>Invalid resource: {$source}</>");
return Command::INVALID;
}
$box = $input->getOption('box');
$query = $input->getArgument('query');
$vert = $input->getOption("vertical");
$unserialize = $input->getOption("unserialize");
$stmt = $sourcePdo->query($query);
$stmt->execute();
$table = new Table($output);
$table->setStyle($box?"box":"compact");
$hasColumns = false;
while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
if (!$hasColumns) {
if ($vert) {
$table->setHeaders([ "Field", "VarType", "Value" ]);
} else {
$table->setHeaders(array_keys($row));
}
$hasColumns = true;
} else {
if ($vert) {
if ($box) {
$table->addRow(new TableSeparator());
} else {
$table->addRow(["","","-----"]);
}
}
}
if ($vert) {
foreach ($row as $k=>$v) {
$vv = $v;
if ($unserialize) {
$j = @json_decode($v);
$p = @unserialize($v);
if ($j) {
$v = $j;
$vv = json_encode($v, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
} elseif ($p) {
$v = $p;
$vv = json_encode($p, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
}
}
$table->addRow([ $k, gettype($v), $vv ]);
}
} else {
$table->addRow($row);
}
}
$table->render();
return Command::SUCCESS;
}
protected function configure() {
$this->setName("pdo:store");
$this->setDescription("Store a query to recall later");
$this->addOption("res", "r", InputOption::VALUE_REQUIRED, "Resource to query", "db");
$this->addArgument("name", InputArgument::REQUIRED, "Query name");
$this->addArgument("query", InputArgument::REQUIRED, "SQL query to execute");
$this->addArgument("slots", InputArgument::IS_ARRAY|InputArgument::OPTIONAL, "Slots in the query string");
}
}