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

80 lines
2.7 KiB
PHP
Raw Normal View History

<?php
namespace SparkPlug\Com\Noccy\Pdo\Commands;
use Spark\Commands\Command;
use SparkPlug\Com\Noccy\Pdo\Reflection\TableReflectionInterface;
use Symfony\Component\Console\Helper\Table;
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 PdoInspectCommand extends Command {
protected function configure() {
$this->setName("pdo:inspect");
$this->setDescription("Inspect the database, a table, or a row");
$this->addOption("res", "r", InputOption::VALUE_REQUIRED, "Resource to query", "db");
$this->addArgument("table", InputArgument::OPTIONAL, "Table name to inspect");
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$sourceName = $input->getOption("res");
$source = get_resource($sourceName);
if (!$source) {
$output->writeln("<error>Invalid resource: {$source}</>");
return Command::INVALID;
}
$reflector = $source->getReflector();
$tableName = $input->getArgument("table");
if ($tableName) {
try {
$table = $reflector->createTableReflection($tableName);
if ($table) {
$this->dumpTable($tableName, $table, $output);
}
} catch (\Exception $e) {
$output->writeln("<error>{$e->getMessage()}</>");
}
} else {
try {
$database = $reflector->createDatabaseReflection();
foreach ($database->getAllTables() as $tableName=>$table) {
$this->dumpTable($tableName, $table, $output);
}
} catch (\Exception $e) {
$output->writeln("<error>{$e->getMessage()}</>");
}
}
return Command::SUCCESS;
}
private function dumpTable(string $name, TableReflectionInterface $table, OutputInterface $output)
{
$output->writeln("<options=bold>{$name}</>");
$t = new Table($output);
$t->setStyle('compact');
$t->setHeaders([ "Name", "Type", "PK", "NULL", "Default" ]);
$t->setColumnWidth(0, 30);
$t->setColumnWidth(1, 30);
foreach ($table->getAllColumns() as $column) {
$t->addRow([
$column->getName(),
$column->getType(),
$column->isPrimaryKey()?"Y":"-",
$column->isNullable()?"Y":"-",
$column->getDefaultValue(),
]);
}
$t->render();
$output->writeln("");
}
}