Passed
Push — master ( f015ee...816b5a )
by Samuel
02:00
created

Application::parseConfiguration()   C

Complexity

Conditions 16
Paths 87

Size

Total Lines 63
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 30
CRAP Score 18.3877

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 16
eloc 39
c 2
b 0
f 0
nc 87
nop 1
dl 0
loc 63
ccs 30
cts 38
cp 0.7895
crap 18.3877
rs 5.5666

How to fix   Long Method    Complexity   

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
/*
4
 * This file is part of CacheTool.
5
 *
6
 * (c) Samuel Gordalina <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace CacheTool\Console;
13
14
use CacheTool\Adapter\FastCGI;
15
use CacheTool\Adapter\Cli;
16
use CacheTool\Adapter\Http\FileGetContents;
17
use CacheTool\Adapter\Http\SymfonyHttpClient;
18
use CacheTool\Adapter\Web;
19
use CacheTool\CacheTool;
20
use CacheTool\Command as CacheToolCommand;
21
use CacheTool\Monolog\ConsoleHandler;
22
use Monolog\Logger;
23
use Symfony\Component\Console\Application as BaseApplication;
24
use Symfony\Component\Console\Command\Command;
25
use Symfony\Component\Console\Input\InputOption;
26
use Symfony\Component\Console\Input\InputInterface;
27
use Symfony\Component\Console\Output\OutputInterface;
28
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
29
use Symfony\Component\DependencyInjection\Container;
30
use Symfony\Component\DependencyInjection\ContainerInterface;
31
use Symfony\Component\Yaml\Parser;
32
33
class Application extends BaseApplication
34
{
35
    const VERSION = '@package_version@';
36
37
    /**
38
     * @var Config
39
     */
40
    protected $config;
41
42
    /**
43
     * @var Logger
44
     */
45
    protected $logger;
46
47
    /**
48
     * @param Config $config
49
     */
50 24
    public function __construct(Config $config)
51
    {
52 24
        parent::__construct('CacheTool', self::VERSION);
53
54 24
        $this->config = $config;
55 24
        $this->logger = new Logger('cachetool');
56 24
    }
57
58
    /**
59
     * {@inheritdoc}
60
     */
61 24
    protected function getDefaultCommands()
