Passed
Branch master (f3f280)
by Maciej
03:18
created

HtmlFormatter::content()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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