Completed
Push — 42-formatter ( cff7a4 )
by Nicolas
32:10 queued 28:41
created

OutputInterfaceAdapter::colorizeMessage()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 18
rs 9.4286
cc 2
eloc 10
nc 2
nop 2
1
<?php
2
3
namespace Karma\Logging;
4
5
use Psr\Log\LoggerInterface;
6
use Symfony\Component\Console\Output\OutputInterface;
7
use Psr\Log\LogLevel;
8
9
class OutputInterfaceAdapter implements LoggerInterface
10
{
11
    use \Psr\Log\LoggerTrait;
12
13
    private
14
        $output,
0 ignored issues
show
Coding Style introduced by
It is generally advisable to only define one property per statement.

Only declaring a single property per statement allows you to later on add doc comments more easily.

It is also recommended by PSR2, so it is a common style that many people expect.

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