Completed
Push — master ( 8f8c09...4c5ae0 )
by Kacper
03:01
created

HtmlFormatter::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 1
dl 0
loc 10
ccs 7
cts 7
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
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 implements FormatterInterface
27
{
28
    protected $_prefix = '';
29
    protected $_tag    = 'span';
30
31
    /**
32
     * HtmlFormatter constructor.
33
     *
34
     * @param array $options
35
     */
36 4
    public function __construct($options = [])
0 ignored issues
show
Unused Code introduced by
The parameter $options is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
37
    {
38 4
        $options = array_merge([
39 4
            'prefix' => null,
40
            'tag'    => 'span'
41 4
        ]);
42
43 4
        $this->_tag = $options['tag'];
44 4
        $this->_prefix = $options['prefix'];
45 4
    }
46
47
48 4
    public function format(Tokens $tokens)
49
    {
50 4
        $source = $tokens->getSource();
51
52 4
        $result = '';
53 4
        $last   = 0;
54
55
        /** @var Token $token */
56 4
        foreach ($tokens as $token) {
57 4
            $result .= htmlspecialchars(substr($source, $last, $token->pos - $last));
58 4
            $result .= $token->isStart() ? $this->getOpenTag($token) : $this->getCloseTag();
59
60 4
            $last = $token->pos;
61 4
        }
62 4
        $result .= substr($source, $last);
63
64 4
        return $result;
65
    }
66
67 4
    protected function getOpenTag(Token $token) {
68 4
        return sprintf(
69 4
            '<%s class="%s">',
70 4
            $this->_tag, $this->_prefix.str_replace('.', " {$this->_prefix}", $token->name)
71 4
        );
72
    }
73
74 4
    protected function getCloseTag() {
75 4
        return "</{$this->_tag}>";
76
    }
77
}
78