protected _highlightTextNode ( DOMText $node, array $wordsToHighlight, callback $callback, array $params ) | ||
$node | DOMText | |
$wordsToHighlight | array | |
$callback | callback | Callback method, used to transform (highlighting) text. |
$params | array | Array of additionall callback parameters (first non-optional parameter is a text to transform) |
protected function _highlightTextNode(DOMText $node, $wordsToHighlight, $callback, $params)
{
/** Zend_Search_Lucene_Analysis_Analyzer */
require_once 'Zend/Search/Lucene/Analysis/Analyzer.php';
$analyzer = Zend_Search_Lucene_Analysis_Analyzer::getDefault();
$analyzer->setInput($node->nodeValue, 'UTF-8');
$matchedTokens = [];
while (($token = $analyzer->nextToken()) !== null) {
if (isset($wordsToHighlight[$token->getTermText()])) {
$matchedTokens[] = $token;
}
}
if (count($matchedTokens) == 0) {
return;
}
$matchedTokens = array_reverse($matchedTokens);
foreach ($matchedTokens as $token) {
// Cut text after matched token
$node->splitText($token->getEndOffset());
// Cut matched node
$matchedWordNode = $node->splitText($token->getStartOffset());
// Retrieve HTML string representation for highlihted word
$fullCallbackparamsList = $params;
array_unshift($fullCallbackparamsList, $matchedWordNode->nodeValue);
$highlightedWordNodeSetHtml = call_user_func_array($callback, $fullCallbackparamsList);
// Transform HTML string to a DOM representation and automatically transform retrieved string
// into valid XHTML (It's automatically done by loadHTML() method)
$highlightedWordNodeSetDomDocument = new DOMDocument('1.0', 'UTF-8');
$success = @$highlightedWordNodeSetDomDocument->loadHTML('<html><head><meta http-equiv="Content-type" content="text/html; charset=UTF-8"/></head><body>' . $highlightedWordNodeSetHtml . '</body></html>');
if (!$success) {
require_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception("Error occured while loading highlighted text fragment: '{$highlightedWordNodeSetHtml}'.");
}
$highlightedWordNodeSetXpath = new DOMXPath($highlightedWordNodeSetDomDocument);
$highlightedWordNodeSet = $highlightedWordNodeSetXpath->query('/html/body')->item(0)->childNodes;
for ($count = 0; $count < $highlightedWordNodeSet->length; $count++) {
$nodeToImport = $highlightedWordNodeSet->item($count);
$node->parentNode->insertBefore($this->_doc->importNode($nodeToImport, true), $matchedWordNode);
}
$node->parentNode->removeChild($matchedWordNode);
}
}