Completed
Push — master ( 9b98d4...f3f280 )
by Maciej
06:39
created

HtmlFormatter   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Test Coverage

Coverage 86.21%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 26
dl 0
loc 68
ccs 25
cts 29
cp 0.8621
rs 10
c 1
b 0
f 0
wmc 9

8 Methods

Rating   Name   Duplication   Size   Complexity  
A formatLineEnd() 0 3 1
A getOpenTag() 0 6 1
A token() 0 7 2
A getCloseTag() 0 3 1
A formatLineStart() 0 3 1
A content() 0 3 1
A __construct() 0 11 1
A format() 0 4 1
1
<?php
2
3
/**
4
 * Highlighter
5
 *
6
 * Copyright (C) 2016, Some right reserved.
7
 *
8
 * @author Kacper "Kadet" Donat <[email protected]>
9
 *
10
 * Contact with author:
11
 * Xmpp:   [email protected]
12
 * E-mail: [email protected]
13
 *
14
 * From Kadet with love.
15
 */
16
17
namespace Kadet\Highlighter\Formatter;
18
19
use Kadet\Highlighter\Parser\Token\Token;
20
use Kadet\Highlighter\Parser\Tokens;
21
22
/**
23
 * Class HtmlFormatter
24
 *
25
 * @package Kadet\Highlighter\Formatter
26
 */
27
class HtmlFormatter extends AbstractFormatter implements FormatterInterface
28
{
29
    protected $_prefix = '';
30
    protected $_tag    = 'span';
31
32
    private $_stack;
33
34
    /**
35
     * HtmlFormatter constructor.
36
     *
37
     * @param array $options
38
     */
39 4
    public function __construct(array $options = [])
40
    {
41 4
        parent::__construct($options);
42
43 4
        $options = array_merge([
44 4
            'prefix' => 'kl-',
45
            'tag'    => 'span'
46 4
        ], $options);
47
48 4
        $this->_tag    = $options['tag'];
49 4
        $this->_prefix = $options['prefix'];
50 4
    }
51
52 4
    public function format(Tokens $tokens)
53
    {
54 4
        $this->_stack = [];
55 4
        return parent::format($tokens);
56
    }
57
58 4
    protected function getOpenTag(Token $token)
59
    {
60 4
        return sprintf(
61 4
            '<%s class="%s">',
62 4
            $this->_tag,
63 4
            $this->_prefix . str_replace('.', " {$this->_prefix}", $token->name)
64
        );
65
    }
66
67 4
    protected function getCloseTag()
68
    {
69 4
        return "</{$this->_tag}>";
70
    }
71
72 4
    protected function token(Token $token)
73
    {
74 4
        if ($token->isStart()) {
75 4
            return $this->_stack[] = $this->getOpenTag($token);
76
        } else {
77 4
            array_pop($this->_stack);
78 4
            return $this->getCloseTag();
79
        }
80
    }
81
82 4
    protected function content($text)
83
    {
84 4
        return htmlspecialchars($text);
85
    }
86
87
    protected function formatLineStart($line)
88
    {
89
        return implode('', $this->_stack);
90
    }
91
92
    protected function formatLineEnd($line)
93
    {
94
        return str_repeat($this->getCloseTag(), count($this->_stack));
95
    }
96
}
97