BUGFIX: Only highlight strings more than 2 characters long. #4949

git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/branches/2.4@107423 467b73ca-7a2a-4603-9d3b-597d59a354a9
This commit is contained in:
Will Rossiter 2010-07-02 03:01:02 +00:00 committed by Sam Minnee
parent 6c7349a2d8
commit 7e30018e8d
2 changed files with 26 additions and 1 deletions

View File

@ -272,6 +272,7 @@ class Text extends StringField {
* @return string
*/
function ContextSummary($characters = 500, $string = false, $striphtml = true, $highlight = true, $prefix = "... ", $suffix = "...") {
if(!$string) $string = $_REQUEST['Search']; // Use the default "Search" request variable (from SearchForm)
// Remove HTML tags so we don't have to deal with matching tags
@ -294,8 +295,11 @@ class Text extends StringField {
if($highlight) {
// Add a span around all key words from the search term as well
if($stringPieces) {
foreach($stringPieces as $stringPiece) {
$summary = str_ireplace($stringPiece, "<span class=\"highlight\">$stringPiece</span>", $summary);
if(strlen($stringPiece) > 2) {
$summary = str_ireplace($stringPiece, "<span class=\"highlight\">$stringPiece</span>", $summary);
}
}
}
}

View File

@ -107,8 +107,14 @@ class TextTest extends SapphireTest {
function testContextSummary() {
$testString1 = '<p>This is some text. It is a test</p>';
$testKeywords1 = 'test';
$testString2 = '<p>This is some test text. Test test what if you have multiple keywords.</p>';
$testKeywords2 = 'some test';
$testString3 = '<p>A dog ate a cat while looking at a Foobar</p>';
$testKeyword3 = 'a';
$testKeyword3a = 'ate';
$textObj = DBField::create('Text', $testString1, 'Text');
$this->assertEquals(
@ -122,5 +128,20 @@ class TextTest extends SapphireTest {
'This is <span class="highlight">some</span> <span class="highlight">test</span> text. <span class="highlight">test</span> <span class="highlight">test</span> what if you have...',
$textObj->ContextSummary(50, $testKeywords2)
);
$textObj->setValue($testString3);
// test that it does not highlight too much (eg every a)
$this->assertEquals(
'A dog ate a cat while looking at a Foobar',
$textObj->ContextSummary(100, $testKeyword3)
);
// it should highlight 3 letters or more.
$this->assertEquals(
'A dog <span class="highlight">ate</span> a cat while looking at a Foobar',
$textObj->ContextSummary(100, $testKeyword3a)
);
}
}