Completed
Push — master ( 01815b...4ed43a )
by Kevin
02:20
created

Text::parse()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 33
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 5

Importance

Changes 4
Bugs 0 Features 2
Metric Value
c 4
b 0
f 2
dl 0
loc 33
ccs 19
cts 19
cp 1
rs 8.439
cc 5
eloc 17
nc 8
nop 1
crap 5
1
<?php
2
3
namespace Kevintweber\HtmlTokenizer\Tokens;
4
5
class Text extends AbstractToken
6
{
7
    /** @var string */
8
    private $value;
9
10 23
    public function __construct(Token $parent = null, $throwOnError = false, $forcedValue = null)
11
    {
12 23
        parent::__construct(Token::TEXT, $parent, $throwOnError);
13
14 23
        $this->value = $forcedValue;
15 23
    }
16
17 17
    public function parse($html)
18
    {
19
        // Collapse whitespace before TEXT.
20 17
        $startingWhitespace = '';
21 17
        if (preg_match("/(^\s)/", $html) === 1) {
22 5
            $startingWhitespace = ' ';
23 5
        }
24
25 17
        $posOfNextElement = mb_strpos($html, '<');
26 17
        if ($posOfNextElement === false) {
27 3
            $this->value = $startingWhitespace . trim($html);
28
29 3
            return '';
30
        }
31
32
        // Find full length of TEXT.
33 14
        $text = mb_substr($html, 0, $posOfNextElement);
34 14
        if (trim($text) == '') {
35 2
            $this->value = ' ';
36
37 2
            return mb_substr($html, $posOfNextElement);
38
        }
39
40
        // Collapse whitespace after TEXT.
41 13
        $endingWhitespace = '';
42 13
        if (preg_match("/(\s$)/", $text) === 1) {
43 5
            $endingWhitespace = ' ';
44 5
        }
45
46 13
        $this->value = $startingWhitespace . trim($text) . $endingWhitespace;
47
48 13
        return mb_substr($html, $posOfNextElement);
49
    }
50
51
    /**
52
     * Getter for 'value'.
53
     *
54
     * @return string
55
     */
56 14
    public function getValue()
57
    {
58 14
        return $this->value;
59
    }
60
61 11
    public function toArray()
62
    {
63
        return array(
64 11
            'type' => 'text',
65 11
            'value' => $this->value
66 11
        );
67
    }
68
}
69
70