ListCommand   A
last analyzed

Complexity

Total Complexity 15

Size/Duplication

Total Lines 153
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 67
c 1
b 0
f 0
dl 0
loc 153
rs 10
wmc 15

4 Methods

Rating   Name   Duplication   Size   Complexity  
C execute() 0 81 12
A configure() 0 9 1
A initialize() 0 7 1
A __construct() 0 6 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Biurad opensource projects.
7
 *
8
 * PHP version 7.2 and above required
9
 *
10
 * @author    Divine Niiquaye Ibok <[email protected]>
11
 * @copyright 2019 Biurad Group (https://biurad.com/)
12
 * @license   https://opensource.org/licenses/BSD-3-Clause License
13
 *
14
 * For the full copyright and license information, please view the LICENSE
15
 * file that was distributed with this source code.
16
 */
17
18
namespace Biurad\Cycle\Commands\Database;
19
20
use Exception;
21
use Spiral\Database\Config\DatabaseConfig;
22
use Spiral\Database\Config\DatabasePartial;
23
use Spiral\Database\DatabaseProviderInterface;
24
use Symfony\Component\Console\Command\Command;
25
use Symfony\Component\Console\Helper\Table;
26
use Symfony\Component\Console\Helper\TableSeparator;
27
use Symfony\Component\Console\Input\InputArgument;
28
use Symfony\Component\Console\Input\InputInterface;
29
use Symfony\Component\Console\Output\OutputInterface;
30
use Symfony\Component\Console\Style\SymfonyStyle;
31
32
/**
33
 * List of every configured database, it's tables and count of records.
34
 *
35
 * @final
36
 */
37
class ListCommand extends Command
38
{
39
    /**
40
     * No information available placeholder.
41
     */
42
    private const SKIP = '<comment>---</comment>';
43
44
    protected static $defaultName = 'database:list';
45
46
    /** @var DatabaseProviderInterface */
47
    private $factory;
48
49
    /** @var DatabaseConfig */
50
    private $config;
51
52
    /** @var SymfonyStyle */
53
    private $io;
54
55
    /** @var Table */
56
    private $table;
57
58
    public function __construct(DatabaseConfig $config, DatabaseProviderInterface $dbal)
59
    {
60
        $this->factory = $dbal;
61
        $this->config  = $config;
62
63
        parent::__construct();
64
    }
65
66
    /**
67
     * {@inheritdoc}
68
     */
69
    protected function configure(): void
70
    {
71
        $this
72
            ->setDefinition([
73
                new InputArgument('db', InputArgument::OPTIONAL, 'Database name'),
74
            ])
75
            ->setDescription('Get list of available databases, their tables and records count')
76
            ->setHelp(
77
                <<<EOT
78
The <info>%command.name%</info> command list the default connections databases:
79
80
    <info>php %command.full_name%</info>
81
82
You can also optionally specify the name of a database name to view it's connection and tables:
83
84
    <info>php %command.full_name% migrations</info>
85
EOT
86
            )
87
        ;
88
    }
89
90
    /**
91
     * This optional method is the first one executed for a command after configure()
92
     * and is useful to initialize properties based on the input arguments and options.
93
     *
94
     * @param InputInterface  $input
95
     * @param OutputInterface $output
96
     */
97
    protected function initialize(InputInterface $input, OutputInterface $output): void
98
    {
99
        // SymfonyStyle is an optional feature that Symfony provides so you can
100
        // apply a consistent look to the commands of your application.
101
        // See https://symfony.com/doc/current/console/style.html
102
        $this->io    = new SymfonyStyle($input, $output);
103
        $this->table = new Table($output);
104
    }
105
106
    /**
107
     * {@inheritdoc}
108
     */
109
    protected function execute(InputInterface $input, OutputInterface $output): int
110
    {
111
        //Every available database
112
        $databases = $this->config->getDatabases();
113
114
        if ($input->getArgument('db')) {
115
            $databases = [$input->getArgument('db')];
116
        }
117
118
        if (empty($databases)) {
119
            $this->io->error('No databases found.');
120
121
            return 1;
122
        }
123
124
        $grid = $this->table->setHeaders([
125
            'Name (ID):',
126
            'Database:',
127
            'Driver:',
128
            'Prefix:',
129
            'Status:',
130
            'Tables:',
131
            'Count Records:',
132
        ]);
133
134
        foreach ($databases as $database) {
135
            if ($database instanceof DatabasePartial) {
136
                $database = $database->getName();
137
            }
138
139
            $database = $this->factory->database($database);
140
            $driver   = $database->getDriver();
141
142
            $source = $driver->getSource();
143
144
            if (\is_file($driver->getSource())) {
145
                $source = \basename($driver->getSource());
146
            }
147
148
            $header = [
149
                $database->getName(), $source,
150
                $driver->getType(),
151
                $database->getPrefix() ?: self::SKIP,
152
            ];
153
154
            try {
155
                $driver->connect();
156
            } catch (Exception $exception) {
157
                $grid->addRow(\array_merge($header, [
158
                    "<fg=red>{$exception->getMessage()}</fg=red>",
159
                    self::SKIP,
160
                    self::SKIP,
161
                ]));
162
163
                if ($database->getName() !== \end($databases)) {
164
                    $grid->addRow(new TableSeparator());
165
                }
166
167
                continue;
168
            }
169
170
            $header[] = '<info>connected</info>';
171
172
            foreach ($database->getTables() as $table) {
173
                $grid->addRow(\array_merge(
174
                    $header,
175
                    [$table->getName(), \number_format($table->count())]
176
                ));
177
                $header = ['', '', '', '', ''];
178
            }
179
180
            $header[1] && $grid->addRow(\array_merge($header, ['no tables', 'no records']));
181
182
            if ($database->getName() !== \end($databases)) {
183
                $grid->addRow(new TableSeparator());
184
            }
185
        }
186
187
        $grid->render();
188
189
        return 0;
190
    }
191
}
192