62
    {
63 24
        $commands = parent::getDefaultCommands();
64 24
        $commands[] = new CacheToolCommand\SelfUpdateCommand(
65 24
            'gordalina/cachetool',
66 24
            '@package_version@',
67 24
            'gordalina/cachetool'
68
        );
69
70 24
        if (in_array('apcu', $this->config['extensions'], true)) {
0 ignored issues
show
Bug introduced by
It seems like $this->config['extensions'] can also be of type null; however, parameter $haystack of in_array() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

70
        if (in_array('apcu', /** @scrutinizer ignore-type */ $this->config['extensions'], true)) {
Loading history...
71 23
            $commands[] = new CacheToolCommand\ApcuCacheClearCommand();
72 23
            $commands[] = new CacheToolCommand\ApcuCacheInfoCommand();
73 23
            $commands[] = new CacheToolCommand\ApcuCacheInfoKeysCommand();
74 23
            $commands[] = new CacheToolCommand\ApcuKeyDeleteCommand();
75 23
            $commands[] = new CacheToolCommand\ApcuKeyExistsCommand();
76 23
            $commands[] = new CacheToolCommand\ApcuKeyFetchCommand();
77 23
            $commands[] = new CacheToolCommand\ApcuKeyStoreCommand();
78 23
            $commands[] = new CacheToolCommand\ApcuSmaInfoCommand();
79 23
            $commands[] = new CacheToolCommand\ApcuRegexpDeleteCommand();
80
        }
81
82 24
        if (in_array('opcache', $this->config['extensions'], true)) {
83 23
            $commands[] = new CacheToolCommand\OpcacheConfigurationCommand();
84 23
            $commands[] = new CacheToolCommand\OpcacheResetCommand();
85 23
            $commands[] = new CacheToolCommand\OpcacheResetFileCacheCommand();
86 23
            $commands[] = new CacheToolCommand\OpcacheStatusCommand();
87 23
            $commands[] = new CacheToolCommand\OpcacheStatusScriptsCommand();
88 23
            $commands[] = new CacheToolCommand\OpcacheInvalidateScriptsCommand();
89 23
            $commands[] = new CacheToolCommand\OpcacheCompileScriptsCommand();
90 23
            $commands[] = new CacheToolCommand\OpcacheCompileScriptCommand();
91
        }
92
93 24
        $commands[] = new CacheToolCommand\PhpEvalCommand();
94 24
        $commands[] = new CacheToolCommand\StatCacheClearCommand();
95 24
        $commands[] = new CacheToolCommand\StatRealpathGetCommand();
96 24
        $commands[] = new CacheToolCommand\StatRealpathSizeCommand();
97
98 24
        return $commands;
99
    }
100
101
    /**
102
     * {@inheritDoc}
103
     */
104 24
    protected function getDefaultInputDefinition()
105
    {
106 24
        $definition = parent::getDefaultInputDefinition();
107 24
        $definition->addOption(new InputOption('--fcgi', null, InputOption::VALUE_OPTIONAL, 'If specified, used as a connection string to FastCGI server.'));
108 24
        $definition->addOption(new InputOption('--fcgi-chroot', null, InputOption::VALUE_OPTIONAL, 'If specified, used for mapping script path to chrooted FastCGI server. --tmp-dir need to be chrooted too.'));
109 24
        $definition->addOption(new InputOption('--cli', null, InputOption::VALUE_NONE, 'If specified, forces adapter to cli'));
110 24
        $definition->addOption(new InputOption('--web', null, InputOption::VALUE_OPTIONAL, 'If specified, uses web adapter, defaults to FileGetContents. Available adapters are: FileGetContents and SymfonyHttpClient', 'FileGetContents'));
111 24
        $definition->addOption(new InputOption('--web-path', null, InputOption::VALUE_OPTIONAL, 'If specified, used as a information for web adapter'));
112 24
        $definition->addOption(new InputOption('--web-url', null, InputOption::VALUE_OPTIONAL, 'If specified, used as a information for web adapter'));
113 24
        $definition->addOption(new InputOption('--web-allow-insecure', null, InputOption::VALUE_OPTIONAL, 'If specified, verify_peer and verify_host are disabled (only for SymfonyHttpClient)'));
114 24
        $definition->addOption(new InputOption('--web-basic-auth', null, InputOption::VALUE_OPTIONAL, 'If specified, used for basic authorization (only for SymfonyHttpClient)'));
115 24
        $definition->addOption(new InputOption('--tmp-dir', '-t', InputOption::VALUE_REQUIRED, 'Temporary directory to write files to'));
116 24
        $definition->addOption(new InputOption('--config', '-c', InputOption::VALUE_REQUIRED, 'If specified use this yaml configuration file'));
117 24
        return $definition;
118
    }
119
120
    /**
121
     * {@inheritDoc}
122
     */
123 24
    public function doRun(InputInterface $input, OutputInterface $output)
124
    {
125 24
        $handler = new ConsoleHandler();
126 24
        $handler->setOutput($output);
127 24
        $this->logger->pushHandler($handler);
128
129 24
        $exitCode = parent::doRun($input, $output);
130
131 21
        $handler->close();
132
133 21
        return $exitCode;
134
    }
135
136
    /**
137
     * {@inheritDoc}
138
     */
139 24
    public function doRunCommand(Command $command, InputInterface $input, OutputInterface $output)
140
    {
141 24
        if ($command instanceof ContainerAwareInterface) {
142 22
            $container = $this->buildContainer($input);
143 21
            $command->setContainer($container);
144
        }
145
146 23
        return parent::doRunCommand($command, $input, $output);
147
    }
148
149
    /**
150
     * @param  InputInterface     $input
151
     * @return ContainerInterface
152
     */
153 22
    public function buildContainer(InputInterface $input)
154
    {
155 22
        $this->parseConfiguration($input);
156
157 22
        $this->logger->info(sprintf('CacheTool %s', self::VERSION));
158 22
        $this->logger->debug(sprintf('Config: %s', $this->config->toJSON()));
159
160 22
        $cacheTool = CacheTool::factory(
161 22
            $this->getAdapter(),
162 21
            $this->config['temp_dir'],
163 21
            $this->logger
164
        );
165
166 21
        $container = new Container();
167 21
        $container->set('cachetool', $cacheTool);
168 21
        $container->set('logger', $this->logger);
169
170 21
        return $container;
171
    }
172
173
    /**
174
     * @param  InputInterface $input
175
     */
176 22
    private function parseConfiguration(InputInterface $input)
177
    {
178 22
        if ($input->hasParameterOption('--config')) {
179 1
            $path = $input->getParameterOption('--config');
180
181 1
            if (!is_file($path)) {
182
                throw new \RuntimeException("Could not read configuration file: {$path}");
183
            }
184
185 1
            $this->config = Config::fromFile($path);
186
        }
187
188 22
        if ($input->hasParameterOption('--cli')) {
189 1
            $this->config['adapter'] = 'cli';
190 21
        } elseif ($input->hasParameterOption('--fcgi')) {
191 1
            $this->config['adapter'] = 'fastcgi';
192 1
            $this->config['fastcgiChroot'] = $input->getParameterOption('--fcgi-chroot');
193
194 1
            if (!is_null($input->getParameterOption('--fcgi'))) {
195 1
                $this->config['fastcgi'] = $input->getParameterOption('--fcgi');
196
            }
197 20
        } elseif ($input->hasParameterOption('--web')) {
198 3
            $this->config['adapter'] = 'web';
199 3
            $this->config['webPath'] = $input->getParameterOption('--web-path');
200 3
            $this->config['webUrl'] = $input->getParameterOption('--web-url');
201
202 3
            switch ($input->getParameterOption('--web') ?? 'FileGetContents') {
203 3
                case 'FileGetContents':
204 2
                    $this->config['http'] = new FileGetContents($this->config['webUrl']);
205 2
                    break;
206
207 1
                case 'SymfonyHttpClient':
208 1
                    if ($input->hasParameterOption('--web-allow-insecure')) {
209
                        $this->config['webAllowInsecure'] = true;
210
                    }
211
212 1
                    if ($input->hasParameterOption('--web-basic-auth')) {
213
                        $this->config['webBasicAuth'] = $input->getParameterOption('--web-basic-auth');
214
                    }
215
216 1
                    $symfonyHttpClientConfig = [];
217
218 1
                    if ($this->config['webAllowInsecure']) {
219
                        $symfonyHttpClientConfig['verify_peer'] = false;
220
                        $symfonyHttpClientConfig['verify_host'] = false;
221
                    }
222
223 1
                    if ($this->config['webBasicAuth']) {
224
                        $symfonyHttpClientConfig['auth_basic'] = $this->config['webBasicAuth'];
225
                    }
226
227 1
                    $this->config['http'] = new SymfonyHttpClient($this->config['webUrl'], $symfonyHttpClientConfig);
228 1
                    break;
229
230
                default:
231
                    var_dump($this->config);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($this->config) looks like debug code. Are you sure you do not want to remove it?
Loading history...
232
                    var_dump($input->getParameterOption('--web', "LOL"));
233
                    throw new \RuntimeException("{$this->config["web"]} is not a valid adapter. Possible adapters: FileGetContents or SymfonyHttpClient");
234
            }
235
        }
236
237 22
        if ($input->hasParameterOption('--tmp-dir') || $input->hasParameterOption('-t')) {
238 1
            $this->config['temp_dir'] = $input->getParameterOption('--tmp-dir') ?: $input->getParameterOption('-t');
239
        }
240 22
    }
241
242
    /**
243
     * @return null|\CacheTool\Adapter\AbstractAdapter
244
     */
245 22
    private function getAdapter()
246
    {
247 22
        switch ($this->config['adapter']) {
248 22
            case 'cli':
249 15
                return new Cli();
250 7
            case 'fastcgi':
251 3
                return new FastCGI($this->config['fastcgi'], $this->config['fastcgiChroot']);
252 4
            case 'web':
253 3
                return new Web($this->config['webPath'], $this->config['http']);
0 ignored issues
show
Bug introduced by
It seems like $this->config['http'] can also be of type null; however, parameter $http of CacheTool\Adapter\Web::__construct() does only seem to accept CacheTool\Adapter\Http\HttpInterface, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

253
                return new Web($this->config['webPath'], /** @scrutinizer ignore-type */ $this->config['http']);
Loading history...
254
        }
255
256 1
        throw new \RuntimeException("Adapter `{$this->config['adapter']}` is not one of cli, fastcgi or web");
257
    }
258
}
259