ShowTablesCommand.php 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace PhpDevCommunity\PaperORM\Command;
  3. use PhpDevCommunity\Console\Argument\CommandArgument;
  4. use PhpDevCommunity\Console\Command\CommandInterface;
  5. use PhpDevCommunity\Console\InputInterface;
  6. use PhpDevCommunity\Console\Option\CommandOption;
  7. use PhpDevCommunity\Console\Output\ConsoleOutput;
  8. use PhpDevCommunity\Console\OutputInterface;
  9. use PhpDevCommunity\PaperORM\EntityManagerInterface;
  10. use PhpDevCommunity\PaperORM\Metadata\ColumnMetadata;
  11. class ShowTablesCommand implements CommandInterface
  12. {
  13. private EntityManagerInterface $entityManager;
  14. public function __construct(EntityManagerInterface $entityManager)
  15. {
  16. $this->entityManager = $entityManager;
  17. }
  18. public function getName(): string
  19. {
  20. return 'paper:show:tables';
  21. }
  22. public function getDescription(): string
  23. {
  24. return 'Show the list of tables in the SQL database';
  25. }
  26. public function getOptions(): array
  27. {
  28. return [
  29. new CommandOption('columns', null, 'Show the list of columns table ', true)
  30. ];
  31. }
  32. public function getArguments(): array
  33. {
  34. return [
  35. new CommandArgument( 'table', false, null, 'The name of the table')
  36. ];
  37. }
  38. public function execute(InputInterface $input, OutputInterface $output): void
  39. {
  40. $io = ConsoleOutput::create($output);
  41. $tableName = null;
  42. $withColumns = false;
  43. if ($input->hasArgument('table')) {
  44. $tableName = $input->getArgumentValue('table');
  45. }
  46. if ($input->hasOption('columns')) {
  47. $withColumns = $input->getOptionValue('columns');
  48. }
  49. $platform = $this->entityManager->createDatabasePlatform();
  50. $io->info('Database : ' . $platform->getDatabaseName());
  51. $tables = $platform->listTables();
  52. if ($tableName !== null) {
  53. if (!in_array($tableName, $tables)) {
  54. throw new \LogicException(sprintf('The table "%s" does not exist', $tableName));
  55. }
  56. $tables = [$tableName];
  57. }
  58. if ($withColumns === false) {
  59. $io->table(['Tables'], array_map(function (string $table) {
  60. return [$table];
  61. }, $tables));
  62. }else {
  63. foreach ($tables as $table) {
  64. $io->title(sprintf('Table : %s', $table));
  65. if ($withColumns === true) {
  66. $columns = array_map(function (ColumnMetadata $column) {
  67. $data = $column->toArray();
  68. foreach ($data as $key => $value) {
  69. $data[$key] = is_array($value) ? json_encode($value) : $value;
  70. }
  71. return $data;
  72. }, $platform->listTableColumns($table));
  73. $io->table(array_keys($columns[0]), $columns);
  74. }
  75. }
  76. }
  77. $io->writeln('');
  78. }
  79. }