1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Kevintweber\HtmlTokenizer\Tokens; |
4
|
|
|
|
5
|
|
|
use Kevintweber\HtmlTokenizer\HtmlTokenizer; |
6
|
|
|
|
7
|
|
|
class Text extends AbstractToken |
8
|
|
|
{ |
9
|
|
|
public function __construct(Token $parent = null, bool $throwOnError = true, string $forcedValue = '') |
10
|
|
|
{ |
11
|
|
|
parent::__construct(Token::TEXT, $parent, $throwOnError); |
12
|
|
|
|
13
|
|
|
$this->value = $forcedValue; |
14
|
|
|
} |
15
|
|
|
|
16
|
|
|
public function parse(string $html) : string |
17
|
|
|
{ |
18
|
|
|
// Get token position. |
19
|
|
|
$positionArray = HtmlTokenizer::getPosition($html); |
20
|
|
|
$this->line = $positionArray['line']; |
21
|
|
|
$this->position = $positionArray['position']; |
22
|
|
|
|
23
|
|
|
// Collapse whitespace before TEXT. |
24
|
|
|
$startingWhitespace = ''; |
25
|
|
|
if (preg_match("/(^\s)/", $html) === 1) { |
26
|
|
|
$startingWhitespace = ' '; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
$posOfNextElement = mb_strpos($html, '<'); |
30
|
|
|
if ($posOfNextElement === false) { |
31
|
|
|
$this->value = $startingWhitespace . trim($html); |
32
|
|
|
|
33
|
|
|
return ''; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
// Find full length of TEXT. |
37
|
|
|
$text = mb_substr($html, 0, $posOfNextElement); |
38
|
|
|
if (trim($text) == '') { |
39
|
|
|
$this->value = ' '; |
40
|
|
|
|
41
|
|
|
return mb_substr($html, $posOfNextElement); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
// Collapse whitespace after TEXT. |
45
|
|
|
$endingWhitespace = ''; |
46
|
|
|
if (preg_match("/(\s$)/", $text) === 1) { |
47
|
|
|
$endingWhitespace = ' '; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
$this->value = $startingWhitespace . trim($text) . $endingWhitespace; |
51
|
|
|
|
52
|
|
|
return mb_substr($html, $posOfNextElement); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
public function toArray() : array |
56
|
|
|
{ |
57
|
|
|
return array( |
58
|
|
|
'type' => 'text', |
59
|
|
|
'value' => $this->value, |
60
|
|
|
'line' => $this->getLine(), |
61
|
|
|
'position' => $this->getPosition() |
62
|
|
|
); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
|