Completed
Push — master ( d33e5b...3f874e )
by Kacper
03:31
created

LineContainedHtmlFormatter::format()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 30
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 3
eloc 18
nc 3
nop 1
dl 0
loc 30
ccs 0
cts 20
cp 0
crap 12
rs 8.8571
c 1
b 0
f 1
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
class LineContainedHtmlFormatter extends HtmlFormatter implements FormatterInterface
11
{
12
    public function format(Tokens $tokens)
13
    {
14
        $source = $tokens->getSource();
15
16
        $result = '';
17
        $last   = 0;
18
19
        $stack = [];
20
21
        /** @var Token $token */
22
        foreach ($tokens as $token) {
23
            $result .= str_replace(
24
                ["\n", "\r\n"],
25
                str_repeat($this->getCloseTag(), count($stack))."\n".implode('', $stack),
26
                htmlspecialchars(substr($source, $last, $token->pos - $last))
27
            );
28
29
            if($token->isStart()) {
30
                $result .= $stack[] = $this->getOpenTag($token);
31
            } else {
32
                array_pop($stack);
33
                $result .= $this->getCloseTag();
34
            }
35
36
            $last = $token->pos;
37
        }
38
        $result .= substr($source, $last);
39
40
        return $result;
41
    }
42
}