Application::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 1
1
<?php
2
3
namespace SugaredRim\PHPMD\TextUI;
4
5
use PHPMD\RuleSetFactory;
6
use PHPMD\TextUI\Command;
7
use Psr\Log\LoggerInterface;
8
use Psr\Log\LogLevel;
9
use Schnittstabil\ComposerExtra\ComposerExtra;
10
11
class Application
12
{
13
    protected $defaultNamespace = 'sugared-rim/phpmd';
14
    protected $defaultConfig;
15
    /**
16
     * @var LoggerInterface
17
     */
18
    protected $logger;
19
20
    public function __construct(LoggerInterface $logger = null)
21
    {
22
        $this->logger = $logger;
23
        $this->defaultConfig = new \stdClass();
24
        $this->defaultConfig->presets = [
25
            'SugaredRim\\PHPMD\\DefaultPreset::get',
26
        ];
27
    }
28
29
    protected function getConfig($namespace)
30
    {
31
        return (new ComposerExtra(
32
            $namespace,
33
            $this->defaultConfig,
34
            'presets'
35
        ))->get();
36
    }
37
38
    protected function parseSugaredArgv(array $args)
39
    {
40
        $options = [
41
            'namespace' => $this->defaultNamespace,
42
        ];
43
44
        foreach ($args as $k => &$v) {
45
            if (substr($v, 0, 12) === '--namespace=') {
46
                $options['namespace'] = substr($v, 12);
47
                unset($args[$k]);
48
            }
49
        }
50
51
        $options['args'] = $args;
52
53
        return $options;
54
    }
55
56
    protected function runCommand(array $args)
57
    {
58
        $argv = $this->parseSugaredArgv($args);
59
        $config = $this->getConfig($argv['namespace']);
60
        $ruleSetFactory = new RuleSetFactory();
61
        $options = new CommandLineOptions(
62
            $argv['args'],
63
            $ruleSetFactory->listAvailableRuleSets(),
64
            $config
65
        );
66
        $command = new Command();
67
68
        return $command->run($options, $ruleSetFactory);
69
    }
70
71
    protected function log($level, $message)
72
    {
73
        // @codeCoverageIgnoreStart
74
        if ($this->logger === null) {
75
            $message = sprintf('[%s] %s %s', date('Y-m-d H:i:s'), strtoupper($level), $message);
76
            echo $message;
77
            flush();
78
            return;
79
        }
80
        // @codeCoverageIgnoreEnd
81
        $this->logger->log($level, $message);
82
    }
83
84
    public function main(array $args)
85
    {
86
        try {
87
            $exitCode = $this->runCommand($args);
88
        } catch (\Exception $e) {
89
            $this->log(LogLevel::ERROR, $e->getMessage());
90
            $exitCode = Command::EXIT_EXCEPTION;
91
        }
92
93
        return $exitCode;
94
    }
95
}
96