Completed
Push — master ( 39b788...79bdc8 )
by Stanislav
02:16
created

StatsGet::execute()   B

Complexity

Conditions 6
Paths 47

Size

Total Lines 66
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 1 Features 1
Metric Value
c 5
b 1
f 1
dl 0
loc 66
rs 8.6045
cc 6
eloc 43
nc 47
nop 2

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
namespace Popstas\Transmission\Console\Command;
4
5
use InfluxDB;
6
use Martial\Transmission\API\Argument\Torrent;
7
use Popstas\Transmission\Console\Helpers\TableUtils;
8
use Popstas\Transmission\Console\Helpers\TorrentListUtils;
9
use Popstas\Transmission\Console\Helpers\TorrentUtils;
10
use Symfony\Component\Console\Input\ArrayInput;
11
use Symfony\Component\Console\Input\InputInterface;
12
use Symfony\Component\Console\Input\InputOption;
13
use Symfony\Component\Console\Output\OutputInterface;
14
15
class StatsGet extends Command
16
{
17
    protected function configure()
18
    {
19
        parent::configure();
20
        $this
21
            ->setName('stats-get')
22
            ->setAliases(['sg'])
23
            ->setDescription('Get metrics from InfluxDB')
24
            ->addOption('sort', null, InputOption::VALUE_OPTIONAL, 'Sort by column number', 4)
25
            ->addOption('name', null, InputOption::VALUE_OPTIONAL, 'Sort by torrent name (regexp)')
26
            ->addOption('days', null, InputOption::VALUE_OPTIONAL, 'Show stats for last days', 7)
27
            ->addOption('limit', null, InputOption::VALUE_OPTIONAL, 'Limit torrent list')
28
            ->addOption('profit', null, InputOption::VALUE_OPTIONAL, 'Filter by profit')
29
            ->addOption('rm', null, InputOption::VALUE_NONE, 'Remove filtered torrents')
30
            ->addOption('soft', null, InputOption::VALUE_NONE, 'Remove only from Transmission, not delete data')
31
            ->addOption('yes', 'y', InputOption::VALUE_NONE, 'Don\'t ask confirmation')
32
            ->addOption('transmission-host', null, InputOption::VALUE_OPTIONAL, 'Transmission host')
33
            ->setHelp(<<<EOT
34
The <info>stats-get</info> sends upload ever for every torrent to InfluxDB.
35
EOT
36
            );
37
    }
38
39
    protected function execute(InputInterface $input, OutputInterface $output)
40
    {
41
        $config = $this->getApplication()->getConfig();
42
        $logger = $this->getApplication()->getLogger();
43
        $client = $this->getApplication()->getClient();
44
45
        try {
46
            $influxDbClient = $this->getApplication()->getInfluxDbClient(
47
                $config->get('influxdb-host'),
48
                $config->get('influxdb-port'),
49
                $config->get('influxdb-user'),
50
                $config->get('influxdb-password'),
51
                $config->get('influxdb-database')
52
            );
53
54
            $lastDays = (int)$input->getOption('days') ? (int)$input->getOption('days') : 0;
55
            $limit = (int)$input->getOption('limit') ? (int)$input->getOption('limit') : 0;
56
57
            $torrentList = $client->getTorrentData();
58
59
            $torrentList = TorrentListUtils::filterTorrents($torrentList, [
60
                'name' => $input->getOption('name'),
61
            ]);
62
63
            $transmissionHost = $config->overrideConfig($input, 'transmission-host');
64
65
            $rows = [];
66
67
            foreach ($torrentList as $torrent) {
68
                $uploaded = $influxDbClient->getTorrentSum($torrent, 'uploaded_last', $transmissionHost, $lastDays);
69
70
                $profit = round($uploaded / $torrent[Torrent\Get::TOTAL_SIZE], 2);
71
72
                $rows[] = [
73
                    $torrent[Torrent\Get::NAME],
74
                    $torrent[Torrent\Get::ID],
75
                    TorrentUtils::getSizeInGb($uploaded) . ' GB',
76
                    $profit
77
                ];
78
            }
79
        } catch (\Exception $e) {
80
            $logger->critical($e->getMessage());
81
            return 1;
82
        }
83
84
        $rows = TableUtils::filterRows($rows, [
85
            '3' => ['type' => 'numeric', 'value' => $input->getOption('profit')]
86
        ]);
87
88
        TableUtils::printTable([
89
            'headers' => ['Name', 'Id', 'Uploaded', 'Profit'],
90
            'rows' => $rows,
91
            'totals' => [
92
                '',
93
                '',
94
                TorrentListUtils::sumArrayField($rows, 2),
95
                TorrentListUtils::sumArrayField($rows, 3)
96
            ]
97
        ], $output, $input->getOption('sort'), $limit);
98
99
        if ($input->getOption('rm')) {
100
            return $this->removeTorrents($input, $output, $rows);
101
        }
102
103
        return 0;
104
    }
105
106
    private function removeTorrents(InputInterface $input, OutputInterface $output, array $rows)
107
    {
108
        $limit = (int)$input->getOption('limit') ? (int)$input->getOption('limit') : 0;
109
110
        $rows = TableUtils::sortRowsByColumnNumber($rows, $input->getOption('sort'));
111
112
        if ($limit && $limit < count($rows)) {
113
            $rows = array_slice($rows, 0, $limit);
114
        }
115
116
        $torrentIds = TorrentListUtils::getArrayField($rows, 1);
117
        $command = $this->getApplication()->find('torrent-remove');
118
        $arguments = array(
119
            'command'     => 'torrent-remove',
120
            'torrent-ids' => $torrentIds,
121
            '--dry-run'   => $input->getOption('dry-run'),
122
            '--yes'       => $input->getOption('yes'),
123
            '--soft'      => $input->getOption('soft'),
124
        );
125
126
        $removeInput = new ArrayInput($arguments);
127
        return $command->run($removeInput, $output);
128
    }
129
}
130