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