1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
|
4
|
|
|
namespace Kadet\Highlighter\Formatter; |
5
|
|
|
|
6
|
|
|
|
7
|
|
|
use Kadet\Highlighter\Parser\Token\Token; |
8
|
|
|
use Kadet\Highlighter\Parser\Tokens; |
9
|
|
|
|
10
|
|
|
abstract class AbstractFormatter implements FormatterInterface |
11
|
|
|
{ |
12
|
|
|
protected $_options = []; |
13
|
|
|
protected $_line = 1; |
14
|
|
|
|
15
|
39 |
|
public function __construct(array $options = []) |
16
|
|
|
{ |
17
|
39 |
|
$this->_options = array_replace_recursive([ |
18
|
|
|
'lines' => [ |
19
|
39 |
|
'enable' => false, |
20
|
39 |
|
'start' => 1, |
21
|
39 |
|
'marked' => [] |
22
|
39 |
|
] |
23
|
39 |
|
], $options); |
24
|
39 |
|
} |
25
|
|
|
|
26
|
6 |
|
public function format(Tokens $tokens) |
27
|
|
|
{ |
28
|
6 |
|
$source = $tokens->getSource(); |
29
|
|
|
|
30
|
6 |
|
$this->_line = (int)$this->_options['lines']['start']; |
31
|
6 |
|
$this->_options['lines']['max'] = substr_count($source, '\n') + $this->_options['lines']['start']; |
32
|
|
|
|
33
|
6 |
|
$result = $this->_options['lines']['enable'] ? $this->formatLineStart($this->_line) : ''; |
34
|
6 |
|
$last = 0; |
35
|
|
|
|
36
|
|
|
/** @var Token $token */ |
37
|
6 |
|
foreach ($tokens as $token) { |
38
|
6 |
|
$result .= $this->_content(substr($source, $last, $token->pos - $last)); |
39
|
6 |
|
$result .= $this->token($token); |
40
|
|
|
|
41
|
6 |
|
$last = $token->pos; |
42
|
6 |
|
} |
43
|
6 |
|
$result .= $this->_content(substr($source, $last)); |
44
|
|
|
|
45
|
6 |
|
return $result.($this->_options['lines']['enable'] ? $this->formatLineEnd($this->_line++) : ''); |
46
|
|
|
} |
47
|
|
|
|
48
|
6 |
|
private function _content($text) |
49
|
|
|
{ |
50
|
6 |
|
$content = $this->content($text); |
51
|
|
|
|
52
|
6 |
|
return $this->_options['lines']['enable'] ? preg_replace_callback('/\R/u', function($feed) { |
53
|
|
|
return $this->formatLineEnd($this->_line++).$feed[0].$this->formatLineStart($this->_line); |
54
|
6 |
|
}, $content) : $content; |
55
|
|
|
} |
56
|
|
|
|
57
|
2 |
|
protected function content($text) |
58
|
|
|
{ |
59
|
2 |
|
return $text; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
protected function formatLineStart($line) |
63
|
|
|
{ |
64
|
|
|
return null; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
protected function formatLineEnd($line) |
|
|
|
|
68
|
|
|
{ |
69
|
|
|
return null; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
protected abstract function token(Token $token); |
73
|
|
|
} |
This check looks from parameters that have been defined for a function or method, but which are not used in the method body.