Skip to content

Commit 2bf24d7

Browse files
committed
Added some basic caching of the dom html
1 parent fbab2e1 commit 2bf24d7

File tree

1 file changed

+51
-1
lines changed

1 file changed

+51
-1
lines changed

src/PHPHtmlParser/Dom/HtmlNode.php

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,25 @@
33

44
class HtmlNode extends Node {
55

6+
/**
7+
* Remembers what the innerHtml was if it was scaned previously.
8+
*/
9+
protected $innerHtml = null;
10+
11+
/**
12+
* Remembers what the outerHtml was if it was scaned previously.
13+
*
14+
* @var string
15+
*/
16+
protected $outerHtml = null;
17+
18+
/**
19+
* Remembers what the text was if it was scaned previously.
20+
*
21+
* @var string
22+
*/
23+
protected $text = null;
24+
625
/**
726
* Sets up the tag of this node.
827
*/
@@ -29,6 +48,12 @@ public function innerHtml()
2948
return '';
3049
}
3150

51+
if ( ! is_null($this->innerHtml))
52+
{
53+
// we already know the result.
54+
return $this->innerHtml;
55+
}
56+
3257
$child = $this->firstChild();
3358
$string = '';
3459

@@ -59,6 +84,9 @@ public function innerHtml()
5984
}
6085
}
6186

87+
// remember the results
88+
$this->innerHtml = $string;
89+
6290
return $string;
6391
}
6492

@@ -76,6 +104,12 @@ public function outerHtml()
76104
return $this->innerHtml();
77105
}
78106

107+
if ( ! is_null($this->outerHtml))
108+
{
109+
// we already know the results.
110+
return $this->outerHtml;
111+
}
112+
79113
$return = $this->tag->makeOpeningTag();
80114
if ($this->tag->isSelfClosing())
81115
{
@@ -89,6 +123,9 @@ public function outerHtml()
89123
// add closing tag
90124
$return .= $this->tag->makeClosingTag();
91125

126+
// remember the results
127+
$this->outerHtml = $return;
128+
92129
return $return;
93130
}
94131

@@ -99,17 +136,30 @@ public function outerHtml()
99136
*/
100137
public function text()
101138
{
139+
if ( ! is_null($this->text))
140+
{
141+
// we already know the results.
142+
return $this->text;
143+
}
144+
102145
// find out if this node has any text children
103146
foreach ($this->children as $child)
104147
{
105148
if ($child['node'] instanceof TextNode)
106149
{
107150
// we found a text node
108-
return $child['node']->text();
151+
$text = $child['node']->text();
152+
153+
// remember the results
154+
$this->text = $text;
155+
156+
return $text;
109157
}
110158
}
111159

112160
// no text found in this node
161+
$this->text = '';
162+
113163
return '';
114164
}
115165
}

0 commit comments

Comments
 (0)