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