Completed
Push — master ( 2515f9...556e6f )
by Stanislav
03:05
created

Command::getRawHelp()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace Popstas\Transmission\Console\Command;
4
5
use GuzzleHttp;
6
use InfluxDB;
7
use Martial\Transmission\API;
8
use Popstas\Transmission\Console;
9
use Popstas\Transmission\Console\Application;
10
use Popstas\Transmission\Console\Config;
11
use Popstas\Transmission\Console\TransmissionClient;
12
use Psr\Log\LogLevel;
13
use Symfony\Component\Console\Command\Command as BaseCommand;
14
use Symfony\Component\Console\Input\InputInterface;
15
use Symfony\Component\Console\Input\InputOption;
16
use Symfony\Component\Console\Logger\ConsoleLogger;
17
use Symfony\Component\Console\Output\OutputInterface;
18
19
class Command extends BaseCommand
20
{
21
    private $help;
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
22
23
    protected function configure()
24
    {
25
        $this->addOption('dry-run', null, InputOption::VALUE_NONE, 'Dry run, don\'t change any data');
26
        $this->addOption('config', null, InputOption::VALUE_OPTIONAL, 'Configuration file');
27
        $this->addOption('transmission-host', null, InputOption::VALUE_OPTIONAL, 'Transmission host');
28
        $this->addOption('transmission-port', null, InputOption::VALUE_OPTIONAL, 'Transmission port');
29
        $this->addOption('transmission-user', null, InputOption::VALUE_OPTIONAL, 'Transmission user');
30
        $this->addOption('transmission-password', null, InputOption::VALUE_OPTIONAL, 'Transmission password');
31
    }
32
33
    /**
34
     * @return Application
35
     */
36
    public function getApplication()
37
    {
38
        return parent::getApplication();
39
    }
40
41
    protected function initialize(InputInterface $input, OutputInterface $output)
0 ignored issues
show
Coding Style introduced by
initialize uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
42
    {
43
        // logger
44
        $logger = $this->getApplication()->getLogger();
45
        if (!isset($logger)) {
46
            $verbosityLevelMap = [
47
                LogLevel::NOTICE => OutputInterface::VERBOSITY_NORMAL,
48
                LogLevel::INFO   => OutputInterface::VERBOSITY_VERBOSE,
49
                LogLevel::DEBUG  => OutputInterface::VERBOSITY_DEBUG,
50
            ];
51
            $logger = new ConsoleLogger($output, $verbosityLevelMap);
52
            $this->getApplication()->setLogger($logger);
53
        }
54
55
        // config
56
        $config = $this->getApplication()->getConfig();
57
        if (!isset($config)) {
58
            $config = new Config($input->getOption('config'));
59
            try {
60
                $config->loadConfigFile();
61
            } catch (\RuntimeException $e) {
62
                $logger->critical($e->getMessage());
63
                $this->setCode(function () {
64
                    return 1;
65
                });
66
                return;
67
            }
68
            $this->getApplication()->setConfig($config);
69
        }
70
71
        // client
72
        $client = $this->getApplication()->getClient();
73
        if (!isset($client)) {
74
            $client = $this->createTransmissionClient(
75
                $config->overrideConfig($input, 'transmission-host'),
76
                $config->overrideConfig($input, 'transmission-port'),
77
                $config->overrideConfig($input, 'transmission-user'),
78
                $config->overrideConfig($input, 'transmission-password')
79
            );
80
            $this->getApplication()->setClient($client);
81
        }
82
83
        $logger->info('[{date}] command: {args}', [
84
            'date' => date('Y-m-d H:i:s'),
85
            'args' => implode(' ', array_slice($_SERVER['argv'], 1)),
86
        ]);
87
88
        parent::initialize($input, $output);
89
    }
90
91
    private function createTransmissionClient($host, $port, $user, $password)
92
    {
93
        $logger = $this->getApplication()->getLogger();
94
95
        $connect = ['host' => $host, 'port' => $port, 'user' => $user, 'password' => $password];
96
97
        $baseUri = 'http://' . $connect['host'] . ':' . $connect['port'] . '/transmission/rpc';
98
        $httpClient = new GuzzleHttp\Client(['base_uri' => $baseUri]);
99
100
        $api = new API\RpcClient($httpClient, $connect['user'], $connect['password']);
101
        $api->setLogger($logger);
102
103
        $logger->debug('Connect Transmission using: {user}:{password}@{host}:{port}', $connect);
104
105
        return new TransmissionClient($api);
106
    }
107
108
    public function dryRun(
109
        InputInterface $input,
110
        OutputInterface $output,
111
        \Closure $callback,
112
        $message = 'dry-run, don\'t doing anything'
113
    ) {
114
        if (!$input->getOption('dry-run')) {
115
            return $callback();
116
        } else {
117
            $output->writeln($message);
118
            return true;
119
        }
120
    }
121
122
    public function setHelp($help)
123
    {
124
        $this->help = $help;
125
        $help = preg_replace('/```\n(.*?)\n```/mis', '<info>$1</info>', $help);
126
        $help = preg_replace('/(\n|^)#+ (.*)/', '$1<question>$2</question>', $help);
127
        $help = preg_replace('/`([^`]*?)`/', '<comment>$1</comment>', $help);
128
        $help = preg_replace('/\*\*(.*?)\*\*/', '<comment>$1</comment>', $help);
129
        return parent::setHelp($help);
130
    }
131
    
132
    public function getRawHelp()
133
    {
134
        return $this->help;
135
    }
136
}
137