Completed
Push — nln-php7 ( 6680df...1a6b54 )
by Nicolas
02:06
created

OutputInterfaceAdapter   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 2
dl 0
loc 70
ccs 32
cts 32
cp 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace Karma\Logging;
6
7
use Psr\Log\LoggerInterface;
8
use Symfony\Component\Console\Output\Output;
9
use Symfony\Component\Console\Output\OutputInterface;
10
use Psr\Log\LogLevel;
11
12
class OutputInterfaceAdapter implements LoggerInterface
13
{
14
    use \Psr\Log\LoggerTrait;
15
16
    private OutputInterface
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_STRING, expecting T_FUNCTION or T_CONST
Loading history...
17
        $output;
18
    private array
19
        $levelConversionTable;
20
21 274
    public function __construct(OutputInterface $output)
22
    {
23 274
        $this->output = $output;
24
25 274
        $this->levelConversionTable = [
26 274
            LogLevel::DEBUG => OutputInterface::VERBOSITY_VERBOSE,
27 274
            LogLevel::INFO => OutputInterface::VERBOSITY_NORMAL,
28 274
            LogLevel::WARNING => OutputInterface::VERBOSITY_NORMAL,
29 274
            LogLevel::ERROR => OutputInterface::VERBOSITY_NORMAL
30
        ];
31 274
    }
32
33 225
    public function log($level, $message, array $context = [])
34
    {
35 225
        if($this->convertLevel($level) <= $this->output->getVerbosity())
36
        {
37 27
            $this->writeLevel($level);
38 27
            $this->output->writeln($message, OutputInterface::OUTPUT_NORMAL);
39
        }
40 225
    }
41
42 225
    private function convertLevel($level)
43
    {
44 225
        $verbosity = OutputInterface::VERBOSITY_NORMAL;
45
46 225
        if(array_key_exists($level, $this->levelConversionTable))
47
        {
48 225
            $verbosity = $this->levelConversionTable[$level];
49
        }
50
51 225
        return $verbosity;
52
    }
53
54 27
    private function writeLevel($level)
55
    {
56 27
        $message = str_pad(sprintf(
57 27
           '[%s]',
58 27
           strtoupper($level)
59 27
        ), 10);
60
61 27
        $this->output->write($this->colorizeMessage($level, $message));
62 27
    }
63
64 27
    private function colorizeMessage($level, $message)
65
    {
66
        $colors = [
67 27
            LogLevel::ERROR => 'red',
68
            LogLevel::WARNING => 'yellow',
69
        ];
70
71 27
        if(isset($colors[$level]))
72
        {
73 8
            $message = sprintf(
74 8
               '<%1$s>%2$s</%1$s>',
75 8
                'fg=' . $colors[$level],
76
                $message
77
            );
78
        }
79
80 27
        return $message;
81
    }
82
}
83