Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"keywords": ["twig extension", "truncate", "twig"],
"type": "library",
"require": {
"php": ">=5.3.0",
"php": ">=5.4.0",
"antoligy/dom-string-iterators": "v1.0.0",
"twig/twig": ">=v1.0.0"
},
Expand Down
17 changes: 5 additions & 12 deletions src/TruncateExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,8 @@ public function truncateWords($html, $limit = 0, $ellipsis = "")

$dom = $this->htmlToDomDocument($html);

// Grab the body of our DOM.
$body = $dom->getElementsByTagName("body")->item(0);

// Iterate over words.
$words = new DOMWordsIterator($body);
$words = new DOMWordsIterator($dom);
foreach ($words as $word) {

// If we have exceeded the limit, we delete the remainder of the content.
Expand All @@ -80,15 +77,14 @@ public function truncateWords($html, $limit = 0, $ellipsis = "")
$words[$offset][1] + strlen($words[$offset][0])
);

self::removeProceedingNodes($curNode, $body);
self::removeProceedingNodes($curNode, $dom);

if (!empty($ellipsis)) {
self::insertEllipsis($curNode, $ellipsis);
}

break;
}

}

return $dom->saveHTML();
Expand All @@ -109,19 +105,16 @@ public function truncateLetters($html, $limit = 0, $ellipsis = "")

$dom = $this->htmlToDomDocument($html);

// Grab the body of our DOM.
$body = $dom->getElementsByTagName("body")->item(0);

// Iterate over letters.
$letters = new DOMLettersIterator($body);
$letters = new DOMLettersIterator($dom);
foreach ($letters as $letter) {

// If we have exceeded the limit, we want to delete the remainder of this document.
if ($letters->key() >= $limit) {

$currentText = $letters->currentTextPosition();
$currentText[0]->nodeValue = substr($currentText[0]->nodeValue, 0, $currentText[1] + 1);
self::removeProceedingNodes($currentText[0], $body);
self::removeProceedingNodes($currentText[0], $dom);

if (!empty($ellipsis)) {
self::insertEllipsis($currentText[0], $ellipsis);
Expand Down Expand Up @@ -150,7 +143,7 @@ public function htmlToDomDocument($html)
// Instantiate new DOMDocument object, and then load in UTF-8 HTML.
$dom = new DOMDocument();
$dom->encoding = 'UTF-8';
$dom->loadHTML($html);
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

return $dom;
}
Expand Down