Passed
Push — master ( 37c5f2...a4e384 )
by Divine Niiquaye
03:06
created

DatabaseListCommand::execute()   B

Complexity

Conditions 8
Paths 12

Size

Total Lines 64
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 36
c 1
b 0
f 0
nc 12
nop 2
dl 0
loc 64
ccs 0
cts 26
cp 0
crap 72
rs 8.0995

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of DivineNii opensource projects.
7
 *
8
 * PHP version 7.4 and above required
9
 *
10
 * @author    Divine Niiquaye Ibok <[email protected]>
11
 * @copyright 2019 DivineNii (https://divinenii.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 Rade\Commands\CycleORM;
19
20
use Cycle\Database\Config\DatabaseConfig;
0 ignored issues
show
Bug introduced by
The type Cycle\Database\Config\DatabaseConfig was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
21
use Cycle\Database\Database;
0 ignored issues
show
Bug introduced by
The type Cycle\Database\Database was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
22
use Cycle\Database\DatabaseProviderInterface;
0 ignored issues
show
Bug introduced by
The type Cycle\Database\DatabaseProviderInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
23
use Cycle\Database\Driver\Driver;
0 ignored issues
show
Bug introduced by
The type Cycle\Database\Driver\Driver was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
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
31
/**
32
 * List of every configured database, it's tables and count of records.
33
 *
34
 * @author Divine Niiquaye Ibok <[email protected]>
35
 */
36
final class DatabaseListCommand extends Command
37
{
38
    /**
39
     * No information available placeholder.
40
     */
41
    private const SKIP = '<comment>---</comment>';
42
43
    protected static $defaultName = 'cycle:database:list';
44
45
    public function __construct(private DatabaseConfig $config, private DatabaseProviderInterface $provider)
46
    {
47
        parent::__construct();
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53
    protected function configure(): void
54
    {
55
        $this
56
            ->setDefinition([
57
                new InputArgument('db', InputArgument::OPTIONAL, 'Database name'),
58
            ])
59
            ->setDescription('Get list of available databases, their tables and records count')
60
            ->setHelp(
61
                <<<EOT
62
The <info>%command.name%</info> command list the default connections databases:
63
64
    <info>php %command.full_name%</info>
65
66
You can also optionally specify the name of a database name to view it's connection and tables:
67
68
    <info>php %command.full_name% migrations</info>
69
EOT
70
            )
71
        ;
72
    }
73
74
    /**
75
     * {@inheritdoc}
76
     */
77
    protected function execute(InputInterface $input, OutputInterface $output): int
78
    {
79
        $databases = $input->getArgument('db') ?? \array_keys($this->config->getDatabases());
80
81
        if (!\is_array($databases)) {
82
            $databases = [$databases];
83
        }
84
85
        if (empty($databases)) {
86
            $output->writeln('<fg=red>No databases found.</fg=red>');
87
88
            return self::SUCCESS;
89
        }
90
91
        // create symfony command table
92
        $grid = new Table($output);
93
        $grid->setHeaders(
94
            [
95
                'Name (ID):',
96
                'Database:',
97
                'Driver:',
98
                'Prefix:',
99
                'Status:',
100
                'Tables:',
101
                'Count Records:',
102
            ]
103
        );
104
105
        foreach ($databases as $database) {
106
            $database = $this->provider->database($database);
107
108
            /** @var Driver $driver */
109
            $driver = $database->getDriver();
110
111
            $header = [
112
                $database->getName(),
113
                $driver->getSource(),
114
                $driver->getType(),
115
                $database->getPrefix() ?: self::SKIP,
116
            ];
117
118
            try {
119
                $driver->connect();
120
            } catch (\Exception $exception) {
121
                $this->renderException($grid, $header, $exception);
122
123
                if ($database->getName() != \end($databases)) {
124
                    $grid->addRow(new TableSeparator());
125
                }
126
127
                continue;
128
            }
129
130
            $header[] = '<info>connected</info>';
131
            $this->renderTables($grid, $header, $database);
132
133
            if ($database->getName() != \end($databases)) {
134
                $grid->addRow(new TableSeparator());
135
            }
136
        }
137
138
        $grid->render();
139
140
        return self::SUCCESS;
141
    }
142
143
    private function renderException(Table $grid, array $header, \Throwable $exception): void
144
    {
145
        $grid->addRow(
146
            \array_merge(
147
                $header,
148
                [
149
                    "<fg=red>{$exception->getMessage()}</fg=red>",
150
                    self::SKIP,
151
                    self::SKIP,
152
                ]
153
            )
154
        );
155
    }
156
157
    private function renderTables(Table $grid, array $header, Database $database): void
158
    {
159
        foreach ($database->getTables() as $table) {
160
            $grid->addRow(
161
                \array_merge(
162
                    $header,
163
                    [$table->getName(), \number_format($table->count())]
164
                )
165
            );
166
            $header = ['', '', '', '', ''];
167
        }
168
169
        $header[1] && $grid->addRow(\array_merge($header, ['no tables', 'no records']));
170
    }
171
}
172