Passed
Push — master ( d2ad69...686350 )
by Kacper
02:44
created

CliFormatter::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 3
ccs 3
cts 3
cp 1
rs 10
cc 2
eloc 2
nc 2
nop 1
crap 2
1
<?php
2
/**
3
 * Highlighter
4
 *
5
 * Copyright (C) 2015, Some right reserved.
6
 *
7
 * @author Kacper "Kadet" Donat <[email protected]>
8
 *
9
 * Contact with author:
10
 * Xmpp: [email protected]
11
 * E-mail: [email protected]
12
 *
13
 * From Kadet with love.
14
 */
15
16
namespace Kadet\Highlighter\Formatter;
17
18
use Kadet\Highlighter\Parser\Token;
19
use Kadet\Highlighter\Parser\TokenIterator;
20
use Kadet\Highlighter\Utils\Console;
21
22
/**
23
 * Class CliFormatter
24
 *
25
 * @package Kadet\Highlighter\Formatter
26
 */
27
class CliFormatter implements FormatterInterface
28
{
29
    private $_styles;
30
31
    /**
32
     * CliFormatter constructor.
33
     *
34
     * @param $styles
35
     */
36 1
    public function __construct($styles = false) {
37 1
        $this->_styles = $styles ?: include __DIR__.'/../Styles/Cli/Default.php';
38 1
    }
39
40 1
    public function format(TokenIterator $tokens)
41
    {
42 1
        $source = $tokens->getSource();
43
44 1
        $result = '';
45 1
        $last = 0;
46
47
        /** @var Token $token */
48 1
        foreach ($tokens as $token) {
49 1
            $result .= substr($source, $last, $token->pos - $last);
50
51 1
            if (($style = self::getColor($token->name)) !== null) {
52 1
                $result .= $token->isStart() ? Console::open($style) : Console::close();
53 1
            }
54
55 1
            $last = $token->pos;
56 1
        }
57 1
        $result .= substr($source, $last).Console::reset();
58
59 1
        return $result;
60
    }
61
62 1
    public function getColor($token)
63
    {
64
        do {
65 1
            if(isset($this->_styles[$token])) {
66 1
                return $this->_styles[$token];
67
            }
68
69 1
            $token = explode('.', $token);
70 1
            array_pop($token);
71 1
            $token = implode('.', $token);
72 1
        } while (!empty($token));
73
74
        return null;
75
    }
76
77
}