Passed
Push — master ( 1d0ea2...0f9d68 )
by Kacper
05:34
created

HtmlFormatter   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Test Coverage

Coverage 85.71%

Importance

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